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
89b3d38fea61ecf9b6fae98464bc9217f44b2727
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Server/Utils.lean
7b929a9374a62254bf844663174e69e3578860f9
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,309
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.Data.Position import Lean.Data.Lsp import Init.System.FilePath namespace IO def throwServerError (err : String) : IO α := throw (userError err) namespace FS.Stream /-- Chains two streams by creating a new stream s.t. writing to it just writes to `a` but reading from it also duplicates the read output into `b`, c.f. `a | tee b` on Unix. NB: if `a` is written to but this stream is never read from, the output will *not* be duplicated. Use this if you only care about the data that was actually read. -/ def chainRight (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { a with flush := a.flush *> b.flush read := fun sz => do let bs ← a.read sz b.write bs when flushEagerly b.flush pure bs getLine := do let ln ← a.getLine b.putStr ln when flushEagerly b.flush pure ln } /-- Like `tee a | b` on Unix. See `chainOut`. -/ def chainLeft (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { b with flush := a.flush *> b.flush write := fun bs => do a.write bs when flushEagerly a.flush b.write bs putStr := fun s => do a.putStr s when flushEagerly a.flush b.putStr s } /-- Prefixes all written outputs with `pre`. -/ def withPrefix (a : Stream) (pre : String) : Stream := { a with write := fun bs => do a.putStr pre a.write bs putStr := fun s => a.putStr (pre ++ s) } end FS.Stream end IO namespace Lean.Server structure DocumentMeta where uri : Lsp.DocumentUri version : Nat text : FileMap deriving Inhabited def replaceLspRange (text : FileMap) (r : Lsp.Range) (newText : String) : FileMap := let start := text.lspPosToUtf8Pos r.start let «end» := text.lspPosToUtf8Pos r.«end» let pre := text.source.extract 0 start let post := text.source.extract «end» text.source.bsize (pre ++ newText ++ post).toFileMap open IO /-- Duplicates an I/O stream to a log file `fName` in LEAN_SERVER_LOG_DIR if that envvar is set. -/ def maybeTee (fName : String) (isOut : Bool) (h : FS.Stream) : IO FS.Stream := do match (← IO.getEnv "LEAN_SERVER_LOG_DIR") with | none => pure h | some logDir => let hTee ← FS.Handle.mk (System.mkFilePath [logDir, fName]) FS.Mode.write true let hTee := FS.Stream.ofHandle hTee pure $ if isOut then hTee.chainLeft h true else h.chainRight hTee true /-- Transform the given path to a file:// URI. -/ def toFileUri (fname : String) : Lsp.DocumentUri := let fname := System.FilePath.normalizePath fname let fname := if System.Platform.isWindows then fname.map fun c => if c == '\\' then '/' else c else fname -- TODO(WN): URL-encode special characters -- Three slashes denote localhost. "file:///" ++ fname.dropWhile (· == '/') open Lsp /-- Returns the document contents with all changes applied, together with the position of the change which lands earliest in the file. Panics if there are no changes. -/ def foldDocumentChanges (changes : @& Array Lsp.TextDocumentContentChangeEvent) (oldText : FileMap) : FileMap × String.Pos := if changes.isEmpty then panic! "Lean.Server.foldDocumentChanges: empty change array" else let accumulateChanges : FileMap × String.Pos → TextDocumentContentChangeEvent → FileMap × String.Pos := fun ⟨newDocText, minStartOff⟩ change => match change with | TextDocumentContentChangeEvent.rangeChange (range : Range) (newText : String) => let startOff := oldText.lspPosToUtf8Pos range.start let newDocText := replaceLspRange newDocText range newText let minStartOff := minStartOff.min startOff ⟨newDocText, minStartOff⟩ | TextDocumentContentChangeEvent.fullChange (newText : String) => ⟨newText.toFileMap, 0⟩ -- NOTE: We assume Lean files are below 16 EiB. changes.foldl accumulateChanges (oldText, 0xffffffff) end Lean.Server namespace List universe u def takeWhile (p : α → Bool) : List α → List α | [] => [] | hd :: tl => if p hd then hd :: takeWhile p tl else [] end List
91c5f6079eaca6ffd113faae450c746003406cf0
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/test/apply_fun.lean
20e4e0551be27282ab049a297c5eb8960069cd57
[ "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,198
lean
import tactic.apply_fun import data.matrix.basic open function example (X Y Z : Type) (f : X → Y) (g : Y → Z) (H : injective $ g ∘ f) : injective f := begin intros x x' h, apply_fun g at h, exact H h end example (f : ℕ → ℕ) (a b : ℕ) (monof : monotone f) (h : a ≤ b) : f a ≤ f b := begin apply_fun f at h, assumption, assumption end example (a b : ℤ) (h : a = b) : a + 1 = b + 1 := begin apply_fun (λ n, n+1) at h, -- check that `h` was β-reduced guard_hyp' h := a + 1 = b + 1, exact h end example (f : ℕ → ℕ) (a b : ℕ) (monof : monotone f) (h : a ≤ b) : f a ≤ f b := begin apply_fun f at h using monof, assumption end -- monotonicity will be proved by `mono` in the next example example (a b : ℕ) (h : a ≤ b) : a + 1 ≤ b + 1 := begin apply_fun (λ n, n+1) at h, exact h end example {n : Type} [fintype n] {X : Type} [semiring X] (f : matrix n n X → matrix n n X) (A B : matrix n n X) (h : A * B = 0) : f (A * B) = f 0 := begin apply_fun f at h, -- check that our β-reduction didn't mess things up: -- (previously `apply_fun` was producing `f (A.mul B) = f 0`) guard_hyp' h := f (A * B) = f 0, exact h, end
866ea946408a06872f199a377410253325ca163d
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Parser/Extension.lean
d983ee15f9f18dcfdaf3190607745b9ac7e40282
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
31,630
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Basic import Lean.Compiler.InitAttr import Lean.ScopedEnvExtension import Lean.DocString /-! Extensible parsing via attributes -/ namespace Lean namespace Parser builtin_initialize builtinTokenTable : IO.Ref TokenTable ← IO.mkRef {} /- Global table with all SyntaxNodeKind's -/ builtin_initialize builtinSyntaxNodeKindSetRef : IO.Ref SyntaxNodeKindSet ← IO.mkRef {} def registerBuiltinNodeKind (k : SyntaxNodeKind) : IO Unit := builtinSyntaxNodeKindSetRef.modify fun s => s.insert k builtin_initialize registerBuiltinNodeKind choiceKind registerBuiltinNodeKind identKind registerBuiltinNodeKind strLitKind registerBuiltinNodeKind numLitKind registerBuiltinNodeKind scientificLitKind registerBuiltinNodeKind charLitKind registerBuiltinNodeKind nameLitKind builtin_initialize builtinParserCategoriesRef : IO.Ref ParserCategories ← IO.mkRef {} private def throwParserCategoryAlreadyDefined {α} (catName : Name) : ExceptT String Id α := throw s!"parser category '{catName}' has already been defined" private def addParserCategoryCore (categories : ParserCategories) (catName : Name) (initial : ParserCategory) : Except String ParserCategories := if categories.contains catName then throwParserCategoryAlreadyDefined catName else pure $ categories.insert catName initial /-- All builtin parser categories are Pratt's parsers -/ private def addBuiltinParserCategory (catName declName : Name) (behavior : LeadingIdentBehavior) : IO Unit := do let categories ← builtinParserCategoriesRef.get let categories ← IO.ofExcept $ addParserCategoryCore categories catName { declName, behavior } builtinParserCategoriesRef.set categories namespace ParserExtension inductive OLeanEntry where | token (val : Token) : OLeanEntry | kind (val : SyntaxNodeKind) : OLeanEntry | category (catName : Name) (declName : Name) (behavior : LeadingIdentBehavior) | parser (catName : Name) (declName : Name) (prio : Nat) : OLeanEntry deriving Inhabited inductive Entry where | token (val : Token) : Entry | kind (val : SyntaxNodeKind) : Entry | category (catName : Name) (declName : Name) (behavior : LeadingIdentBehavior) | parser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Entry deriving Inhabited def Entry.toOLeanEntry : Entry → OLeanEntry | token v => OLeanEntry.token v | kind v => OLeanEntry.kind v | category c d b => OLeanEntry.category c d b | parser c d _ _ prio => OLeanEntry.parser c d prio structure State where tokens : TokenTable := {} kinds : SyntaxNodeKindSet := {} categories : ParserCategories := {} deriving Inhabited end ParserExtension open ParserExtension in abbrev ParserExtension := ScopedEnvExtension OLeanEntry Entry State private def ParserExtension.mkInitial : IO ParserExtension.State := do let tokens ← builtinTokenTable.get let kinds ← builtinSyntaxNodeKindSetRef.get let categories ← builtinParserCategoriesRef.get pure { tokens := tokens, kinds := kinds, categories := categories } private def addTokenConfig (tokens : TokenTable) (tk : Token) : Except String TokenTable := do if tk == "" then throw "invalid empty symbol" else match tokens.find? tk with | none => pure $ tokens.insert tk tk | some _ => pure tokens def throwUnknownParserCategory {α} (catName : Name) : ExceptT String Id α := throw s!"unknown parser category '{catName}'" abbrev getCategory (categories : ParserCategories) (catName : Name) : Option ParserCategory := categories.find? catName def addLeadingParser (categories : ParserCategories) (catName declName : Name) (p : Parser) (prio : Nat) : Except String ParserCategories := match getCategory categories catName with | none => throwUnknownParserCategory catName | some cat => let kinds := cat.kinds.insert declName let addTokens (tks : List Token) : Except String ParserCategories := let tks := tks.map Name.mkSimple let tables := tks.eraseDups.foldl (init := cat.tables) fun tables tk => { tables with leadingTable := tables.leadingTable.insert tk (p, prio) } pure $ categories.insert catName { cat with kinds, tables } match p.info.firstTokens with | FirstTokens.tokens tks => addTokens tks | FirstTokens.optTokens tks => addTokens tks | _ => let tables := { cat.tables with leadingParsers := (p, prio) :: cat.tables.leadingParsers } pure $ categories.insert catName { cat with kinds, tables } private def addTrailingParserAux (tables : PrattParsingTables) (p : TrailingParser) (prio : Nat) : PrattParsingTables := let addTokens (tks : List Token) : PrattParsingTables := let tks := tks.map fun tk => Name.mkSimple tk tks.eraseDups.foldl (init := tables) fun tables tk => { tables with trailingTable := tables.trailingTable.insert tk (p, prio) } match p.info.firstTokens with | FirstTokens.tokens tks => addTokens tks | FirstTokens.optTokens tks => addTokens tks | _ => { tables with trailingParsers := (p, prio) :: tables.trailingParsers } def addTrailingParser (categories : ParserCategories) (catName declName : Name) (p : TrailingParser) (prio : Nat) : Except String ParserCategories := match getCategory categories catName with | none => throwUnknownParserCategory catName | some cat => let kinds := cat.kinds.insert declName let tables := addTrailingParserAux cat.tables p prio pure $ categories.insert catName { cat with kinds, tables } def addParser (categories : ParserCategories) (catName declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Except String ParserCategories := do match leading, p with | true, p => addLeadingParser categories catName declName p prio | false, p => addTrailingParser categories catName declName p prio def addParserTokens (tokenTable : TokenTable) (info : ParserInfo) : Except String TokenTable := let newTokens := info.collectTokens [] newTokens.foldlM addTokenConfig tokenTable private def updateBuiltinTokens (info : ParserInfo) (declName : Name) : IO Unit := do let tokenTable ← builtinTokenTable.swap {} match addParserTokens tokenTable info with | Except.ok tokenTable => builtinTokenTable.set tokenTable | Except.error msg => throw (IO.userError s!"invalid builtin parser '{declName}', {msg}") def ParserExtension.addEntryImpl (s : State) (e : Entry) : State := match e with | Entry.token tk => match addTokenConfig s.tokens tk with | Except.ok tokens => { s with tokens } | _ => unreachable! | Entry.kind k => { s with kinds := s.kinds.insert k } | Entry.category catName declName behavior => if s.categories.contains catName then s else { s with categories := s.categories.insert catName { declName, behavior } } | Entry.parser catName declName leading parser prio => match addParser s.categories catName declName leading parser prio with | Except.ok categories => { s with categories } | _ => unreachable! /-- Parser aliases for making `ParserDescr` extensible -/ inductive AliasValue (α : Type) where | const (p : α) | unary (p : α → α) | binary (p : α → α → α) abbrev AliasTable (α) := NameMap (AliasValue α) def registerAliasCore {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) (value : AliasValue α) : IO Unit := do unless (← IO.initializing) do throw ↑"aliases can only be registered during initialization" if (← mapRef.get).contains aliasName then throw ↑s!"alias '{aliasName}' has already been declared" mapRef.modify (·.insert aliasName value) def getAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (Option (AliasValue α)) := do return (← mapRef.get).find? aliasName def getConstAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO α := do match (← getAlias mapRef aliasName) with | some (AliasValue.const v) => pure v | some (AliasValue.unary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes one argument" | some (AliasValue.binary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes two arguments" | none => throw ↑s!"parser '{aliasName}' was not found" def getUnaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α) := do match (← getAlias mapRef aliasName) with | some (AliasValue.unary v) => pure v | some _ => throw ↑s!"parser '{aliasName}' does not take one argument" | none => throw ↑s!"parser '{aliasName}' was not found" def getBinaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α → α) := do match (← getAlias mapRef aliasName) with | some (AliasValue.binary v) => pure v | some _ => throw ↑s!"parser '{aliasName}' does not take two arguments" | none => throw ↑s!"parser '{aliasName}' was not found" abbrev ParserAliasValue := AliasValue Parser structure ParserAliasInfo where declName : Name := .anonymous /-- Number of syntax nodes produced by this parser. `none` means "sum of input sizes". -/ stackSz? : Option Nat := some 1 /-- Whether arguments should be wrapped in `group(·)` if they do not produce exactly one syntax node. -/ autoGroupArgs : Bool := stackSz?.isSome builtin_initialize parserAliasesRef : IO.Ref (NameMap ParserAliasValue) ← IO.mkRef {} builtin_initialize parserAlias2kindRef : IO.Ref (NameMap SyntaxNodeKind) ← IO.mkRef {} builtin_initialize parserAliases2infoRef : IO.Ref (NameMap ParserAliasInfo) ← IO.mkRef {} def getParserAliasInfo (aliasName : Name) : IO ParserAliasInfo := do return (← parserAliases2infoRef.get).findD aliasName {} -- Later, we define macro `register_parser_alias` which registers a parser, formatter and parenthesizer def registerAlias (aliasName declName : Name) (p : ParserAliasValue) (kind? : Option SyntaxNodeKind := none) (info : ParserAliasInfo := {}) : IO Unit := do registerAliasCore parserAliasesRef aliasName p if let some kind := kind? then parserAlias2kindRef.modify (·.insert aliasName kind) parserAliases2infoRef.modify (·.insert aliasName { info with declName }) instance : Coe Parser ParserAliasValue := { coe := AliasValue.const } instance : Coe (Parser → Parser) ParserAliasValue := { coe := AliasValue.unary } instance : Coe (Parser → Parser → Parser) ParserAliasValue := { coe := AliasValue.binary } def isParserAlias (aliasName : Name) : IO Bool := do match (← getAlias parserAliasesRef aliasName) with | some _ => pure true | _ => pure false def getSyntaxKindOfParserAlias? (aliasName : Name) : IO (Option SyntaxNodeKind) := return (← parserAlias2kindRef.get).find? aliasName def ensureUnaryParserAlias (aliasName : Name) : IO Unit := discard $ getUnaryAlias parserAliasesRef aliasName def ensureBinaryParserAlias (aliasName : Name) : IO Unit := discard $ getBinaryAlias parserAliasesRef aliasName def ensureConstantParserAlias (aliasName : Name) : IO Unit := discard $ getConstAlias parserAliasesRef aliasName unsafe def mkParserOfConstantUnsafe (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser) := do let env := (← read).env let opts := (← read).opts match env.find? constName with | none => throw ↑s!"unknown constant '{constName}'" | some info => match info.type with | Expr.const `Lean.Parser.TrailingParser _ => let p ← IO.ofExcept $ env.evalConst Parser opts constName pure ⟨false, p⟩ | Expr.const `Lean.Parser.Parser _ => let p ← IO.ofExcept $ env.evalConst Parser opts constName pure ⟨true, p⟩ | Expr.const `Lean.ParserDescr _ => let d ← IO.ofExcept $ env.evalConst ParserDescr opts constName let p ← compileParserDescr d pure ⟨true, p⟩ | Expr.const `Lean.TrailingParserDescr _ => let d ← IO.ofExcept $ env.evalConst TrailingParserDescr opts constName let p ← compileParserDescr d pure ⟨false, p⟩ | _ => throw ↑s!"unexpected parser type at '{constName}' (`ParserDescr`, `TrailingParserDescr`, `Parser` or `TrailingParser` expected)" @[implementedBy mkParserOfConstantUnsafe] opaque mkParserOfConstantAux (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser) partial def compileParserDescr (categories : ParserCategories) (d : ParserDescr) : ImportM Parser := let rec visit : ParserDescr → ImportM Parser | ParserDescr.const n => getConstAlias parserAliasesRef n | ParserDescr.unary n d => return (← getUnaryAlias parserAliasesRef n) (← visit d) | ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias parserAliasesRef n) (← visit d₁) (← visit d₂) | ParserDescr.node k prec d => return leadingNode k prec (← visit d) | ParserDescr.nodeWithAntiquot n k d => return nodeWithAntiquot n k (← visit d) (anonymous := true) | ParserDescr.sepBy p sep psep trail => return sepBy (← visit p) sep (← visit psep) trail | ParserDescr.sepBy1 p sep psep trail => return sepBy1 (← visit p) sep (← visit psep) trail | ParserDescr.trailingNode k prec lhsPrec d => return trailingNode k prec lhsPrec (← visit d) | ParserDescr.symbol tk => return symbol tk | ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol tk includeIdent | ParserDescr.parser constName => do let (_, p) ← mkParserOfConstantAux constName visit; pure p | ParserDescr.cat catName prec => match getCategory categories catName with | some _ => pure $ categoryParser catName prec | none => IO.ofExcept $ throwUnknownParserCategory catName visit d def mkParserOfConstant (categories : ParserCategories) (constName : Name) : ImportM (Bool × Parser) := mkParserOfConstantAux constName (compileParserDescr categories) structure ParserAttributeHook where /-- Called after a parser attribute is applied to a declaration. -/ postAdd (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit builtin_initialize parserAttributeHooks : IO.Ref (List ParserAttributeHook) ← IO.mkRef {} def registerParserAttributeHook (hook : ParserAttributeHook) : IO Unit := do parserAttributeHooks.modify fun hooks => hook::hooks def runParserAttributeHooks (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit := do let hooks ← parserAttributeHooks.get hooks.forM fun hook => hook.postAdd catName declName builtin builtin_initialize registerBuiltinAttribute { name := `runBuiltinParserAttributeHooks descr := "explicitly run hooks normally activated by builtin parser attributes" add := fun decl stx _ => do Attribute.Builtin.ensureNoArgs stx runParserAttributeHooks Name.anonymous decl (builtin := true) } builtin_initialize registerBuiltinAttribute { name := `runParserAttributeHooks descr := "explicitly run hooks normally activated by parser attributes" add := fun decl stx _ => do Attribute.Builtin.ensureNoArgs stx runParserAttributeHooks Name.anonymous decl (builtin := false) } private def ParserExtension.OLeanEntry.toEntry (s : State) : OLeanEntry → ImportM Entry | token tk => return Entry.token tk | kind k => return Entry.kind k | category c d l => return Entry.category c d l | parser catName declName prio => do let (leading, p) ← mkParserOfConstant s.categories declName return Entry.parser catName declName leading p prio builtin_initialize parserExtension : ParserExtension ← registerScopedEnvExtension { name := `parserExt mkInitial := ParserExtension.mkInitial addEntry := ParserExtension.addEntryImpl toOLeanEntry := ParserExtension.Entry.toOLeanEntry ofOLeanEntry := ParserExtension.OLeanEntry.toEntry } def isParserCategory (env : Environment) (catName : Name) : Bool := (parserExtension.getState env).categories.contains catName def addParserCategory (env : Environment) (catName declName : Name) (behavior : LeadingIdentBehavior) : Except String Environment := do if isParserCategory env catName then throwParserCategoryAlreadyDefined catName else return parserExtension.addEntry env <| ParserExtension.Entry.category catName declName behavior def leadingIdentBehavior (env : Environment) (catName : Name) : LeadingIdentBehavior := match getCategory (parserExtension.getState env).categories catName with | none => LeadingIdentBehavior.default | some cat => cat.behavior unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => unsafeBaseIO do let categories := (parserExtension.getState ctx.env).categories match (← (mkParserOfConstant categories declName { env := ctx.env, opts := ctx.options }).toBaseIO) with | .ok (_, p) => -- We should manually register `p`'s tokens before invoking it as it might not be part of any syntax category (yet) let ctx := { ctx with tokens := p.info.collectTokens [] |>.foldl (fun tks tk => tks.insert tk tk) ctx.tokens } return p.fn ctx s | .error e => return s.mkUnexpectedError e.toString @[implementedBy evalParserConstUnsafe] opaque evalParserConst (declName : Name) : ParserFn register_builtin_option internal.parseQuotWithCurrentStage : Bool := { defValue := false group := "internal" descr := "(Lean bootstrapping) use parsers from the current stage inside quotations" } /-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/ def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with fn := fun c s => if c.quotDepth > 0 && !c.suppressInsideQuot && internal.parseQuotWithCurrentStage.get c.options && c.env.contains declName then evalParserConst declName c s else p.fn c s } def addBuiltinParser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : IO Unit := do let p := evalInsideQuot declName p let categories ← builtinParserCategoriesRef.get let categories ← IO.ofExcept $ addParser categories catName declName leading p prio builtinParserCategoriesRef.set categories builtinSyntaxNodeKindSetRef.modify p.info.collectKinds updateBuiltinTokens p.info declName def addBuiltinLeadingParser (catName : Name) (declName : Name) (p : Parser) (prio : Nat) : IO Unit := addBuiltinParser catName declName true p prio def addBuiltinTrailingParser (catName : Name) (declName : Name) (p : TrailingParser) (prio : Nat) : IO Unit := addBuiltinParser catName declName false p prio def mkCategoryAntiquotParser (kind : Name) : Parser := mkAntiquot kind.toString kind (isPseudoKind := true) -- helper decl to work around inlining issue https://github.com/leanprover/lean4/commit/3f6de2af06dd9a25f62294129f64bc05a29ea912#r41340377 @[inline] private def mkCategoryAntiquotParserFn (kind : Name) : ParserFn := (mkCategoryAntiquotParser kind).fn def categoryParserFnImpl (catName : Name) : ParserFn := fun ctx s => let catName := if catName == `syntax then `stx else catName -- temporary Hack let categories := (parserExtension.getState ctx.env).categories match getCategory categories catName with | some cat => prattParser catName cat.tables cat.behavior (mkCategoryAntiquotParserFn catName) ctx s | none => s.mkUnexpectedError ("unknown parser category '" ++ toString catName ++ "'") builtin_initialize categoryParserFnRef.set categoryParserFnImpl def addToken (tk : Token) (kind : AttributeKind) : AttrM Unit := do -- Recall that `ParserExtension.addEntry` is pure, and assumes `addTokenConfig` does not fail. -- So, we must run it here to handle exception. discard <| ofExcept <| addTokenConfig (parserExtension.getState (← getEnv)).tokens tk parserExtension.add (ParserExtension.Entry.token tk) kind def addSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Environment := parserExtension.addEntry env <| ParserExtension.Entry.kind k def isValidSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Bool := let kinds := (parserExtension.getState env).kinds -- accept any constant in stage 1 (i.e. when compiled by stage 0) so that -- we can add a built-in parser and its elaborator in the same stage kinds.contains k || (Internal.isStage0 () && env.contains k) def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind := let kinds := (parserExtension.getState env).kinds kinds.foldl (fun ks k _ => k::ks) [] def getTokenTable (env : Environment) : TokenTable := (parserExtension.getState env).tokens def mkInputContext (input : String) (fileName : String) : InputContext := { input := input, fileName := fileName, fileMap := input.toFileMap } def mkParserContext (ictx : InputContext) (pmctx : ParserModuleContext) : ParserContext := { prec := 0, toInputContext := ictx, toParserModuleContext := pmctx, tokens := getTokenTable pmctx.env } def mkParserState (input : String) : ParserState := { cache := initCacheForInput input } /-- convenience function for testing -/ def runParserCategory (env : Environment) (catName : Name) (input : String) (fileName := "<input>") : Except String Syntax := let c := mkParserContext (mkInputContext input fileName) { env := env, options := {} } let s := mkParserState input let s := whitespace c s let s := categoryParserFnImpl catName c s if s.hasError then Except.error (s.toErrorMsg c) else if input.atEnd s.pos then Except.ok s.stxStack.back else Except.error ((s.mkError "end of input").toErrorMsg c) def declareBuiltinParser (addFnName : Name) (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit := let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName, mkRawNatLit prio] declareBuiltin declName val def declareLeadingBuiltinParser (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit := declareBuiltinParser `Lean.Parser.addBuiltinLeadingParser catName declName prio def declareTrailingBuiltinParser (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit := declareBuiltinParser `Lean.Parser.addBuiltinTrailingParser catName declName prio def getParserPriority (args : Syntax) : Except String Nat := match args.getNumArgs with | 0 => pure 0 | 1 => match (args.getArg 0).isNatLit? with | some prio => pure prio | none => throw "invalid parser attribute, numeral expected" | _ => throw "invalid parser attribute, no argument or numeral expected" private def BuiltinParserAttribute.add (attrName : Name) (catName : Name) (declName : Name) (stx : Syntax) (kind : AttributeKind) : AttrM Unit := do let prio ← Attribute.Builtin.getPrio stx unless kind == AttributeKind.global do throwError "invalid attribute '{attrName}', must be global" let decl ← getConstInfo declName match decl.type with | Expr.const `Lean.Parser.TrailingParser _ => declareTrailingBuiltinParser catName declName prio | Expr.const `Lean.Parser.Parser _ => declareLeadingBuiltinParser catName declName prio | _ => throwError "unexpected parser type at '{declName}' (`Parser` or `TrailingParser` expected)" if let some doc ← findDocString? (← getEnv) declName (includeBuiltin := false) then declareBuiltin (declName ++ `docString) (mkAppN (mkConst ``addBuiltinDocString) #[toExpr declName, toExpr doc]) if let some declRanges ← findDeclarationRanges? declName then declareBuiltin (declName ++ `declRange) (mkAppN (mkConst ``addBuiltinDeclarationRanges) #[toExpr declName, toExpr declRanges]) runParserAttributeHooks catName declName (builtin := true) /-- The parsing tables for builtin parsers are "stored" in the extracted source code. -/ def registerBuiltinParserAttribute (attrName declName : Name) (behavior := LeadingIdentBehavior.default) : IO Unit := do let .str ``Lean.Parser.Category s := declName | throw (IO.userError "`declName` should be in Lean.Parser.Category") let catName := Name.mkSimple s addBuiltinParserCategory catName declName behavior registerBuiltinAttribute { ref := declName name := attrName descr := "Builtin parser" add := fun declName stx kind => liftM $ BuiltinParserAttribute.add attrName catName declName stx kind applicationTime := AttributeApplicationTime.afterCompilation } private def ParserAttribute.add (_attrName : Name) (catName : Name) (declName : Name) (stx : Syntax) (attrKind : AttributeKind) : AttrM Unit := do let prio ← Attribute.Builtin.getPrio stx let env ← getEnv let categories := (parserExtension.getState env).categories let p ← mkParserOfConstant categories declName let leading := p.1 let parser := p.2 let tokens := parser.info.collectTokens [] tokens.forM fun token => do try addToken token attrKind catch | Exception.error _ msg => throwError "invalid parser '{declName}', {msg}" | ex => throw ex let kinds := parser.info.collectKinds {} kinds.forM fun kind _ => modifyEnv fun env => addSyntaxNodeKind env kind let entry := ParserExtension.Entry.parser catName declName leading parser prio match addParser categories catName declName leading parser prio with | Except.error ex => throwError ex | Except.ok _ => parserExtension.add entry attrKind runParserAttributeHooks catName declName (builtin := false) def mkParserAttributeImpl (attrName catName : Name) (ref : Name := by exact decl_name%) : AttributeImpl where ref := ref name := attrName descr := "parser" add declName stx attrKind := ParserAttribute.add attrName catName declName stx attrKind applicationTime := AttributeApplicationTime.afterCompilation /-- A builtin parser attribute that can be extended by users. -/ def registerBuiltinDynamicParserAttribute (attrName catName : Name) (ref : Name := by exact decl_name%) : IO Unit := do registerBuiltinAttribute (mkParserAttributeImpl attrName catName ref) builtin_initialize registerAttributeImplBuilder `parserAttr fun ref args => match args with | [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName ref | _ => throw "invalid parser attribute implementation builder arguments" def registerParserCategory (env : Environment) (attrName catName : Name) (behavior := LeadingIdentBehavior.default) (ref : Name := by exact decl_name%) : IO Environment := do let env ← IO.ofExcept $ addParserCategory env catName ref behavior registerAttributeOfBuilder env `parserAttr ref [DataValue.ofName attrName, DataValue.ofName catName] -- declare `termParser` here since it is used everywhere via antiquotations builtin_initialize registerBuiltinParserAttribute `builtinTermParser ``Category.term builtin_initialize registerBuiltinDynamicParserAttribute `termParser `term -- declare `commandParser` to break cyclic dependency builtin_initialize registerBuiltinParserAttribute `builtinCommandParser ``Category.command builtin_initialize registerBuiltinDynamicParserAttribute `commandParser `command @[inline] def commandParser (rbp : Nat := 0) : Parser := categoryParser `command rbp private def withNamespaces (ids : Array Name) (p : ParserFn) (addOpenSimple : Bool) : ParserFn := fun c s => let c := ids.foldl (init := c) fun c id => let nss := ResolveName.resolveNamespace c.env c.currNamespace c.openDecls id let (env, openDecls) := nss.foldl (init := (c.env, c.openDecls)) fun (env, openDecls) ns => let openDecls := if addOpenSimple then OpenDecl.simple ns [] :: openDecls else openDecls let env := parserExtension.activateScoped env ns (env, openDecls) { c with env, openDecls } let tokens := parserExtension.getState c.env |>.tokens p { c with tokens } s def withOpenDeclFnCore (openDeclStx : Syntax) (p : ParserFn) : ParserFn := fun c s => if openDeclStx.getKind == `Lean.Parser.Command.openSimple then withNamespaces (openDeclStx[0].getArgs.map fun stx => stx.getId) (addOpenSimple := true) p c s else if openDeclStx.getKind == `Lean.Parser.Command.openScoped then withNamespaces (openDeclStx[1].getArgs.map fun stx => stx.getId) (addOpenSimple := false) p c s else if openDeclStx.getKind == `Lean.Parser.Command.openOnly then -- It does not activate scoped attributes, nor affects namespace resolution p c s else if openDeclStx.getKind == `Lean.Parser.Command.openHiding then -- TODO: it does not activate scoped attributes, but it affects namespaces resolution of open decls parsed by `p`. p c s else p c s /-- If the parsing stack is of the form `#[.., openCommand]`, we process the open command, and execute `p` -/ def withOpenFn (p : ParserFn) : ParserFn := fun c s => if s.stxStack.size > 0 then let stx := s.stxStack.back if stx.getKind == `Lean.Parser.Command.open then withOpenDeclFnCore stx[1] p c s else p c s else p c s @[inline] def withOpen (p : Parser) : Parser := { info := p.info fn := withOpenFn p.fn } /-- If the parsing stack is of the form `#[.., openDecl]`, we process the open declaration, and execute `p` -/ def withOpenDeclFn (p : ParserFn) : ParserFn := fun c s => if s.stxStack.size > 0 then let stx := s.stxStack.back withOpenDeclFnCore stx p c s else p c s @[inline] def withOpenDecl (p : Parser) : Parser := { info := p.info fn := withOpenDeclFn p.fn } def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) := ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id def parserOfStackFn (offset : Nat) : ParserFn := fun ctx s => Id.run do let stack := s.stxStack if stack.size < offset + 1 then return s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small") let Syntax.ident (val := parserName) .. := stack.get! (stack.size - offset - 1) | s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier") match ctx.resolveName parserName with | [(parserName, [])] => let iniSz := s.stackSize let mut ctx' := ctx if !internal.parseQuotWithCurrentStage.get ctx'.options then -- static quotations such as `(e) do not use the interpreter unless the above option is set, -- so for consistency neither should dynamic quotations using this function ctx' := { ctx' with options := ctx'.options.setBool `interpreter.prefer_native true } let s := evalParserConst parserName ctx' s if !s.hasError && s.stackSize != iniSz + 1 then s.mkUnexpectedError "expected parser to return exactly one syntax object" else s | _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}" | _ => s.mkUnexpectedError s!"unknown parser {parserName}" def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => parserOfStackFn offset { c with prec := prec } s } end Parser end Lean
094d9fe3140cc79367e62291ada9fb4050f9be83
d1bbf1801b3dcb214451d48214589f511061da63
/src/tactic/ring.lean
577baad2575f950a4ccf7071979f7f8260d9bae4
[ "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
29,069
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num import data.int.range /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (α : Type) : Type := reader_t cache tactic α /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : ℕ) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m ℕ := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. This version of `ring_m.run` uses an external atoms ref, so that subexpressions can be named across multiple `ring_m` calls. -/ meta def ring_m.run' (red : transparency) (atoms : ref (buffer expr)) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache α, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(ℕ), using_new_ref ic $ λ r, using_new_ref nc $ λ nr, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := using_new_ref mk_buffer $ λ atoms, ring_m.run' red atoms e m /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/ @[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α} (f : instance_cache → tactic (instance_cache × α)) : ring_m α := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `α`. -/ @[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `ℕ`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `ℕ` and `ℚ` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : ℚ) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr → expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr → bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr → string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr → tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ λ nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := ic_lift $ λ ic, do let n := c₁ + c₂, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ e₂ e c₁ c₂ n, return (ic, const e n, p) | he₁@(const e₁ c₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``zero_add [e₂], return (ic, he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂ c₂) := do c ← get_cache, if c₂ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek n₂.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0 0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₂.1 ek n₁.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0 0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ic_lift $ λ ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr × ℚ) : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic e₁ e₂ c₁ c₂, return (const e' (c₁ * c₂), p) | (const e₁ c₁) e₂ := if c₁ = 0 then do c ← get_cache, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ λ ic, ic.mk_app ``zero_mul [e₂], return (const α0 0, p) else if c₁ = 1 then do p ← ic_lift $ λ ic, ic.mk_app ``one_mul [e₂], return (e₂, p) else eval_const_mul (e₁, c₁) e₂ | e₁ he₂@(const e₂ c₂) := do p₁ ← ic_lift $ λ ic, ic.mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (haa, h₂) ← eval_horner aa x₁ n₂ (const α0 0), if b₂.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] theorem pow_succ {α} [comm_semiring α] (a n b c) (h₁ : (a:α) ^ n = b) (h₂ : b * a = c) : a ^ (n + 1) = c := by rw [← h₂, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], p ← ic_lift $ λ ic, ic.mk_app ``pow_zero [e], return (const α1 1, p) | e (_, 1) := do p ← ic_lift $ λ ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (e₂, m) := ic_lift $ λ ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic e₂, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ λ nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', h₂) ← eval_pow a m, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const α0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← nc_lift $ λ nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, e₂, tl, t, hl, p₂]) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], return (xadd' c (const α1 1) (e, i) (`(1), 1) (const α0 0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := by rw [div_eq_mul_inv, h] /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%inst %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_neg.neg [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_sub [e₁, e₂, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ic_lift $ λ ic, ic.mk_app ``div_inv_monoid.to_has_div [], lift $ is_def_eq inst inst')) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_inv.inv [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_div [e₁, e₂, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (atoms : ref (buffer expr)) (e : expr) : tactic (expr × expr) := ring_m.run' red atoms e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := (sub_eq_add_neg a b).symm /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := using_new_ref mk_buffer $ λ atoms, do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red atoms | normalize_mode.horner := trans_conv (eval' red atoms) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red atoms) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (λ e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [`tactic.interactive.ring], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
c2bea25882e12f16a4dd38a344a7eb4c0bda4144
bb31430994044506fa42fd667e2d556327e18dfe
/src/field_theory/minpoly/basic.lean
ec940ccbf05d3c5b3dc2864fc0020af20bf1c461
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
8,967
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import data.polynomial.field_division import ring_theory.integral_closure /-! # Minimal polynomials This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`, under the assumption that x is integral over `A`, and derives some basic properties such as ireducibility under the assumption `B` is a domain. -/ open_locale classical polynomial open polynomial set function variables {A B : Type*} section min_poly_def variables (A) [comm_ring A] [ring B] [algebra A B] /-- Suppose `x : B`, where `B` is an `A`-algebra. The minimal polynomial `minpoly A x` of `x` is a monic polynomial with coefficients in `A` of smallest degree that has `x` as its root, if such exists (`is_integral A x`) or zero otherwise. For example, if `V` is a `𝕜`-vector space for some field `𝕜` and `f : V →ₗ[𝕜] V` then the minimal polynomial of `f` is `minpoly 𝕜 f`. -/ noncomputable def minpoly (x : B) : A[X] := if hx : is_integral A x then well_founded.min degree_lt_wf _ hx else 0 end min_poly_def namespace minpoly section ring variables [comm_ring A] [ring B] [algebra A B] variables {x : B} /-- A minimal polynomial is monic. -/ lemma monic (hx : is_integral A x) : monic (minpoly A x) := by { delta minpoly, rw dif_pos hx, exact (well_founded.min_mem degree_lt_wf _ hx).1 } /-- A minimal polynomial is nonzero. -/ lemma ne_zero [nontrivial A] (hx : is_integral A x) : minpoly A x ≠ 0 := (monic hx).ne_zero lemma eq_zero (hx : ¬ is_integral A x) : minpoly A x = 0 := dif_neg hx variables (A x) /-- An element is a root of its minimal polynomial. -/ @[simp] lemma aeval : aeval x (minpoly A x) = 0 := begin delta minpoly, split_ifs with hx, { exact (well_founded.min_mem degree_lt_wf _ hx).2 }, { exact aeval_zero _ } end /-- A minimal polynomial is not `1`. -/ lemma ne_one [nontrivial B] : minpoly A x ≠ 1 := begin intro h, refine (one_ne_zero : (1 : B) ≠ 0) _, simpa using congr_arg (polynomial.aeval x) h end lemma map_ne_one [nontrivial B] {R : Type*} [semiring R] [nontrivial R] (f : A →+* R) : (minpoly A x).map f ≠ 1 := begin by_cases hx : is_integral A x, { exact mt ((monic hx).eq_one_of_map_eq_one f) (ne_one A x) }, { rw [eq_zero hx, polynomial.map_zero], exact zero_ne_one }, end /-- A minimal polynomial is not a unit. -/ lemma not_is_unit [nontrivial B] : ¬ is_unit (minpoly A x) := begin haveI : nontrivial A := (algebra_map A B).domain_nontrivial, by_cases hx : is_integral A x, { exact mt (monic hx).eq_one_of_is_unit (ne_one A x) }, { rw [eq_zero hx], exact not_is_unit_zero } end lemma mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebra_map A B).range := begin have h : is_integral A x, { by_contra h, rw [eq_zero h, degree_zero, ←with_bot.coe_one] at hx, exact (ne_of_lt (show ⊥ < ↑1, from with_bot.bot_lt_coe 1) hx) }, have key := minpoly.aeval A x, rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leading_coeff, C_1, one_mul, aeval_add, aeval_C, aeval_X, ←eq_neg_iff_add_eq_zero, ←ring_hom.map_neg] at key, exact ⟨-(minpoly A x).coeff 0, key.symm⟩, end /-- The defining property of the minimal polynomial of an element `x`: it is the monic polynomial with smallest degree that has `x` as its root. -/ lemma min {p : A[X]} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := begin delta minpoly, split_ifs with hx, { exact le_of_not_lt (well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩) }, { simp only [degree_zero, bot_le] } end @[nontriviality] lemma subsingleton [subsingleton B] : minpoly A x = 1 := begin nontriviality A, have := minpoly.min A x monic_one (subsingleton.elim _ _), rw degree_one at this, cases le_or_lt (minpoly A x).degree 0 with h h, { rwa (monic ⟨1, monic_one, by simp⟩ : (minpoly A x).monic).degree_le_zero_iff_eq_one at h }, { exact (this.not_lt h).elim }, end end ring section comm_ring variables [comm_ring A] section ring variables [ring B] [algebra A B] [nontrivial B] variables {x : B} /-- The degree of a minimal polynomial, as a natural number, is positive. -/ lemma nat_degree_pos (hx : is_integral A x) : 0 < nat_degree (minpoly A x) := begin rw pos_iff_ne_zero, intro ndeg_eq_zero, have eq_one : minpoly A x = 1, { rw eq_C_of_nat_degree_eq_zero ndeg_eq_zero, convert C_1, simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval A x end /-- The degree of a minimal polynomial is positive. -/ lemma degree_pos (hx : is_integral A x) : 0 < degree (minpoly A x) := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos hx) /-- If `B/A` is an injective ring extension, and `a` is an element of `A`, then the minimal polynomial of `algebra_map A B a` is `X - C a`. -/ lemma eq_X_sub_C_of_algebra_map_inj (a : A) (hf : function.injective (algebra_map A B)) : minpoly A (algebra_map A B a) = X - C a := begin nontriviality A, have hdegle : (minpoly A (algebra_map A B a)).nat_degree ≤ 1, { apply with_bot.coe_le_coe.1, rw [←degree_eq_nat_degree (ne_zero (@is_integral_algebra_map A B _ _ _ a)), with_top.coe_one, ←degree_X_sub_C a], refine min A (algebra_map A B a) (monic_X_sub_C a) _, simp only [aeval_C, aeval_X, alg_hom.map_sub, sub_self] }, have hdeg : (minpoly A (algebra_map A B a)).degree = 1, { apply (degree_eq_iff_nat_degree_eq (ne_zero (@is_integral_algebra_map A B _ _ _ a))).2, apply le_antisymm hdegle (nat_degree_pos (@is_integral_algebra_map A B _ _ _ a)) }, have hrw := eq_X_add_C_of_degree_eq_one hdeg, simp only [monic (@is_integral_algebra_map A B _ _ _ a), one_mul, monic.leading_coeff, ring_hom.map_one] at hrw, have h0 : (minpoly A (algebra_map A B a)).coeff 0 = -a, { have hroot := aeval A (algebra_map A B a), rw [hrw, add_comm] at hroot, simp only [aeval_C, aeval_X, aeval_add] at hroot, replace hroot := eq_neg_of_add_eq_zero_left hroot, rw [←ring_hom.map_neg _ a] at hroot, exact (hf hroot) }, rw hrw, simp only [h0, ring_hom.map_neg, sub_eq_add_neg], end end ring section is_domain variables [is_domain A] [ring B] [algebra A B] variables {x : B} /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ lemma aeval_ne_zero_of_dvd_not_unit_minpoly {a : A[X]} (hx : is_integral A x) (hamonic : a.monic) (hdvd : dvd_not_unit a (minpoly A x)) : polynomial.aeval x a ≠ 0 := begin intro ha, refine not_lt_of_ge (minpoly.min A x hamonic ha) _, obtain ⟨hzeroa, b, hb_nunit, prod⟩ := hdvd, have hbmonic : b.monic, { rw monic.def, have := monic hx, rwa [monic.def, prod, leading_coeff_mul, monic.def.mp hamonic, one_mul] at this }, have hzerob : b ≠ 0 := hbmonic.ne_zero, have degbzero : 0 < b.nat_degree, { apply nat.pos_of_ne_zero, intro h, have h₁ := eq_C_of_nat_degree_eq_zero h, rw [←h, ←leading_coeff, monic.def.1 hbmonic, C_1] at h₁, rw h₁ at hb_nunit, have := is_unit_one, contradiction }, rw [prod, degree_mul, degree_eq_nat_degree hzeroa, degree_eq_nat_degree hzerob], exact_mod_cast lt_add_of_pos_right _ degbzero, end variables [is_domain B] /-- A minimal polynomial is irreducible. -/ lemma irreducible (hx : is_integral A x) : irreducible (minpoly A x) := begin cases irreducible_or_factor (minpoly A x) (not_is_unit A x) with hirr hred, { exact hirr }, exfalso, obtain ⟨a, b, ha_nunit, hb_nunit, hab_eq⟩ := hred, have coeff_prod : a.leading_coeff * b.leading_coeff = 1, { rw [←monic.def.1 (monic hx), ←hab_eq], simp only [leading_coeff_mul] }, have hamonic : (a * C b.leading_coeff).monic, { rw monic.def, simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have hbmonic : (b * C a.leading_coeff).monic, { rw [monic.def, mul_comm], simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have prod : minpoly A x = (a * C b.leading_coeff) * (b * C a.leading_coeff), { symmetry, calc a * C b.leading_coeff * (b * C a.leading_coeff) = a * b * (C a.leading_coeff * C b.leading_coeff) : by ring ... = a * b * (C (a.leading_coeff * b.leading_coeff)) : by simp only [ring_hom.map_mul] ... = a * b : by rw [coeff_prod, C_1, mul_one] ... = minpoly A x : hab_eq }, have hzero := aeval A x, rw [prod, aeval_mul, mul_eq_zero] at hzero, cases hzero, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hamonic _ hzero, exact ⟨hamonic.ne_zero, _, mt is_unit_of_mul_is_unit_left hb_nunit, prod⟩ }, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hbmonic _ hzero, rw mul_comm at prod, exact ⟨hbmonic.ne_zero, _, mt is_unit_of_mul_is_unit_left ha_nunit, prod⟩ }, end end is_domain end comm_ring end minpoly
604dbfe27aa980a0b5ad0c83bbcb67080b48149c
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/measurable_space_def.lean
ecf8df9a1e75f8f3a0dc2be2a5b600764283fc8f
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
17,493
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 algebra.indicator_function import data.equiv.encodable.lattice import data.set.countable import order.disjointed import order.filter.basic import order.symm_diff /-! # Measurable spaces and measurable functions This file defines measurable spaces and measurable functions. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. Do not add measurability lemmas (which could be tagged with @[measurability]) to this file, since the measurability tactic is downstream from here. Use `measure_theory.measurable_space` instead. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function -/ open set encodable function equiv open_locale classical filter variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (measurable_set' : set α → Prop) (measurable_set_empty : measurable_set' ∅) (measurable_set_compl : ∀ s, measurable_set' s → measurable_set' sᶜ) (measurable_set_Union : ∀ f : ℕ → set α, (∀ i, measurable_set' (f i)) → measurable_set' (⋃ i, f i)) attribute [class] measurable_space instance [h : measurable_space α] : measurable_space (order_dual α) := h section variable [measurable_space α] /-- `measurable_set s` means that `s` is measurable (in the ambient measure space on `α`) -/ def measurable_set : set α → Prop := ‹measurable_space α›.measurable_set' localized "notation `measurable_set[` m `]` := @measurable_set _ m" in measure_theory @[simp] lemma measurable_set.empty : measurable_set (∅ : set α) := ‹measurable_space α›.measurable_set_empty lemma measurable_set.compl : measurable_set s → measurable_set sᶜ := ‹measurable_space α›.measurable_set_compl s lemma measurable_set.of_compl (h : measurable_set sᶜ) : measurable_set s := compl_compl s ▸ h.compl @[simp] lemma measurable_set.compl_iff : measurable_set sᶜ ↔ measurable_set s := ⟨measurable_set.of_compl, measurable_set.compl⟩ @[simp] lemma measurable_set.univ : measurable_set (univ : set α) := by simpa using (@measurable_set.empty α _).compl @[nontriviality] lemma subsingleton.measurable_set [subsingleton α] {s : set α} : measurable_set s := subsingleton.set_cases measurable_set.empty measurable_set.univ s lemma measurable_set.congr {s t : set α} (hs : measurable_set s) (h : s = t) : measurable_set t := by rwa ← h lemma measurable_set.bUnion_decode₂ [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) (n : ℕ) : measurable_set (⋃ b ∈ decode₂ β n, f b) := encodable.Union_decode₂_cases measurable_set.empty h lemma measurable_set.Union [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := begin rw ← encodable.Union_decode₂, exact ‹measurable_space α›.measurable_set_Union _ (measurable_set.bUnion_decode₂ h) end lemma measurable_set.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact measurable_set.Union (by simpa using h) end lemma set.finite.measurable_set_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := measurable_set.bUnion hs.countable h lemma finset.measurable_set_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := s.finite_to_set.measurable_set_bUnion h lemma measurable_set.sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h } lemma set.finite.measurable_set_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := measurable_set.sUnion hs.countable h lemma measurable_set.Union_Prop {p : Prop} {f : p → set α} (hf : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := by { by_cases p; simp [h, hf, measurable_set.empty] } lemma measurable_set.Inter [encodable β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.compl_iff.1 $ by { rw compl_Inter, exact measurable_set.Union (λ b, (h b).compl) } section fintype local attribute [instance] fintype.encodable lemma measurable_set.Union_fintype [fintype β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := measurable_set.Union h lemma measurable_set.Inter_fintype [fintype β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.Inter h end fintype lemma measurable_set.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.compl_iff.1 $ by { rw compl_bInter, exact measurable_set.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.measurable_set_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.bInter hs.countable h lemma finset.measurable_set_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := s.finite_to_set.measurable_set_bInter h lemma measurable_set.sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := by { rw sInter_eq_bInter, exact measurable_set.bInter hs h } lemma set.finite.measurable_set_sInter {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := measurable_set.sInter hs.countable h lemma measurable_set.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := by { by_cases p; simp [h, hf, measurable_set.univ] } @[simp] lemma measurable_set.union {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∪ s₂) := by { rw union_eq_Union, exact measurable_set.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma measurable_set.inter {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma measurable_set.diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma measurable_set.symm_diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ Δ s₂) := (h₁.diff h₂).union (h₂.diff h₁) @[simp] lemma measurable_set.ite {t s₁ s₂ : set α} (ht : measurable_set t) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (t.ite s₁ s₂) := (h₁.inter ht).union (h₂.diff ht) @[simp] lemma measurable_set.cond {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) {i : bool} : measurable_set (cond i s₁ s₂) := by { cases i, exacts [h₂, h₁] } @[simp] lemma measurable_set.disjointed {f : ℕ → set α} (h : ∀ i, measurable_set (f i)) (n) : measurable_set (disjointed f n) := disjointed_induct (h n) (assume t i ht, measurable_set.diff ht $ h _) @[simp] lemma measurable_set.const (p : Prop) : measurable_set {a : α | p} := by { by_cases p; simp [h, measurable_set.empty]; apply measurable_set.univ } /-- Every set has a measurable superset. Declare this as local instance as needed. -/ lemma nonempty_measurable_superset (s : set α) : nonempty { t // s ⊆ t ∧ measurable_set t} := ⟨⟨univ, subset_univ s, measurable_set.univ⟩⟩ end @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, m₁.measurable_set' s ↔ m₂.measurable_set' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀ s : set α, m₁.measurable_set' s ↔ m₂.measurable_set' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (measurable_set_singleton : ∀ x, measurable_set ({x} : set α)) export measurable_singleton_class (measurable_set_singleton) attribute [simp] measurable_set_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma measurable_set_eq {a : α} : measurable_set {x | x = a} := measurable_set_singleton a lemma measurable_set.insert {s : set α} (hs : measurable_set s) (a : α) : measurable_set (insert a s) := (measurable_set_singleton a).union hs @[simp] lemma measurable_set_insert {a : α} {s : set α} : measurable_set (insert a s) ↔ measurable_set s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (measurable_set_singleton _), λ h, h.insert a⟩ lemma set.finite.measurable_set {s : set α} (hs : finite s) : measurable_set s := finite.induction_on hs measurable_set.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.measurable_set (s : finset α) : measurable_set (↑s : set α) := s.finite_to_set.measurable_set lemma set.countable.measurable_set {s : set α} (hs : countable s) : measurable_set s := begin rw [← bUnion_of_singleton s], exact measurable_set.bUnion hs (λ b hb, measurable_set_singleton b) end end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λ m₁ m₂, m₁.measurable_set' ≤ m₂.measurable_set', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀ u ∈ s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀ s, generate_measurable s → generate_measurable sᶜ | union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { measurable_set' := generate_measurable s, measurable_set_empty := generate_measurable.empty, measurable_set_compl := generate_measurable.compl, measurable_set_Union := generate_measurable.union } lemma measurable_set_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).measurable_set' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, m.measurable_set' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (measurable_set_empty m) (assume s _ hs, measurable_set_compl m s hs) (assume f _ hf, measurable_set_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.measurable_set' t} := iff.intro (assume h u hu, h _ $ measurable_set_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_measurable_set [measurable_space α] : generate_from {s : set α | measurable_set s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, measurable_set_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).measurable_set' t} = g) : measurable_space α := { measurable_set' := λ s, s ∈ g, measurable_set_empty := hg ▸ measurable_set_empty _, measurable_set_compl := hg ▸ measurable_set_compl _, measurable_set_Union := hg ▸ measurable_set_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).measurable_set' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @measurable_set α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, measurable_set_generate_from, choice := λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma measurable_set_bot_iff {s : set α} : @measurable_set α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { measurable_set' := λ s, s = ∅ ∨ s = univ, measurable_set_empty := or.inl rfl, measurable_set_compl := by simp [or_imp_distrib] {contextual := tt}, measurable_set_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (λ s, s.symm ▸ @measurable_set_empty _ ⊥) (λ s, s.symm ▸ @measurable_set.univ _ ⊥), this ▸ iff.rfl @[simp] theorem measurable_set_top {s : set α} : @measurable_set _ ⊤ s := trivial @[simp] theorem measurable_set_inf {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊓ m₂) s ↔ @measurable_set _ m₁ s ∧ @measurable_set _ m₂ s := iff.rfl @[simp] theorem measurable_set_Inf {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Inf ms) s ↔ ∀ m ∈ ms, @measurable_set _ m s := show s ∈ (⋂ m ∈ ms, {t | @measurable_set _ m t }) ↔ _, by simp @[simp] theorem measurable_set_infi {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (infi m) s ↔ ∀ i, @measurable_set _ (m i) s := show s ∈ (λ m, {s | @measurable_set _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem measurable_set_sup {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.measurable_set' ∪ m₂.measurable_set') s := iff.refl _ theorem measurable_set_Sup {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Sup ms) s ↔ generate_measurable {s : set α | ∃ m ∈ ms, @measurable_set _ m s} s := begin change @measurable_set' _ (generate_from $ ⋃ m ∈ ms, _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem measurable_set_supr {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, @measurable_set _ (m i) s} s := begin convert @measurable_set_Sup _ (range m) s, simp, end end complete_lattice end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, measurable_set t → measurable_set (f ⁻¹' t) variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_id : measurable (@id α) := λ t, id lemma measurable_id' : measurable (λ a : α, a) := measurable_id lemma measurable.comp {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) @[simp] lemma measurable_const {a : α} : measurable (λ b : β, a) := assume s hs, measurable_set.const (a ∈ s) end measurable_functions
728453cfcfaaa2080fd88d58cfcaa48b7e6a20ce
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/rat/lemmas.lean
ed1458d00700267900ad4200a23438c8f74401ae
[ "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
12,418
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.defs import data.int.cast.lemmas import data.int.div import algebra.group_with_zero.units.lemmas import tactic.nth_rewrite /-! # Further lemmas for the Rational Numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace rat open_locale rat theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := begin cases e : a /. b with n d h c, rw [rat.num_denom', rat.mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.dvd_of_dvd_mul_right _), have := congr_arg int.nat_abs e, simp only [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this] end theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b := begin by_cases b0 : b = 0, {simp [b0]}, cases e : a /. b with n d h c, rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _), rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp end lemma num_denom_mk {q : ℚ} {n d : ℤ} (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom := begin obtain rfl|hn := eq_or_ne n 0, { simp [qdf] }, have : q.num * d = n * ↑(q.denom), { refine (rat.mk_eq _ hd).mp _, { exact int.coe_nat_ne_zero.mpr (rat.denom_ne_zero _) }, { rwa [num_denom] } }, have hqdn : q.num ∣ n, { rw qdf, exact rat.num_dvd _ hd }, refine ⟨n / q.num, _, _⟩, { rw int.div_mul_cancel hqdn }, { refine int.eq_mul_div_of_mul_eq_mul_of_dvd_left _ hqdn this, rw qdf, exact rat.num_ne_zero_of_ne_zero ((mk_ne_zero hd).mpr hn) } end theorem mk_pnat_num (n : ℤ) (d : ℕ+) : (mk_pnat n d).num = n / nat.gcd n.nat_abs d := by cases d; refl theorem mk_pnat_denom (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom = d / nat.gcd n.nat_abs d := by cases d; refl lemma num_mk (n d : ℤ) : (n /. d).num = d.sign * n / n.gcd d := begin rcases d with ((_ | _) | _); simp [rat.mk, mk_nat, mk_pnat, nat.succ_pnat, int.sign, int.gcd, -nat.cast_succ, -int.coe_nat_succ, int.zero_div] end lemma denom_mk (n d : ℤ) : (n /. d).denom = if d = 0 then 1 else d.nat_abs / n.gcd d := begin rcases d with ((_ | _) | _); simp [rat.mk, mk_nat, mk_pnat, nat.succ_pnat, int.sign, int.gcd, -nat.cast_succ, -int.coe_nat_succ] end theorem mk_pnat_denom_dvd (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom ∣ d.1 := begin rw mk_pnat_denom, apply nat.div_dvd_of_dvd, apply nat.gcd_dvd_right end theorem add_denom_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).denom ∣ q₁.denom * q₂.denom := by { cases q₁, cases q₂, apply mk_pnat_denom_dvd } theorem mul_denom_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).denom ∣ q₁.denom * q₂.denom := by { cases q₁, cases q₂, apply mk_pnat_denom_dvd } theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = (q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom = (q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom := by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) lemma add_num_denom (q r : ℚ) : q + r = ((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) := have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3, have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3, by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] }; simp [mul_comm] section casts lemma exists_eq_mul_div_num_and_eq_mul_div_denom (n : ℤ) {d : ℤ} (d_ne_zero : d ≠ 0) : ∃ (c : ℤ), n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).denom := begin have : ((n : ℚ) / d) = rat.mk n d, by rw [←rat.mk_eq_div], exact rat.num_denom_mk d_ne_zero this end lemma mul_num_denom' (q r : ℚ) : (q * r).num * q.denom * r.denom = q.num * r.num * (q * r).denom := begin let s := (q.num * r.num) /. (q.denom * r.denom : ℤ), have hs : (q.denom * r.denom : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.mpr (mul_pos q.pos r.pos), obtain ⟨c, ⟨c_mul_num, c_mul_denom⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_denom (q.num * r.num) hs, rw [c_mul_num, mul_assoc, mul_comm], nth_rewrite 0 c_mul_denom, repeat {rw mul_assoc}, apply mul_eq_mul_left_iff.2, rw or_iff_not_imp_right, intro c_pos, have h : _ = s := @mul_def q.num q.denom r.num r.denom (int.coe_nat_ne_zero_iff_pos.mpr q.pos) (int.coe_nat_ne_zero_iff_pos.mpr r.pos), rw [num_denom, num_denom] at h, rw h, rw mul_comm, apply rat.eq_iff_mul_eq_mul.mp, rw ←mk_eq_div, end lemma add_num_denom' (q r : ℚ) : (q + r).num * q.denom * r.denom = (q.num * r.denom + r.num * q.denom) * (q + r).denom := begin let s := mk (q.num * r.denom + r.num * q.denom) (q.denom * r.denom : ℤ), have hs : (q.denom * r.denom : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.mpr (mul_pos q.pos r.pos), obtain ⟨c, ⟨c_mul_num, c_mul_denom⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_denom (q.num * r.denom + r.num * q.denom) hs, rw [c_mul_num, mul_assoc, mul_comm], nth_rewrite 0 c_mul_denom, repeat {rw mul_assoc}, apply mul_eq_mul_left_iff.2, rw or_iff_not_imp_right, intro c_pos, have h : _ = s := @add_def q.num q.denom r.num r.denom (int.coe_nat_ne_zero_iff_pos.mpr q.pos) (int.coe_nat_ne_zero_iff_pos.mpr r.pos), rw [num_denom, num_denom] at h, rw h, rw mul_comm, apply rat.eq_iff_mul_eq_mul.mp, rw ←mk_eq_div, end lemma substr_num_denom' (q r : ℚ) : (q - r).num * q.denom * r.denom = (q.num * r.denom - r.num * q.denom) * (q - r).denom := by rw [sub_eq_add_neg, sub_eq_add_neg, ←neg_mul, ←num_neg_eq_neg_num, ←denom_neg_eq_denom r, add_num_denom' q (-r)] end casts lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num := by { conv_lhs { rw ←@num_denom q }, rw [inv_def, mk_eq_div, int.cast_coe_nat] } protected lemma inv_neg (q : ℚ) : (-q)⁻¹ = -q⁻¹ := by { rw ←@num_denom q, simp [-num_denom] } @[simp] lemma mul_denom_eq_num {q : ℚ} : q * q.denom = q.num := begin suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by { conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] }, have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos), rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)] end lemma denom_div_cast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) : ((m : ℚ) / n).denom = 1 ↔ n ∣ m := begin replace hn : (n:ℚ) ≠ 0, by rwa [ne.def, ← int.cast_zero, coe_int_inj], split, { intro h, lift ((m : ℚ) / n) to ℤ using h with k hk, use k, rwa [eq_div_iff_mul_eq hn, ← int.cast_mul, mul_comm, eq_comm, coe_int_inj] at hk }, { rintros ⟨d, rfl⟩, rw [int.cast_mul, mul_comm, mul_div_cancel _ hn, rat.coe_int_denom] } end lemma num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) : (a / b : ℚ).num = a := begin lift b to ℕ using le_of_lt hb0, norm_cast at hb0 h, rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_num, pnat.mk_coe, h.gcd_eq_one, int.coe_nat_one, int.div_one] end lemma denom_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) : ((a / b : ℚ).denom : ℤ) = b := begin lift b to ℕ using le_of_lt hb0, norm_cast at hb0 h, rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_denom, pnat.mk_coe, h.gcd_eq_one, nat.div_one] end lemma div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d) (h1 : nat.coprime a.nat_abs b.nat_abs) (h2 : nat.coprime c.nat_abs d.nat_abs) (h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d := begin apply and.intro, { rw [← (num_div_eq_of_coprime hb0 h1), h, num_div_eq_of_coprime hd0 h2] }, { rw [← (denom_div_eq_of_coprime hb0 h1), h, denom_div_eq_of_coprime hd0 h2] } end @[norm_cast] lemma coe_int_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n := begin by_cases hn : n = 0, { subst hn, simp only [int.cast_zero, int.zero_div, zero_div] }, { have : (n : ℚ) ≠ 0, { rwa ← coe_int_inj at hn }, simp only [int.div_self hn, int.cast_one, ne.def, not_false_iff, div_self this] } end @[norm_cast] lemma coe_nat_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n := coe_int_div_self n lemma coe_int_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b := begin rcases h with ⟨c, rfl⟩, simp only [mul_comm b, int.mul_div_assoc c (dvd_refl b), int.cast_mul, mul_div_assoc, coe_int_div_self] end lemma coe_nat_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b := begin rcases h with ⟨c, rfl⟩, simp only [mul_comm b, nat.mul_div_assoc c (dvd_refl b), nat.cast_mul, mul_div_assoc, coe_nat_div_self] end lemma inv_coe_int_num_of_pos {a : ℤ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 := begin rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one], apply num_div_eq_of_coprime ha0, rw int.nat_abs_one, exact nat.coprime_one_left _, end lemma inv_coe_nat_num_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 := inv_coe_int_num_of_pos (by exact_mod_cast ha0 : 0 < (a : ℤ)) lemma inv_coe_int_denom_of_pos {a : ℤ} (ha0 : 0 < a) : ((a : ℚ)⁻¹.denom : ℤ) = a := begin rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one], apply denom_div_eq_of_coprime ha0, rw int.nat_abs_one, exact nat.coprime_one_left _, end lemma inv_coe_nat_denom_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.denom = a := begin rw [← int.coe_nat_eq_coe_nat_iff, ← int.cast_coe_nat a, inv_coe_int_denom_of_pos], rwa [← nat.cast_zero, nat.cast_lt] end @[simp] lemma inv_coe_int_num (a : ℤ) : (a : ℚ)⁻¹.num = int.sign a := begin induction a using int.induction_on; simp [←int.neg_succ_of_nat_coe', int.neg_succ_of_nat_coe, -neg_add_rev, rat.inv_neg, int.coe_nat_add_one_out, -nat.cast_succ, inv_coe_nat_num_of_pos, -int.cast_neg_succ_of_nat, @eq_comm ℤ 1, int.sign_eq_one_of_pos] end @[simp] lemma inv_coe_nat_num (a : ℕ) : (a : ℚ)⁻¹.num = int.sign a := inv_coe_int_num a @[simp] lemma inv_coe_int_denom (a : ℤ) : (a : ℚ)⁻¹.denom = if a = 0 then 1 else a.nat_abs := begin induction a using int.induction_on; simp [←int.neg_succ_of_nat_coe', int.neg_succ_of_nat_coe, -neg_add_rev, rat.inv_neg, int.coe_nat_add_one_out, -nat.cast_succ, inv_coe_nat_denom_of_pos, -int.cast_neg_succ_of_nat] end @[simp] lemma inv_coe_nat_denom (a : ℕ) : (a : ℚ)⁻¹.denom = if a = 0 then 1 else a := by simpa using inv_coe_int_denom a protected lemma «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) := ⟨λ h _ _, h _, λ h q, (show q = q.num / q.denom, from by simp [rat.div_num_denom]).symm ▸ (h q.1 q.2)⟩ protected lemma «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) := ⟨λ ⟨r, hr⟩, ⟨r.num, r.denom, by rwa [← mk_eq_div, num_denom]⟩, λ ⟨a, b, h⟩, ⟨_, h⟩⟩ /-! ### Denominator as `ℕ+` -/ section pnat_denom /-- Denominator as `ℕ+`. -/ def pnat_denom (x : ℚ) : ℕ+ := ⟨x.denom, x.pos⟩ @[simp] lemma coe_pnat_denom (x : ℚ) : (x.pnat_denom : ℕ) = x.denom := rfl @[simp] lemma mk_pnat_pnat_denom_eq (x : ℚ) : mk_pnat x.num x.pnat_denom = x := by rw [pnat_denom, mk_pnat_eq, num_denom] lemma pnat_denom_eq_iff_denom_eq {x : ℚ} {n : ℕ+} : x.pnat_denom = n ↔ x.denom = ↑n := subtype.ext_iff @[simp] lemma pnat_denom_one : (1 : ℚ).pnat_denom = 1 := rfl @[simp] lemma pnat_denom_zero : (0 : ℚ).pnat_denom = 1 := rfl end pnat_denom end rat
8ed3660fbce06fce1bd7aa814d3f8fcd7c616bbb
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/lie/tensor_product.lean
ed0389173dcbcac9a2c6e909f628d968bd74d19a
[ "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,872
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.abelian /-! # Tensor products of Lie modules Tensor products of Lie modules carry natural Lie module structures. ## Tags lie module, tensor product, universal property -/ universes u v w w₁ w₂ w₃ variables {R : Type u} [comm_ring R] open lie_module namespace tensor_product open_locale tensor_product namespace lie_module variables {L : Type v} {M : Type w} {N : Type w₁} {P : Type w₂} {Q : Type w₃} variables [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] variables [add_comm_group P] [module R P] [lie_ring_module L P] [lie_module R L P] variables [add_comm_group Q] [module R Q] [lie_ring_module L Q] [lie_module R L Q] local attribute [ext] tensor_product.ext /-- It is useful to define the bracket via this auxiliary function so that we have a type-theoretic expression of the fact that `L` acts by linear endomorphisms. It simplifies the proofs in `lie_ring_module` below. -/ def has_bracket_aux (x : L) : module.End R (M ⊗[R] N) := (to_endomorphism R L M x).rtensor N + (to_endomorphism R L N x).ltensor M /-- The tensor product of two Lie modules is a Lie ring module. -/ instance lie_ring_module : lie_ring_module L (M ⊗[R] N) := { bracket := λ x, has_bracket_aux x, add_lie := λ x y t, by { simp only [has_bracket_aux, linear_map.ltensor_add, linear_map.rtensor_add, lie_hom.map_add, linear_map.add_apply], abel, }, lie_add := λ x, linear_map.map_add _, leibniz_lie := λ x y t, by { suffices : (has_bracket_aux x).comp (has_bracket_aux y) = has_bracket_aux ⁅x,y⁆ + (has_bracket_aux y).comp (has_bracket_aux x), { simp only [← linear_map.add_apply], rw [← linear_map.comp_apply, this], refl }, ext m n, simp only [has_bracket_aux, lie_ring.of_associative_ring_bracket, linear_map.mul_apply, mk_apply, linear_map.ltensor_sub, linear_map.compr₂_apply, function.comp_app, linear_map.coe_comp, linear_map.rtensor_tmul, lie_hom.map_lie, to_endomorphism_apply_apply, linear_map.add_apply, linear_map.map_add, linear_map.rtensor_sub, linear_map.sub_apply, linear_map.ltensor_tmul], abel, }, } /-- The tensor product of two Lie modules is a Lie module. -/ instance lie_module : lie_module R L (M ⊗[R] N) := { smul_lie := λ c x t, by { change has_bracket_aux (c • x) _ = c • has_bracket_aux _ _, simp only [has_bracket_aux, smul_add, linear_map.rtensor_smul, linear_map.smul_apply, linear_map.ltensor_smul, lie_hom.map_smul, linear_map.add_apply], }, lie_smul := λ c x, linear_map.map_smul _ c, } @[simp] lemma lie_tmul_right (x : L) (m : M) (n : N) : ⁅x, m ⊗ₜ[R] n⁆ = ⁅x, m⁆ ⊗ₜ n + m ⊗ₜ ⁅x, n⁆ := show has_bracket_aux x (m ⊗ₜ[R] n) = _, by simp only [has_bracket_aux, linear_map.rtensor_tmul, to_endomorphism_apply_apply, linear_map.add_apply, linear_map.ltensor_tmul] variables (R L M N P Q) /-- The universal property for tensor product of modules of a Lie algebra: the `R`-linear tensor-hom adjunction is equivariant with respect to the `L` action. -/ def lift : (M →ₗ[R] N →ₗ[R] P) ≃ₗ⁅R,L⁆ (M ⊗[R] N →ₗ[R] P) := { map_lie' := λ x f, by { ext m n, simp only [mk_apply, linear_map.compr₂_apply, lie_tmul_right, linear_map.sub_apply, lift.equiv_apply, linear_equiv.to_fun_eq_coe, lie_hom.lie_apply, linear_map.map_add], abel, }, ..tensor_product.lift.equiv R M N P } @[simp] lemma lift_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : lift R L M N P f (m ⊗ₜ n) = f m n := rfl /-- A weaker form of the universal property for tensor product of modules of a Lie algebra. Note that maps `f` of type `M →ₗ⁅R,L⁆ N →ₗ[R] P` are exactly those `R`-bilinear maps satisfying `⁅x, f m n⁆ = f ⁅x, m⁆ n + f m ⁅x, n⁆` for all `x, m, n` (see e.g, `lie_module_hom.map_lie₂`). -/ def lift_lie : (M →ₗ⁅R,L⁆ N →ₗ[R] P) ≃ₗ[R] (M ⊗[R] N →ₗ⁅R,L⁆ P) := (max_triv_linear_map_equiv_lie_module_hom.symm ≪≫ₗ ↑(max_triv_equiv (lift R L M N P))) ≪≫ₗ max_triv_linear_map_equiv_lie_module_hom @[simp] lemma coe_lift_lie_eq_lift_coe (f : M →ₗ⁅R,L⁆ N →ₗ[R] P) : ⇑(lift_lie R L M N P f) = lift R L M N P f := begin suffices : (lift_lie R L M N P f : M ⊗[R] N →ₗ[R] P) = lift R L M N P f, { rw [← this, lie_module_hom.coe_to_linear_map], }, ext m n, simp only [lift_lie, linear_equiv.trans_apply, lie_module_equiv.coe_to_linear_equiv, coe_linear_map_max_triv_linear_map_equiv_lie_module_hom, coe_max_triv_equiv_apply, coe_linear_map_max_triv_linear_map_equiv_lie_module_hom_symm], end lemma lift_lie_apply (f : M →ₗ⁅R,L⁆ N →ₗ[R] P) (m : M) (n : N) : lift_lie R L M N P f (m ⊗ₜ n) = f m n := by simp only [coe_lift_lie_eq_lift_coe, lie_module_hom.coe_to_linear_map, lift_apply] variables {R L M N P Q} /-- A pair of Lie module morphisms `f : M → P` and `g : N → Q`, induce a Lie module morphism: `M ⊗ N → P ⊗ Q`. -/ def map (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) : M ⊗[R] N →ₗ⁅R,L⁆ P ⊗[R] Q := { map_lie' := λ x t, by { simp only [linear_map.to_fun_eq_coe], apply t.induction_on, { simp only [linear_map.map_zero, lie_zero], }, { intros m n, simp only [lie_module_hom.coe_to_linear_map, lie_tmul_right, lie_module_hom.map_lie, map_tmul, linear_map.map_add], }, { intros t₁ t₂ ht₁ ht₂, simp only [ht₁, ht₂, lie_add, linear_map.map_add], }, }, .. map (f : M →ₗ[R] P) (g : N →ₗ[R] Q), } @[simp] lemma coe_linear_map_map (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) : (map f g : M ⊗[R] N →ₗ[R] P ⊗[R] Q) = tensor_product.map (f : M →ₗ[R] P) (g : N →ₗ[R] Q) := rfl @[simp] lemma map_tmul (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = (f m) ⊗ₜ (g n) := map_tmul f g m n /-- Given Lie submodules `M' ⊆ M` and `N' ⊆ N`, this is the natural map: `M' ⊗ N' → M ⊗ N`. -/ def map_incl (M' : lie_submodule R L M) (N' : lie_submodule R L N) : M' ⊗[R] N' →ₗ⁅R,L⁆ M ⊗[R] N := map M'.incl N'.incl @[simp] lemma map_incl_def (M' : lie_submodule R L M) (N' : lie_submodule R L N) : map_incl M' N' = map M'.incl N'.incl := rfl end lie_module end tensor_product namespace lie_module open_locale tensor_product variables (R) (L : Type v) (M : Type w) variables [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] /-- The action of the Lie algebra on one of its modules, regarded as a morphism of Lie modules. -/ def to_module_hom : L ⊗[R] M →ₗ⁅R,L⁆ M := tensor_product.lie_module.lift_lie R L L M M { map_lie' := λ x m, by { ext n, simp [lie_ring.of_associative_ring_bracket], }, ..(to_endomorphism R L M : L →ₗ[R] M →ₗ[R] M), } @[simp] lemma to_module_hom_apply (x : L) (m : M) : to_module_hom R L M (x ⊗ₜ m) = ⁅x, m⁆ := by simp only [to_module_hom, tensor_product.lie_module.lift_lie_apply, to_endomorphism_apply_apply, lie_hom.coe_to_linear_map, lie_module_hom.coe_mk, linear_map.coe_mk, linear_map.to_fun_eq_coe] end lie_module namespace lie_submodule open_locale tensor_product open tensor_product.lie_module open lie_module variables {L : Type v} {M : Type w} variables [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables (I : lie_ideal R L) (N : lie_submodule R L M) /-- A useful alternative characterisation of Lie ideal operations on Lie submodules. Given a Lie ideal `I ⊆ L` and a Lie submodule `N ⊆ M`, by tensoring the inclusion maps and then applying the action of `L` on `M`, we obtain morphism of Lie modules `f : I ⊗ N → L ⊗ M → M`. This lemma states that `⁅I, N⁆ = range f`. -/ lemma lie_ideal_oper_eq_tensor_map_range : ⁅I, N⁆ = ((to_module_hom R L M).comp (map_incl I N : ↥I ⊗ ↥N →ₗ⁅R,L⁆ L ⊗ M)).range := begin rw [← coe_to_submodule_eq_iff, lie_ideal_oper_eq_linear_span, lie_module_hom.coe_submodule_range, lie_module_hom.coe_linear_map_comp, linear_map.range_comp, map_incl_def, coe_linear_map_map, tensor_product.map_range_eq_span_tmul, submodule.map_span], congr, ext m, split, { rintros ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, use x ⊗ₜ n, split, { use [⟨x, hx⟩, ⟨n, hn⟩], simp, }, { simp, }, }, { rintros ⟨t, ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, h⟩, rw ← h, use [⟨x, hx⟩, ⟨n, hn⟩], simp, }, end end lie_submodule
6b31501f95f7e0d0a748c132a9ab059aa0dd465d
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/group/prod.lean
78103582d7a99e00920807e9f201918200410a4d
[ "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
20,496
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Yury Kudryashov -/ import algebra.group.opposite /-! # Monoid, group etc structures on `M × N` In this file we define one-binop (`monoid`, `group` etc) structures on `M × N`. We also prove trivial `simp` lemmas, and define the following operations on `monoid_hom`s: * `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `prod.fst` and `prod.snd` as `monoid_hom`s; * `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid into the product; * `f.prod g : `M →* N × P`: sends `x` to `(f x, g x)`; * `f.coprod g : M × N →* P`: sends `(x, y)` to `f x * g y`; * `f.prod_map g : M × N → M' × N'`: `prod.map f g` as a `monoid_hom`, sends `(x, y)` to `(f x, g y)`. ## Main declarations * `mul_mul_hom`/`mul_monoid_hom`/`mul_monoid_with_zero_hom`: Multiplication bundled as a multiplicative/monoid/monoid with zero homomorphism. * `div_monoid_hom`/`div_monoid_with_zero_hom`: Division bundled as a monoid/monoid with zero homomorphism. -/ variables {A : Type*} {B : Type*} {G : Type*} {H : Type*} {M : Type*} {N : Type*} {P : Type*} namespace prod @[to_additive] instance [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ @[simp, to_additive] lemma fst_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive] lemma snd_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive] lemma mk_mul_mk [has_mul M] [has_mul N] (a₁ a₂ : M) (b₁ b₂ : N) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl @[simp, to_additive] lemma swap_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).swap = p.swap * q.swap := rfl @[to_additive] lemma mul_def [has_mul M] [has_mul N] (p q : M × N) : p * q = (p.1 * q.1, p.2 * q.2) := rfl @[to_additive] instance [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ @[simp, to_additive] lemma fst_one [has_one M] [has_one N] : (1 : M × N).1 = 1 := rfl @[simp, to_additive] lemma snd_one [has_one M] [has_one N] : (1 : M × N).2 = 1 := rfl @[to_additive] lemma one_eq_mk [has_one M] [has_one N] : (1 : M × N) = (1, 1) := rfl @[simp, to_additive] lemma mk_eq_one [has_one M] [has_one N] {x : M} {y : N} : (x, y) = 1 ↔ x = 1 ∧ y = 1 := mk.inj_iff @[simp, to_additive] lemma swap_one [has_one M] [has_one N] : (1 : M × N).swap = 1 := rfl @[to_additive] lemma fst_mul_snd [mul_one_class M] [mul_one_class N] (p : M × N) : (p.fst, 1) * (1, p.snd) = p := ext (mul_one p.1) (one_mul p.2) @[to_additive] instance [has_inv M] [has_inv N] : has_inv (M × N) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive] lemma fst_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive] lemma snd_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).2 = (p.2)⁻¹ := rfl @[simp, to_additive] lemma inv_mk [has_inv G] [has_inv H] (a : G) (b : H) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl @[simp, to_additive] lemma swap_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).swap = p.swap⁻¹ := rfl @[to_additive] instance [has_involutive_inv M] [has_involutive_inv N] : has_involutive_inv (M × N) := { inv_inv := λ a, ext (inv_inv _) (inv_inv _), ..prod.has_inv } @[to_additive] instance [has_div M] [has_div N] : has_div (M × N) := ⟨λ p q, ⟨p.1 / q.1, p.2 / q.2⟩⟩ @[simp, to_additive] lemma fst_div [has_div G] [has_div H] (a b : G × H) : (a / b).1 = a.1 / b.1 := rfl @[simp, to_additive] lemma snd_div [has_div G] [has_div H] (a b : G × H) : (a / b).2 = a.2 / b.2 := rfl @[simp, to_additive] lemma mk_div_mk [has_div G] [has_div H] (x₁ x₂ : G) (y₁ y₂ : H) : (x₁, y₁) / (x₂, y₂) = (x₁ / x₂, y₁ / y₂) := rfl @[simp, to_additive] lemma swap_div [has_div G] [has_div H] (a b : G × H) : (a / b).swap = a.swap / b.swap := rfl instance [mul_zero_class M] [mul_zero_class N] : mul_zero_class (M × N) := { zero_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, .. prod.has_zero, .. prod.has_mul } @[to_additive] instance [semigroup M] [semigroup N] : semigroup (M × N) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } @[to_additive] instance [comm_semigroup G] [comm_semigroup H] : comm_semigroup (G × H) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } instance [semigroup_with_zero M] [semigroup_with_zero N] : semigroup_with_zero (M × N) := { .. prod.mul_zero_class, .. prod.semigroup } @[to_additive] instance [mul_one_class M] [mul_one_class N] : mul_one_class (M × N) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.has_mul, .. prod.has_one } @[to_additive] instance [monoid M] [monoid N] : monoid (M × N) := { npow := λ z a, ⟨monoid.npow z a.1, monoid.npow z a.2⟩, npow_zero' := λ z, ext (monoid.npow_zero' _) (monoid.npow_zero' _), npow_succ' := λ z a, ext (monoid.npow_succ' _ _) (monoid.npow_succ' _ _), .. prod.semigroup, .. prod.mul_one_class } @[to_additive prod.sub_neg_monoid] instance [div_inv_monoid G] [div_inv_monoid H] : div_inv_monoid (G × H) := { div_eq_mul_inv := λ a b, mk.inj_iff.mpr ⟨div_eq_mul_inv _ _, div_eq_mul_inv _ _⟩, zpow := λ z a, ⟨div_inv_monoid.zpow z a.1, div_inv_monoid.zpow z a.2⟩, zpow_zero' := λ z, ext (div_inv_monoid.zpow_zero' _) (div_inv_monoid.zpow_zero' _), zpow_succ' := λ z a, ext (div_inv_monoid.zpow_succ' _ _) (div_inv_monoid.zpow_succ' _ _), zpow_neg' := λ z a, ext (div_inv_monoid.zpow_neg' _ _) (div_inv_monoid.zpow_neg' _ _), .. prod.monoid, .. prod.has_inv, .. prod.has_div } @[to_additive subtraction_monoid] instance [division_monoid G] [division_monoid H] : division_monoid (G × H) := { mul_inv_rev := λ a b, ext (mul_inv_rev _ _) (mul_inv_rev _ _), inv_eq_of_mul := λ a b h, ext (inv_eq_of_mul_eq_one_right $ congr_arg fst h) (inv_eq_of_mul_eq_one_right $ congr_arg snd h), .. prod.div_inv_monoid, .. prod.has_involutive_inv } @[to_additive subtraction_comm_monoid] instance [division_comm_monoid G] [division_comm_monoid H] : division_comm_monoid (G × H) := { .. prod.division_monoid, .. prod.comm_semigroup } @[to_additive] instance [group G] [group H] : group (G × H) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, .. prod.div_inv_monoid } @[to_additive] instance [left_cancel_semigroup G] [left_cancel_semigroup H] : left_cancel_semigroup (G × H) := { mul_left_cancel := λ a b c h, prod.ext (mul_left_cancel (prod.ext_iff.1 h).1) (mul_left_cancel (prod.ext_iff.1 h).2), .. prod.semigroup } @[to_additive] instance [right_cancel_semigroup G] [right_cancel_semigroup H] : right_cancel_semigroup (G × H) := { mul_right_cancel := λ a b c h, prod.ext (mul_right_cancel (prod.ext_iff.1 h).1) (mul_right_cancel (prod.ext_iff.1 h).2), .. prod.semigroup } @[to_additive] instance [left_cancel_monoid M] [left_cancel_monoid N] : left_cancel_monoid (M × N) := { .. prod.left_cancel_semigroup, .. prod.monoid } @[to_additive] instance [right_cancel_monoid M] [right_cancel_monoid N] : right_cancel_monoid (M × N) := { .. prod.right_cancel_semigroup, .. prod.monoid } @[to_additive] instance [cancel_monoid M] [cancel_monoid N] : cancel_monoid (M × N) := { .. prod.right_cancel_monoid, .. prod.left_cancel_monoid } @[to_additive] instance [comm_monoid M] [comm_monoid N] : comm_monoid (M × N) := { .. prod.comm_semigroup, .. prod.monoid } @[to_additive] instance [cancel_comm_monoid M] [cancel_comm_monoid N] : cancel_comm_monoid (M × N) := { .. prod.left_cancel_monoid, .. prod.comm_monoid } instance [mul_zero_one_class M] [mul_zero_one_class N] : mul_zero_one_class (M × N) := { .. prod.mul_zero_class, .. prod.mul_one_class } instance [monoid_with_zero M] [monoid_with_zero N] : monoid_with_zero (M × N) := { .. prod.monoid, .. prod.mul_zero_one_class } instance [comm_monoid_with_zero M] [comm_monoid_with_zero N] : comm_monoid_with_zero (M × N) := { .. prod.comm_monoid, .. prod.monoid_with_zero } @[to_additive] instance [comm_group G] [comm_group H] : comm_group (G × H) := { .. prod.comm_semigroup, .. prod.group } end prod namespace mul_hom section prod variables (M N) [has_mul M] [has_mul N] [has_mul P] /-- Given magmas `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ @[to_additive "Given additive magmas `A`, `B`, the natural projection homomorphism from `A × B` to `A`"] def fst : (M × N) →ₙ* M := ⟨prod.fst, λ _ _, rfl⟩ /-- Given magmas `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ @[to_additive "Given additive magmas `A`, `B`, the natural projection homomorphism from `A × B` to `B`"] def snd : (M × N) →ₙ* N := ⟨prod.snd, λ _ _, rfl⟩ variables {M N} @[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl @[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl /-- Combine two `monoid_hom`s `f : M →ₙ* N`, `g : M →ₙ* P` into `f.prod g : M →ₙ* (N × P)` given by `(f.prod g) x = (f x, g x)`. -/ @[to_additive prod "Combine two `add_monoid_hom`s `f : add_hom M N`, `g : add_hom M P` into `f.prod g : add_hom M (N × P)` given by `(f.prod g) x = (f x, g x)`"] protected def prod (f : M →ₙ* N) (g : M →ₙ* P) : M →ₙ* (N × P) := { to_fun := pi.prod f g, map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) } @[to_additive coe_prod] lemma coe_prod (f : M →ₙ* N) (g : M →ₙ* P) : ⇑(f.prod g) = pi.prod f g := rfl @[simp, to_additive prod_apply] lemma prod_apply (f : M →ₙ* N) (g : M →ₙ* P) (x) : f.prod g x = (f x, g x) := rfl @[simp, to_additive fst_comp_prod] lemma fst_comp_prod (f : M →ₙ* N) (g : M →ₙ* P) : (fst N P).comp (f.prod g) = f := ext $ λ x, rfl @[simp, to_additive snd_comp_prod] lemma snd_comp_prod (f : M →ₙ* N) (g : M →ₙ* P) : (snd N P).comp (f.prod g) = g := ext $ λ x, rfl @[simp, to_additive prod_unique] lemma prod_unique (f : M →ₙ* (N × P)) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables {M' : Type*} {N' : Type*} [has_mul M] [has_mul N] [has_mul M'] [has_mul N'] [has_mul P] (f : M →ₙ* M') (g : N →ₙ* N') /-- `prod.map` as a `monoid_hom`. -/ @[to_additive prod_map "`prod.map` as an `add_monoid_hom`"] def prod_map : (M × N) →ₙ* (M' × N') := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prod_map_def] lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[simp, to_additive coe_prod_map] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl @[to_additive prod_comp_prod_map] lemma prod_comp_prod_map (f : P →ₙ* M) (g : P →ₙ* N) (f' : M →ₙ* M') (g' : N →ₙ* N') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map section coprod variables [has_mul M] [has_mul N] [comm_semigroup P] (f : M →ₙ* P) (g : N →ₙ* P) /-- Coproduct of two `mul_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ @[to_additive "Coproduct of two `add_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`."] def coprod : (M × N) →ₙ* P := f.comp (fst M N) * g.comp (snd M N) @[simp, to_additive] lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[to_additive] lemma comp_coprod {Q : Type*} [comm_semigroup Q] (h : P →ₙ* Q) (f : M →ₙ* P) (g : N →ₙ* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext $ λ x, by simp end coprod end mul_hom namespace monoid_hom variables (M N) [mul_one_class M] [mul_one_class N] /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `A`"] def fst : M × N →* M := ⟨prod.fst, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `B`"] def snd : M × N →* N := ⟨prod.snd, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `A` to `A × B`."] def inl : M →* M × N := ⟨λ x, (x, 1), rfl, λ _ _, prod.ext rfl (one_mul 1).symm⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `B` to `A × B`."] def inr : N →* M × N := ⟨λ y, (1, y), rfl, λ _ _, prod.ext (one_mul 1).symm rfl⟩ variables {M N} @[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl @[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl @[simp, to_additive] lemma inl_apply (x) : inl M N x = (x, 1) := rfl @[simp, to_additive] lemma inr_apply (y) : inr M N y = (1, y) := rfl @[simp, to_additive] lemma fst_comp_inl : (fst M N).comp (inl M N) = id M := rfl @[simp, to_additive] lemma snd_comp_inl : (snd M N).comp (inl M N) = 1 := rfl @[simp, to_additive] lemma fst_comp_inr : (fst M N).comp (inr M N) = 1 := rfl @[simp, to_additive] lemma snd_comp_inr : (snd M N).comp (inr M N) = id N := rfl section prod variable [mul_one_class P] /-- Combine two `monoid_hom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P` given by `(f.prod g) x = (f x, g x)`. -/ @[to_additive prod "Combine two `add_monoid_hom`s `f : M →+ N`, `g : M →+ P` into `f.prod g : M →+ N × P` given by `(f.prod g) x = (f x, g x)`"] protected def prod (f : M →* N) (g : M →* P) : M →* N × P := { to_fun := pi.prod f g, map_one' := prod.ext f.map_one g.map_one, map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) } @[to_additive coe_prod] lemma coe_prod (f : M →* N) (g : M →* P) : ⇑(f.prod g) = pi.prod f g := rfl @[simp, to_additive prod_apply] lemma prod_apply (f : M →* N) (g : M →* P) (x) : f.prod g x = (f x, g x) := rfl @[simp, to_additive fst_comp_prod] lemma fst_comp_prod (f : M →* N) (g : M →* P) : (fst N P).comp (f.prod g) = f := ext $ λ x, rfl @[simp, to_additive snd_comp_prod] lemma snd_comp_prod (f : M →* N) (g : M →* P) : (snd N P).comp (f.prod g) = g := ext $ λ x, rfl @[simp, to_additive prod_unique] lemma prod_unique (f : M →* N × P) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] [mul_one_class P] (f : M →* M') (g : N →* N') /-- `prod.map` as a `monoid_hom`. -/ @[to_additive prod_map "`prod.map` as an `add_monoid_hom`"] def prod_map : M × N →* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prod_map_def] lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[simp, to_additive coe_prod_map] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl @[to_additive prod_comp_prod_map] lemma prod_comp_prod_map (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map section coprod variables [comm_monoid P] (f : M →* P) (g : N →* P) /-- Coproduct of two `monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ @[to_additive "Coproduct of two `add_monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`."] def coprod : M × N →* P := f.comp (fst M N) * g.comp (snd M N) @[simp, to_additive] lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[simp, to_additive] lemma coprod_comp_inl : (f.coprod g).comp (inl M N) = f := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_comp_inr : (f.coprod g).comp (inr M N) = g := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_unique (f : M × N →* P) : (f.comp (inl M N)).coprod (f.comp (inr M N)) = f := ext $ λ x, by simp [coprod_apply, inl_apply, inr_apply, ← map_mul] @[simp, to_additive] lemma coprod_inl_inr {M N : Type*} [comm_monoid M] [comm_monoid N] : (inl M N).coprod (inr M N) = id (M × N) := coprod_unique (id $ M × N) @[to_additive] lemma comp_coprod {Q : Type*} [comm_monoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext $ λ x, by simp end coprod end monoid_hom namespace mul_equiv section variables {M N} [mul_one_class M] [mul_one_class N] /-- The equivalence between `M × N` and `N × M` given by swapping the components is multiplicative. -/ @[to_additive prod_comm "The equivalence between `M × N` and `N × M` given by swapping the components is additive."] def prod_comm : M × N ≃* N × M := { map_mul' := λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, rfl, ..equiv.prod_comm M N } @[simp, to_additive coe_prod_comm] lemma coe_prod_comm : ⇑(prod_comm : M × N ≃* N × M) = prod.swap := rfl @[simp, to_additive coe_prod_comm_symm] lemma coe_prod_comm_symm : ⇑((prod_comm : M × N ≃* N × M).symm) = prod.swap := rfl end section variables {M N} [monoid M] [monoid N] /-- The monoid equivalence between units of a product of two monoids, and the product of the units of each monoid. -/ @[to_additive prod_add_units "The additive monoid equivalence between additive units of a product of two additive monoids, and the product of the additive units of each additive monoid."] def prod_units : (M × N)ˣ ≃* Mˣ × Nˣ := { to_fun := (units.map (monoid_hom.fst M N)).prod (units.map (monoid_hom.snd M N)), inv_fun := λ u, ⟨(u.1, u.2), (↑u.1⁻¹, ↑u.2⁻¹), by simp, by simp⟩, left_inv := λ u, by simp, right_inv := λ ⟨u₁, u₂⟩, by simp [units.map], map_mul' := monoid_hom.map_mul _ } end end mul_equiv namespace units open mul_opposite /-- Canonical homomorphism of monoids from `αˣ` into `α × αᵐᵒᵖ`. Used mainly to define the natural topology of `αˣ`. -/ @[to_additive "Canonical homomorphism of additive monoids from `add_units α` into `α × αᵃᵒᵖ`. Used mainly to define the natural topology of `add_units α`."] def embed_product (α : Type*) [monoid α] : αˣ →* α × αᵐᵒᵖ := { to_fun := λ x, ⟨x, op ↑x⁻¹⟩, map_one' := by simp only [inv_one, eq_self_iff_true, units.coe_one, op_one, prod.mk_eq_one, and_self], map_mul' := λ x y, by simp only [mul_inv_rev, op_mul, units.coe_mul, prod.mk_mul_mk] } end units /-! ### Multiplication and division as homomorphisms -/ section bundled_mul_div variables {α : Type*} /-- Multiplication as a multiplicative homomorphism. -/ @[to_additive "Addition as an additive homomorphism.", simps] def mul_mul_hom [comm_semigroup α] : (α × α) →ₙ* α := { to_fun := λ a, a.1 * a.2, map_mul' := λ a b, mul_mul_mul_comm _ _ _ _ } /-- Multiplication as a monoid homomorphism. -/ @[to_additive "Addition as an additive monoid homomorphism.", simps] def mul_monoid_hom [comm_monoid α] : α × α →* α := { map_one' := mul_one _, .. mul_mul_hom } /-- Multiplication as a multiplicative homomorphism with zero. -/ @[simps] def mul_monoid_with_zero_hom [comm_monoid_with_zero α] : α × α →*₀ α := { map_zero' := mul_zero _, .. mul_monoid_hom } /-- Division as a monoid homomorphism. -/ @[to_additive "Subtraction as an additive monoid homomorphism.", simps] def div_monoid_hom [comm_group α] : α × α →* α := { to_fun := λ a, a.1 / a.2, map_one' := div_one _, map_mul' := λ a b, mul_div_mul_comm _ _ _ _ } /-- Division as a multiplicative homomorphism with zero. -/ @[simps] def div_monoid_with_zero_hom [comm_group_with_zero α] : α × α →*₀ α := { to_fun := λ a, a.1 / a.2, map_zero' := zero_div _, map_one' := div_one _, map_mul' := λ a b, mul_div_mul_comm _ _ _ _ } end bundled_mul_div
e26c6e8ffa11f2e326f837023d7f4fcedb4dac0f
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/expr_of_unsat.lean
1204e813cf1fa7e034c9370664708b02a48b6d02
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
1,548
lean
import .scalar .clause .eqelim open int tactic meta def expr_of_neg : int → tactic expr | (of_nat _) := failed | -[1+ m] := return `(neg_succ_lt_zero %%`(m)) lemma zero_eq_zero : (0 : int) = 0 := rfl meta def expr_of_forall_mem_eq_zero : list int → tactic expr | [] := return `(forall_mem_nil_eq_zero).to_expr | (i::is) := do x ← expr_of_forall_mem_eq_zero is, to_expr ``(forall_mem_cons_eq_zero 0 %%`(is) zero_eq_zero %%x) meta def expr_of_unsat_comb (ks : list nat) (p : list term) : tactic expr := let ⟨b,as⟩ := comb p ks in do x1 ← expr_of_neg b, x2 ← expr_of_forall_mem_eq_zero as, to_expr ``(unsat_comb_of %%`(p) %%`(ks) %%x1 %%x2) /- Given a (([],les) : clause), return the expr of a term (t : clause.unsat ([],les)). -/ meta def expr_of_unsat_ef : clause → tactic expr | ((_::_), _) := failed | ([], les) := do ks ← search les, x ← expr_of_unsat_comb ks les, return `(unsat_of_unsat_comb %%`(ks) %%`(les) %%x) /- Given a (c : clause), return the expr of a term (t : clause.unsat c) -/ meta def expr_of_unsat (c : clause) : tactic expr := do ee ← find_ees c, x ← expr_of_unsat_ef (conc ee c), return `(unsat_of_unsat_conc %%`(ee) %%`(c) %%x) /- Given a (cs : list clause), return the expr of a term (t : clauses.unsat cs) -/ meta def expr_of_unsats : list clause → tactic expr | [] := return `(clauses.unsat_nil) | (p::ps) := do x ← expr_of_unsat p, xs ← expr_of_unsats ps, to_expr ``(clauses.unsat_cons %%`(p) %%`(ps) %%x %%xs)
d61a34d54dde03bfbe20cd664a2cd0c67ef711bd
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Init/Data/ByteArray/Basic.lean
2ff05788c43e608226d3f44042b7646b0fc865b6
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
2,676
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Array.Basic import Init.Data.Array.Subarray import Init.Data.UInt import Init.Data.Option.Basic universes u structure ByteArray where data : Array UInt8 attribute [extern "lean_byte_array_mk"] ByteArray.mk attribute [extern "lean_byte_array_data"] ByteArray.data namespace ByteArray @[extern "lean_mk_empty_byte_array"] def mkEmpty (c : @& Nat) : ByteArray := { data := #[] } def empty : ByteArray := mkEmpty 0 instance : Inhabited ByteArray := ⟨empty⟩ @[extern "lean_byte_array_push"] def push : ByteArray → UInt8 → ByteArray | ⟨bs⟩, b => ⟨bs.push b⟩ @[extern "lean_byte_array_size"] def size : (@& ByteArray) → Nat | ⟨bs⟩ => bs.size @[extern "lean_byte_array_get"] def get! : (@& ByteArray) → (@& Nat) → UInt8 | ⟨bs⟩, i => bs.get! i @[extern "lean_byte_array_set"] def set! : ByteArray → (@& Nat) → UInt8 → ByteArray | ⟨bs⟩, i, b => ⟨bs.set! i b⟩ def isEmpty (s : ByteArray) : Bool := s.size == 0 /-- Copy the slice at `[srcOff, srcOff + len)` in `src` to `[destOff, destOff + len)` in `dest`, growing `dest` if necessary. If `exact` is `false`, the capacity will be doubled when grown. -/ @[extern "lean_byte_array_copy_slice"] def copySlice (src : @& ByteArray) (srcOff : Nat) (dest : ByteArray) (destOff len : Nat) (exact : Bool := true) : ByteArray := ⟨dest.data.extract 0 destOff ++ src.data.extract srcOff len ++ dest.data.extract (destOff + len) dest.data.size⟩ def extract (a : ByteArray) (b e : Nat) : ByteArray := a.copySlice b empty 0 (e - b) protected def append (a : ByteArray) (b : ByteArray) : ByteArray := -- we assume that `append`s may be repeated, so use asymptotic growing; use `copySlice` directly to customize b.copySlice 0 a a.size b.size false instance : Append ByteArray := ⟨ByteArray.append⟩ partial def toList (bs : ByteArray) : List UInt8 := let rec loop (i : Nat) (r : List UInt8) := if i < bs.size then loop (i+1) (bs.get! i :: r) else r.reverse loop 0 [] @[inline] partial def findIdx? (a : ByteArray) (p : UInt8 → Bool) (start := 0) : Option Nat := let rec @[specialize] loop (i : Nat) := if i < a.size then if p (a.get! i) then some i else loop (i+1) else none loop start end ByteArray def List.toByteArray (bs : List UInt8) : ByteArray := let rec loop | [], r => r | b::bs, r => loop bs (r.push b) loop bs ByteArray.empty instance : ToString ByteArray := ⟨fun bs => bs.toList.toString⟩
47d6499d3aae15ac5e4d75455fc8f1765809cf23
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/local_homeomorph.lean
3927b96763fcd8b095938b967a7a8d77ab74838f
[]
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
54,102
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.local_equiv import Mathlib.topology.opens import Mathlib.PostPort universes u_5 u_6 l u_1 u_2 u_3 u_4 namespace Mathlib /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. -/ /-- local homeomorphisms, defined on open subsets of the space -/ structure local_homeomorph (α : Type u_5) (β : Type u_6) [topological_space α] [topological_space β] extends local_equiv α β where open_source : is_open (local_equiv.source _to_local_equiv) open_target : is_open (local_equiv.target _to_local_equiv) continuous_to_fun : continuous_on (local_equiv.to_fun _to_local_equiv) (local_equiv.source _to_local_equiv) continuous_inv_fun : continuous_on (local_equiv.inv_fun _to_local_equiv) (local_equiv.target _to_local_equiv) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : α ≃ₜ β) : local_homeomorph α β := local_homeomorph.mk (local_equiv.mk (local_equiv.to_fun (equiv.to_local_equiv (homeomorph.to_equiv e))) (local_equiv.inv_fun (equiv.to_local_equiv (homeomorph.to_equiv e))) (local_equiv.source (equiv.to_local_equiv (homeomorph.to_equiv e))) (local_equiv.target (equiv.to_local_equiv (homeomorph.to_equiv e))) sorry sorry sorry sorry) is_open_univ is_open_univ sorry sorry namespace local_homeomorph protected instance has_coe_to_fun {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] : has_coe_to_fun (local_homeomorph α β) := has_coe_to_fun.mk (fun (e : local_homeomorph α β) => α → β) fun (e : local_homeomorph α β) => local_equiv.to_fun (to_local_equiv e) /-- The inverse of a local homeomorphism -/ protected def symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_homeomorph β α := mk (local_equiv.mk (local_equiv.to_fun (local_equiv.symm (to_local_equiv e))) (local_equiv.inv_fun (local_equiv.symm (to_local_equiv e))) (local_equiv.source (local_equiv.symm (to_local_equiv e))) (local_equiv.target (local_equiv.symm (to_local_equiv e))) sorry sorry sorry sorry) (open_target e) (open_source e) (continuous_inv_fun e) (continuous_to_fun e) protected theorem continuous_on {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : continuous_on (⇑e) (local_equiv.source (to_local_equiv e)) := continuous_to_fun e theorem continuous_on_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : continuous_on (⇑(local_homeomorph.symm e)) (local_equiv.target (to_local_equiv e)) := continuous_inv_fun e @[simp] theorem mk_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_equiv α β) (a : is_open (local_equiv.source e)) (b : is_open (local_equiv.target e)) (c : continuous_on (local_equiv.to_fun e) (local_equiv.source e)) (d : continuous_on (local_equiv.inv_fun e) (local_equiv.target e)) : ⇑(mk e a b c d) = ⇑e := rfl @[simp] theorem mk_coe_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_equiv α β) (a : is_open (local_equiv.source e)) (b : is_open (local_equiv.target e)) (c : continuous_on (local_equiv.to_fun e) (local_equiv.source e)) (d : continuous_on (local_equiv.inv_fun e) (local_equiv.target e)) : ⇑(local_homeomorph.symm (mk e a b c d)) = ⇑(local_equiv.symm e) := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp] theorem to_fun_eq_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_equiv.to_fun (to_local_equiv e) = ⇑e := rfl @[simp] theorem inv_fun_eq_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_equiv.inv_fun (to_local_equiv e) = ⇑(local_homeomorph.symm e) := rfl @[simp] theorem coe_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : ⇑(to_local_equiv e) = ⇑e := rfl @[simp] theorem coe_coe_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : ⇑(local_equiv.symm (to_local_equiv e)) = ⇑(local_homeomorph.symm e) := rfl @[simp] theorem map_source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : α} (h : x ∈ local_equiv.source (to_local_equiv e)) : coe_fn e x ∈ local_equiv.target (to_local_equiv e) := local_equiv.map_source' (to_local_equiv e) h @[simp] theorem map_target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : β} (h : x ∈ local_equiv.target (to_local_equiv e)) : coe_fn (local_homeomorph.symm e) x ∈ local_equiv.source (to_local_equiv e) := local_equiv.map_target' (to_local_equiv e) h @[simp] theorem left_inv {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : α} (h : x ∈ local_equiv.source (to_local_equiv e)) : coe_fn (local_homeomorph.symm e) (coe_fn e x) = x := local_equiv.left_inv' (to_local_equiv e) h @[simp] theorem right_inv {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : β} (h : x ∈ local_equiv.target (to_local_equiv e)) : coe_fn e (coe_fn (local_homeomorph.symm e) x) = x := local_equiv.right_inv' (to_local_equiv e) h theorem source_preimage_target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_equiv.source (to_local_equiv e) ⊆ ⇑e ⁻¹' local_equiv.target (to_local_equiv e) := fun (_x : α) (h : _x ∈ local_equiv.source (to_local_equiv e)) => map_source e h theorem eq_of_local_equiv_eq {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {e' : local_homeomorph α β} (h : to_local_equiv e = to_local_equiv e') : e = e' := sorry theorem eventually_left_inverse {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : α} (hx : x ∈ local_equiv.source (to_local_equiv e)) : filter.eventually (fun (y : α) => coe_fn (local_homeomorph.symm e) (coe_fn e y) = y) (nhds x) := filter.eventually.mono (is_open.eventually_mem (open_source e) hx) (local_equiv.left_inv' (to_local_equiv e)) theorem eventually_left_inverse' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : β} (hx : x ∈ local_equiv.target (to_local_equiv e)) : filter.eventually (fun (y : α) => coe_fn (local_homeomorph.symm e) (coe_fn e y) = y) (nhds (coe_fn (local_homeomorph.symm e) x)) := eventually_left_inverse e (map_target e hx) theorem eventually_right_inverse {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : β} (hx : x ∈ local_equiv.target (to_local_equiv e)) : filter.eventually (fun (y : β) => coe_fn e (coe_fn (local_homeomorph.symm e) y) = y) (nhds x) := filter.eventually.mono (is_open.eventually_mem (open_target e) hx) (local_equiv.right_inv' (to_local_equiv e)) theorem eventually_right_inverse' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : α} (hx : x ∈ local_equiv.source (to_local_equiv e)) : filter.eventually (fun (y : β) => coe_fn e (coe_fn (local_homeomorph.symm e) y) = y) (nhds (coe_fn e x)) := eventually_right_inverse e (map_source e hx) theorem eventually_ne_nhds_within {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : α} (hx : x ∈ local_equiv.source (to_local_equiv e)) : filter.eventually (fun (x' : α) => coe_fn e x' ≠ coe_fn e x) (nhds_within x (singleton xᶜ)) := sorry theorem image_eq_target_inter_inv_preimage {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set α} (h : s ⊆ local_equiv.source (to_local_equiv e)) : ⇑e '' s = local_equiv.target (to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' s := local_equiv.image_eq_target_inter_inv_preimage (to_local_equiv e) h theorem image_inter_source_eq {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) : ⇑e '' (s ∩ local_equiv.source (to_local_equiv e)) = local_equiv.target (to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' (s ∩ local_equiv.source (to_local_equiv e)) := image_eq_target_inter_inv_preimage e (set.inter_subset_right s (local_equiv.source (to_local_equiv e))) theorem symm_image_eq_source_inter_preimage {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set β} (h : s ⊆ local_equiv.target (to_local_equiv e)) : ⇑(local_homeomorph.symm e) '' s = local_equiv.source (to_local_equiv e) ∩ ⇑e ⁻¹' s := image_eq_target_inter_inv_preimage (local_homeomorph.symm e) h theorem symm_image_inter_target_eq {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set β) : ⇑(local_homeomorph.symm e) '' (s ∩ local_equiv.target (to_local_equiv e)) = local_equiv.source (to_local_equiv e) ∩ ⇑e ⁻¹' (s ∩ local_equiv.target (to_local_equiv e)) := image_inter_source_eq (local_homeomorph.symm e) s /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ protected theorem ext {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (e' : local_homeomorph α β) (h : ∀ (x : α), coe_fn e x = coe_fn e' x) (hinv : ∀ (x : β), coe_fn (local_homeomorph.symm e) x = coe_fn (local_homeomorph.symm e') x) (hs : local_equiv.source (to_local_equiv e) = local_equiv.source (to_local_equiv e')) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) -- The following lemmas are already simp via local_equiv @[simp] theorem symm_to_local_equiv {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : to_local_equiv (local_homeomorph.symm e) = local_equiv.symm (to_local_equiv e) := rfl theorem symm_source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_equiv.source (to_local_equiv (local_homeomorph.symm e)) = local_equiv.target (to_local_equiv e) := rfl theorem symm_target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_equiv.target (to_local_equiv (local_homeomorph.symm e)) = local_equiv.source (to_local_equiv e) := rfl @[simp] theorem symm_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_homeomorph.symm (local_homeomorph.symm e) = e := sorry /-- A local homeomorphism is continuous at any point of its source -/ protected theorem continuous_at {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : α} (h : x ∈ local_equiv.source (to_local_equiv e)) : continuous_at (⇑e) x := continuous_within_at.continuous_at (local_homeomorph.continuous_on e x h) (mem_nhds_sets (open_source e) h) /-- A local homeomorphism inverse is continuous at any point of its target -/ theorem continuous_at_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : β} (h : x ∈ local_equiv.target (to_local_equiv e)) : continuous_at (⇑(local_homeomorph.symm e)) x := local_homeomorph.continuous_at (local_homeomorph.symm e) h theorem tendsto_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : α} (hx : x ∈ local_equiv.source (to_local_equiv e)) : filter.tendsto (⇑(local_homeomorph.symm e)) (nhds (coe_fn e x)) (nhds x) := sorry theorem map_nhds_eq {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {x : α} (hx : x ∈ local_equiv.source (to_local_equiv e)) : filter.map (⇑e) (nhds x) = nhds (coe_fn e x) := le_antisymm (local_homeomorph.continuous_at e hx) (filter.le_map_of_right_inverse (eventually_right_inverse' e hx) (tendsto_symm e hx)) /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ theorem preimage_interior {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set β) : local_equiv.source (to_local_equiv e) ∩ ⇑e ⁻¹' interior s = local_equiv.source (to_local_equiv e) ∩ interior (⇑e ⁻¹' s) := sorry theorem preimage_open_of_open {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set β} (hs : is_open s) : is_open (local_equiv.source (to_local_equiv e) ∩ ⇑e ⁻¹' s) := continuous_on.preimage_open_of_open (local_homeomorph.continuous_on e) (open_source e) hs theorem preimage_open_of_open_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set α} (hs : is_open s) : is_open (local_equiv.target (to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' s) := continuous_on.preimage_open_of_open (local_homeomorph.continuous_on (local_homeomorph.symm e)) (open_target e) hs /-- The image of an open set in the source is open. -/ theorem image_open_of_open {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set α} (hs : is_open s) (h : s ⊆ local_equiv.source (to_local_equiv e)) : is_open (⇑e '' s) := eq.mpr (id (Eq._oldrec (Eq.refl (is_open (⇑e '' s))) (local_equiv.image_eq_target_inter_inv_preimage (to_local_equiv e) h))) (continuous_on.preimage_open_of_open (continuous_on_symm e) (open_target e) hs) /-- The image of the restriction of an open set to the source is open. -/ theorem image_open_of_open' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set α} (hs : is_open s) : is_open (⇑e '' (s ∩ local_equiv.source (to_local_equiv e))) := sorry /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) (hs : is_open s) : local_homeomorph α β := mk (local_equiv.mk (local_equiv.to_fun (local_equiv.restr (to_local_equiv e) s)) (local_equiv.inv_fun (local_equiv.restr (to_local_equiv e) s)) (local_equiv.source (local_equiv.restr (to_local_equiv e) s)) (local_equiv.target (local_equiv.restr (to_local_equiv e) s)) sorry sorry sorry sorry) sorry sorry sorry sorry @[simp] theorem restr_open_to_local_equiv {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) (hs : is_open s) : to_local_equiv (local_homeomorph.restr_open e s hs) = local_equiv.restr (to_local_equiv e) s := rfl -- Already simp via local_equiv theorem restr_open_source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) (hs : is_open s) : local_equiv.source (to_local_equiv (local_homeomorph.restr_open e s hs)) = local_equiv.source (to_local_equiv e) ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ protected def restr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) : local_homeomorph α β := local_homeomorph.restr_open e (interior s) is_open_interior @[simp] theorem restr_to_local_equiv {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) : to_local_equiv (local_homeomorph.restr e s) = local_equiv.restr (to_local_equiv e) (interior s) := rfl @[simp] theorem restr_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) : ⇑(local_homeomorph.restr e s) = ⇑e := rfl @[simp] theorem restr_coe_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) : ⇑(local_homeomorph.symm (local_homeomorph.restr e s)) = ⇑(local_homeomorph.symm e) := rfl theorem restr_source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) : local_equiv.source (to_local_equiv (local_homeomorph.restr e s)) = local_equiv.source (to_local_equiv e) ∩ interior s := rfl theorem restr_target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) : local_equiv.target (to_local_equiv (local_homeomorph.restr e s)) = local_equiv.target (to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' interior s := rfl theorem restr_source' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) (hs : is_open s) : local_equiv.source (to_local_equiv (local_homeomorph.restr e s)) = local_equiv.source (to_local_equiv e) ∩ s := sorry theorem restr_to_local_equiv' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) (hs : is_open s) : to_local_equiv (local_homeomorph.restr e s) = local_equiv.restr (to_local_equiv e) s := sorry theorem restr_eq_of_source_subset {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {s : set α} (h : local_equiv.source (to_local_equiv e) ⊆ s) : local_homeomorph.restr e s = e := sorry @[simp] theorem restr_univ {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} : local_homeomorph.restr e set.univ = e := restr_eq_of_source_subset (set.subset_univ (local_equiv.source (to_local_equiv e))) theorem restr_source_inter {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : set α) : local_homeomorph.restr e (local_equiv.source (to_local_equiv e) ∩ s) = local_homeomorph.restr e s := sorry /-- The identity on the whole space as a local homeomorphism. -/ protected def refl (α : Type u_1) [topological_space α] : local_homeomorph α α := homeomorph.to_local_homeomorph (homeomorph.refl α) @[simp] theorem refl_local_equiv {α : Type u_1} [topological_space α] : to_local_equiv (local_homeomorph.refl α) = local_equiv.refl α := rfl theorem refl_source {α : Type u_1} [topological_space α] : local_equiv.source (to_local_equiv (local_homeomorph.refl α)) = set.univ := rfl theorem refl_target {α : Type u_1} [topological_space α] : local_equiv.target (to_local_equiv (local_homeomorph.refl α)) = set.univ := rfl @[simp] theorem refl_symm {α : Type u_1} [topological_space α] : local_homeomorph.symm (local_homeomorph.refl α) = local_homeomorph.refl α := rfl @[simp] theorem refl_coe {α : Type u_1} [topological_space α] : ⇑(local_homeomorph.refl α) = id := rfl /-- The identity local equiv on a set `s` -/ def of_set {α : Type u_1} [topological_space α] (s : set α) (hs : is_open s) : local_homeomorph α α := mk (local_equiv.mk (local_equiv.to_fun (local_equiv.of_set s)) (local_equiv.inv_fun (local_equiv.of_set s)) (local_equiv.source (local_equiv.of_set s)) (local_equiv.target (local_equiv.of_set s)) sorry sorry sorry sorry) hs hs sorry sorry @[simp] theorem of_set_to_local_equiv {α : Type u_1} [topological_space α] {s : set α} (hs : is_open s) : to_local_equiv (of_set s hs) = local_equiv.of_set s := rfl theorem of_set_source {α : Type u_1} [topological_space α] {s : set α} (hs : is_open s) : local_equiv.source (to_local_equiv (of_set s hs)) = s := rfl theorem of_set_target {α : Type u_1} [topological_space α] {s : set α} (hs : is_open s) : local_equiv.target (to_local_equiv (of_set s hs)) = s := rfl @[simp] theorem of_set_coe {α : Type u_1} [topological_space α] {s : set α} (hs : is_open s) : ⇑(of_set s hs) = id := rfl @[simp] theorem of_set_symm {α : Type u_1} [topological_space α] {s : set α} (hs : is_open s) : local_homeomorph.symm (of_set s hs) = of_set s hs := rfl @[simp] theorem of_set_univ_eq_refl {α : Type u_1} [topological_space α] : of_set set.univ is_open_univ = local_homeomorph.refl α := sorry /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) (h : local_equiv.target (to_local_equiv e) = local_equiv.source (to_local_equiv e')) : local_homeomorph α γ := mk (local_equiv.mk (local_equiv.to_fun (local_equiv.trans' (to_local_equiv e) (to_local_equiv e') h)) (local_equiv.inv_fun (local_equiv.trans' (to_local_equiv e) (to_local_equiv e') h)) (local_equiv.source (local_equiv.trans' (to_local_equiv e) (to_local_equiv e') h)) (local_equiv.target (local_equiv.trans' (to_local_equiv e) (to_local_equiv e') h)) sorry sorry sorry sorry) (open_source e) (open_target e') sorry sorry /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : local_homeomorph α γ := local_homeomorph.trans' (local_homeomorph.symm (local_homeomorph.restr_open (local_homeomorph.symm e) (local_equiv.source (to_local_equiv e')) (open_source e'))) (local_homeomorph.restr_open e' (local_equiv.target (to_local_equiv e)) (open_target e)) sorry @[simp] theorem trans_to_local_equiv {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : to_local_equiv (local_homeomorph.trans e e') = local_equiv.trans (to_local_equiv e) (to_local_equiv e') := rfl @[simp] theorem coe_trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : ⇑(local_homeomorph.trans e e') = ⇑e' ∘ ⇑e := rfl @[simp] theorem coe_trans_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : ⇑(local_homeomorph.symm (local_homeomorph.trans e e')) = ⇑(local_homeomorph.symm e) ∘ ⇑(local_homeomorph.symm e') := rfl theorem trans_symm_eq_symm_trans_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : local_homeomorph.symm (local_homeomorph.trans e e') = local_homeomorph.trans (local_homeomorph.symm e') (local_homeomorph.symm e) := sorry /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ theorem trans_source {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : local_equiv.source (to_local_equiv (local_homeomorph.trans e e')) = local_equiv.source (to_local_equiv e) ∩ ⇑e ⁻¹' local_equiv.source (to_local_equiv e') := local_equiv.trans_source (to_local_equiv e) (to_local_equiv e') theorem trans_source' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : local_equiv.source (to_local_equiv (local_homeomorph.trans e e')) = local_equiv.source (to_local_equiv e) ∩ ⇑e ⁻¹' (local_equiv.target (to_local_equiv e) ∩ local_equiv.source (to_local_equiv e')) := local_equiv.trans_source' (to_local_equiv e) (to_local_equiv e') theorem trans_source'' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : local_equiv.source (to_local_equiv (local_homeomorph.trans e e')) = ⇑(local_homeomorph.symm e) '' (local_equiv.target (to_local_equiv e) ∩ local_equiv.source (to_local_equiv e')) := local_equiv.trans_source'' (to_local_equiv e) (to_local_equiv e') theorem image_trans_source {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : ⇑e '' local_equiv.source (to_local_equiv (local_homeomorph.trans e e')) = local_equiv.target (to_local_equiv e) ∩ local_equiv.source (to_local_equiv e') := local_equiv.image_trans_source (to_local_equiv e) (to_local_equiv e') theorem trans_target {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : local_equiv.target (to_local_equiv (local_homeomorph.trans e e')) = local_equiv.target (to_local_equiv e') ∩ ⇑(local_homeomorph.symm e') ⁻¹' local_equiv.target (to_local_equiv e) := rfl theorem trans_target' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : local_equiv.target (to_local_equiv (local_homeomorph.trans e e')) = local_equiv.target (to_local_equiv e') ∩ ⇑(local_homeomorph.symm e') ⁻¹' (local_equiv.source (to_local_equiv e') ∩ local_equiv.target (to_local_equiv e)) := trans_source' (local_homeomorph.symm e') (local_homeomorph.symm e) theorem trans_target'' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : local_equiv.target (to_local_equiv (local_homeomorph.trans e e')) = ⇑e' '' (local_equiv.source (to_local_equiv e') ∩ local_equiv.target (to_local_equiv e)) := trans_source'' (local_homeomorph.symm e') (local_homeomorph.symm e) theorem inv_image_trans_target {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) : ⇑(local_homeomorph.symm e') '' local_equiv.target (to_local_equiv (local_homeomorph.trans e e')) = local_equiv.source (to_local_equiv e') ∩ local_equiv.target (to_local_equiv e) := image_trans_source (local_homeomorph.symm e') (local_homeomorph.symm e) theorem trans_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) (e'' : local_homeomorph γ δ) : local_homeomorph.trans (local_homeomorph.trans e e') e'' = local_homeomorph.trans e (local_homeomorph.trans e' e'') := eq_of_local_equiv_eq (local_equiv.trans_assoc (to_local_equiv e) (to_local_equiv e') (to_local_equiv e'')) @[simp] theorem trans_refl {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_homeomorph.trans e (local_homeomorph.refl β) = e := eq_of_local_equiv_eq (local_equiv.trans_refl (to_local_equiv e)) @[simp] theorem refl_trans {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_homeomorph.trans (local_homeomorph.refl α) e = e := eq_of_local_equiv_eq (local_equiv.refl_trans (to_local_equiv e)) theorem trans_of_set {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set β} (hs : is_open s) : local_homeomorph.trans e (of_set s hs) = local_homeomorph.restr e (⇑e ⁻¹' s) := sorry theorem trans_of_set' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set β} (hs : is_open s) : local_homeomorph.trans e (of_set s hs) = local_homeomorph.restr e (local_equiv.source (to_local_equiv e) ∩ ⇑e ⁻¹' s) := sorry theorem of_set_trans {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set α} (hs : is_open s) : local_homeomorph.trans (of_set s hs) e = local_homeomorph.restr e s := sorry theorem of_set_trans' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) {s : set α} (hs : is_open s) : local_homeomorph.trans (of_set s hs) e = local_homeomorph.restr e (local_equiv.source (to_local_equiv e) ∩ s) := sorry @[simp] theorem of_set_trans_of_set {α : Type u_1} [topological_space α] {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : local_homeomorph.trans (of_set s hs) (of_set s' hs') = of_set (s ∩ s') (is_open_inter hs hs') := sorry theorem restr_trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) (e' : local_homeomorph β γ) (s : set α) : local_homeomorph.trans (local_homeomorph.restr e s) e' = local_homeomorph.restr (local_homeomorph.trans e e') s := eq_of_local_equiv_eq (local_equiv.restr_trans (to_local_equiv e) (to_local_equiv e') (interior s)) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (e' : local_homeomorph α β) := local_equiv.source (to_local_equiv e) = local_equiv.source (to_local_equiv e') ∧ set.eq_on (⇑e) (⇑e') (local_equiv.source (to_local_equiv e)) theorem eq_on_source_iff {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source (to_local_equiv e) (to_local_equiv e') := iff.rfl /-- `eq_on_source` is an equivalence relation -/ protected instance setoid {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] : setoid (local_homeomorph α β) := setoid.mk eq_on_source sorry theorem eq_on_source_refl {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : e ≈ e := setoid.refl e /-- If two local homeomorphisms are equivalent, so are their inverses -/ theorem eq_on_source.symm' {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {e' : local_homeomorph α β} (h : e ≈ e') : local_homeomorph.symm e ≈ local_homeomorph.symm e' := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ theorem eq_on_source.source_eq {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {e' : local_homeomorph α β} (h : e ≈ e') : local_equiv.source (to_local_equiv e) = local_equiv.source (to_local_equiv e') := and.left h /-- Two equivalent local homeomorphisms have the same target -/ theorem eq_on_source.target_eq {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {e' : local_homeomorph α β} (h : e ≈ e') : local_equiv.target (to_local_equiv e) = local_equiv.target (to_local_equiv e') := and.left (eq_on_source.symm' h) /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ theorem eq_on_source.eq_on {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {e' : local_homeomorph α β} (h : e ≈ e') : set.eq_on (⇑e) (⇑e') (local_equiv.source (to_local_equiv e)) := and.right h /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ theorem eq_on_source.symm_eq_on_target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {e' : local_homeomorph α β} (h : e ≈ e') : set.eq_on (⇑(local_homeomorph.symm e)) (⇑(local_homeomorph.symm e')) (local_equiv.target (to_local_equiv e)) := and.right (eq_on_source.symm' h) /-- Composition of local homeomorphisms respects equivalence -/ theorem eq_on_source.trans' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {e : local_homeomorph α β} {e' : local_homeomorph α β} {f : local_homeomorph β γ} {f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : local_homeomorph.trans e f ≈ local_homeomorph.trans e' f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ theorem eq_on_source.restr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : local_homeomorph.restr e s ≈ local_homeomorph.restr e' s := local_equiv.eq_on_source.restr he (interior s) /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ theorem trans_self_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_homeomorph.trans e (local_homeomorph.symm e) ≈ of_set (local_equiv.source (to_local_equiv e)) (open_source e) := local_equiv.trans_self_symm (to_local_equiv e) theorem trans_symm_self {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) : local_homeomorph.trans (local_homeomorph.symm e) e ≈ of_set (local_equiv.target (to_local_equiv e)) (open_target e) := trans_self_symm (local_homeomorph.symm e) theorem eq_of_eq_on_source_univ {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {e : local_homeomorph α β} {e' : local_homeomorph α β} (h : e ≈ e') (s : local_equiv.source (to_local_equiv e) = set.univ) (t : local_equiv.target (to_local_equiv e) = set.univ) : e = e' := eq_of_local_equiv_eq (local_equiv.eq_of_eq_on_source_univ (to_local_equiv e) (to_local_equiv e') h s t) /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ def prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := mk (local_equiv.mk (local_equiv.to_fun (local_equiv.prod (to_local_equiv e) (to_local_equiv e'))) (local_equiv.inv_fun (local_equiv.prod (to_local_equiv e) (to_local_equiv e'))) (local_equiv.source (local_equiv.prod (to_local_equiv e) (to_local_equiv e'))) (local_equiv.target (local_equiv.prod (to_local_equiv e) (to_local_equiv e'))) sorry sorry sorry sorry) sorry sorry sorry sorry @[simp] theorem prod_to_local_equiv {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : to_local_equiv (prod e e') = local_equiv.prod (to_local_equiv e) (to_local_equiv e') := rfl theorem prod_source {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_equiv.source (to_local_equiv (prod e e')) = set.prod (local_equiv.source (to_local_equiv e)) (local_equiv.source (to_local_equiv e')) := rfl theorem prod_target {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_equiv.target (to_local_equiv (prod e e')) = set.prod (local_equiv.target (to_local_equiv e)) (local_equiv.target (to_local_equiv e')) := rfl @[simp] theorem prod_coe {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : ⇑(prod e e') = fun (p : α × γ) => (coe_fn e (prod.fst p), coe_fn e' (prod.snd p)) := rfl theorem prod_coe_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : ⇑(local_homeomorph.symm (prod e e')) = fun (p : β × δ) => (coe_fn (local_homeomorph.symm e) (prod.fst p), coe_fn (local_homeomorph.symm e') (prod.snd p)) := rfl @[simp] theorem prod_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph.symm (prod e e') = prod (local_homeomorph.symm e) (local_homeomorph.symm e') := rfl @[simp] theorem prod_trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {η : Type u_5} {ε : Type u_6} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : local_homeomorph.trans (prod e e') (prod f f') = prod (local_homeomorph.trans e f) (local_homeomorph.trans e' f') := sorry /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ theorem continuous_within_at_iff_continuous_within_at_comp_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) {f : β → γ} {s : set β} {x : β} (h : x ∈ local_equiv.target (to_local_equiv e)) : continuous_within_at f s x ↔ continuous_within_at (f ∘ ⇑e) (⇑e ⁻¹' s) (coe_fn (local_homeomorph.symm e) x) := sorry /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ theorem continuous_at_iff_continuous_at_comp_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) {f : β → γ} {x : β} (h : x ∈ local_equiv.target (to_local_equiv e)) : continuous_at f x ↔ continuous_at (f ∘ ⇑e) (coe_fn (local_homeomorph.symm e) x) := sorry /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ theorem continuous_on_iff_continuous_on_comp_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) {f : β → γ} {s : set β} (h : s ⊆ local_equiv.target (to_local_equiv e)) : continuous_on f s ↔ continuous_on (f ∘ ⇑e) (local_equiv.source (to_local_equiv e) ∩ ⇑e ⁻¹' s) := sorry /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ theorem continuous_within_at_iff_continuous_within_at_comp_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ local_equiv.source (to_local_equiv e)) (h : f ⁻¹' local_equiv.source (to_local_equiv e) ∈ nhds_within x s) : continuous_within_at f s x ↔ continuous_within_at (⇑e ∘ f) s x := sorry /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ theorem continuous_at_iff_continuous_at_comp_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) {f : γ → α} {x : γ} (h : f ⁻¹' local_equiv.source (to_local_equiv e) ∈ nhds x) : continuous_at f x ↔ continuous_at (⇑e ∘ f) x := sorry /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ theorem continuous_on_iff_continuous_on_comp_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : local_homeomorph α β) {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' local_equiv.source (to_local_equiv e)) : continuous_on f s ↔ continuous_on (⇑e ∘ f) s := sorry /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ def to_homeomorph_of_source_eq_univ_target_eq_univ {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (h : local_equiv.source (to_local_equiv e) = set.univ) (h' : local_equiv.target (to_local_equiv e) = set.univ) : α ≃ₜ β := homeomorph.mk (equiv.mk ⇑e ⇑(local_homeomorph.symm e) sorry sorry) @[simp] theorem to_homeomorph_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (h : local_equiv.source (to_local_equiv e) = set.univ) (h' : local_equiv.target (to_local_equiv e) = set.univ) : ⇑(to_homeomorph_of_source_eq_univ_target_eq_univ e h h') = ⇑e := rfl @[simp] theorem to_homeomorph_symm_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (h : local_equiv.source (to_local_equiv e) = set.univ) (h' : local_equiv.target (to_local_equiv e) = set.univ) : ⇑(homeomorph.symm (to_homeomorph_of_source_eq_univ_target_eq_univ e h h')) = ⇑(local_homeomorph.symm e) := rfl /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ theorem to_open_embedding {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (h : local_equiv.source (to_local_equiv e) = set.univ) : open_embedding (local_equiv.to_fun (to_local_equiv e)) := sorry end local_homeomorph namespace homeomorph /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ @[simp] theorem to_local_homeomorph_source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : α ≃ₜ β) : local_equiv.source (local_homeomorph.to_local_equiv (to_local_homeomorph e)) = set.univ := rfl @[simp] theorem to_local_homeomorph_target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : α ≃ₜ β) : local_equiv.target (local_homeomorph.to_local_equiv (to_local_homeomorph e)) = set.univ := rfl @[simp] theorem to_local_homeomorph_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : α ≃ₜ β) : ⇑(to_local_homeomorph e) = ⇑e := rfl @[simp] theorem to_local_homeomorph_coe_symm {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : α ≃ₜ β) : ⇑(local_homeomorph.symm (to_local_homeomorph e)) = ⇑(homeomorph.symm e) := rfl @[simp] theorem refl_to_local_homeomorph {α : Type u_1} [topological_space α] : to_local_homeomorph (homeomorph.refl α) = local_homeomorph.refl α := rfl @[simp] theorem symm_to_local_homeomorph {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : α ≃ₜ β) : to_local_homeomorph (homeomorph.symm e) = local_homeomorph.symm (to_local_homeomorph e) := rfl @[simp] theorem trans_to_local_homeomorph {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] (e : α ≃ₜ β) (e' : β ≃ₜ γ) : to_local_homeomorph (homeomorph.trans e e') = local_homeomorph.trans (to_local_homeomorph e) (to_local_homeomorph e') := local_homeomorph.eq_of_local_equiv_eq (equiv.trans_to_local_equiv (to_equiv e) (to_equiv e')) end homeomorph namespace open_embedding /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local equivalence whose source is all of `α`. This is mainly an auxiliary lemma for the stronger result `to_local_homeomorph`. -/ def to_local_equiv {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : local_equiv α β := set.inj_on.to_local_equiv f set.univ sorry @[simp] theorem to_local_equiv_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : ⇑(to_local_equiv h) = f := rfl @[simp] theorem to_local_equiv_source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : local_equiv.source (to_local_equiv h) = set.univ := rfl @[simp] theorem to_local_equiv_target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : local_equiv.target (to_local_equiv h) = set.range f := sorry theorem open_target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : is_open (local_equiv.target (to_local_equiv h)) := sorry theorem continuous_inv_fun {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : continuous_on (local_equiv.inv_fun (to_local_equiv h)) (local_equiv.target (to_local_equiv h)) := sorry /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ def to_local_homeomorph {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : local_homeomorph α β := local_homeomorph.mk (to_local_equiv h) is_open_univ (open_target h) sorry (continuous_inv_fun h) @[simp] theorem to_local_homeomorph_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : ⇑(to_local_homeomorph h) = f := rfl @[simp] theorem source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : local_equiv.source (local_homeomorph.to_local_equiv (to_local_homeomorph h)) = set.univ := rfl @[simp] theorem target {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Nonempty α] {f : α → β} (h : open_embedding f) : local_equiv.target (local_homeomorph.to_local_equiv (to_local_homeomorph h)) = set.range f := to_local_equiv_target h end open_embedding -- We close and reopen the namespace to avoid -- picking up the unnecessary `[nonempty α]` typeclass argument namespace open_embedding theorem continuous_at_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [topological_space α] [topological_space β] [topological_space γ] {f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} : continuous_at (g ∘ f) x ↔ continuous_at g (f x) := sorry end open_embedding namespace topological_space.opens /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ def local_homeomorph_subtype_coe {α : Type u_1} [topological_space α] (s : opens α) [Nonempty ↥s] : local_homeomorph (↥s) α := open_embedding.to_local_homeomorph sorry @[simp] theorem local_homeomorph_subtype_coe_coe {α : Type u_1} [topological_space α] (s : opens α) [Nonempty ↥s] : ⇑(local_homeomorph_subtype_coe s) = coe := rfl @[simp] theorem local_homeomorph_subtype_coe_source {α : Type u_1} [topological_space α] (s : opens α) [Nonempty ↥s] : local_equiv.source (local_homeomorph.to_local_equiv (local_homeomorph_subtype_coe s)) = set.univ := rfl @[simp] theorem local_homeomorph_subtype_coe_target {α : Type u_1} [topological_space α] (s : opens α) [Nonempty ↥s] : local_equiv.target (local_homeomorph.to_local_equiv (local_homeomorph_subtype_coe s)) = ↑s := sorry end topological_space.opens namespace local_homeomorph /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ def subtype_restr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : topological_space.opens α) [Nonempty ↥s] : local_homeomorph (↥s) β := local_homeomorph.trans (topological_space.opens.local_homeomorph_subtype_coe s) e theorem subtype_restr_def {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : topological_space.opens α) [Nonempty ↥s] : subtype_restr e s = local_homeomorph.trans (topological_space.opens.local_homeomorph_subtype_coe s) e := rfl @[simp] theorem subtype_restr_coe {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : topological_space.opens α) [Nonempty ↥s] : ⇑(subtype_restr e s) = set.restrict ⇑e ↑s := rfl @[simp] theorem subtype_restr_source {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (e : local_homeomorph α β) (s : topological_space.opens α) [Nonempty ↥s] : local_equiv.source (to_local_equiv (subtype_restr e s)) = coe ⁻¹' local_equiv.source (to_local_equiv e) := sorry /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ theorem subtype_restr_symm_trans_subtype_restr {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] (s : topological_space.opens α) [Nonempty ↥s] (f : local_homeomorph α β) (f' : local_homeomorph α β) : local_homeomorph.trans (local_homeomorph.symm (subtype_restr f s)) (subtype_restr f' s) ≈ local_homeomorph.restr (local_homeomorph.trans (local_homeomorph.symm f) f') (local_equiv.target (to_local_equiv f) ∩ ⇑(local_homeomorph.symm f) ⁻¹' ↑s) := sorry
5695491fb0e1ead96c528c9a7ec37f6928dd1ee1
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/algebra/module/submodule.lean
641543c68e2ee8d2d0a56eb2eeb7b50cde7da77e
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,366
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.module.linear_map import group_theory.group_action.sub_mul_action /-! # Submodules of a module In this file we define * `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to addition and scalar multiplication. * `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`. ## Tags submodule, subspace, linear map -/ open function open_locale big_operators universes u v w variables {R : Type u} {M : Type v} {ι : Type w} set_option old_structure_cmd true /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] extends add_submonoid M, sub_mul_action R M : Type v. /-- Reinterpret a `submodule` as an `add_submonoid`. -/ add_decl_doc submodule.to_add_submonoid /-- Reinterpret a `submodule` as an `sub_mul_action`. -/ add_decl_doc submodule.to_sub_mul_action namespace submodule variables [semiring R] [add_comm_monoid M] [semimodule R M] instance : has_coe_t (submodule R M) (set M) := ⟨λ s, s.carrier⟩ instance : has_mem M (submodule R M) := ⟨λ x p, x ∈ (p : set M)⟩ instance : has_coe_to_sort (submodule R M) := ⟨_, λ p, {x : M // x ∈ p}⟩ variables (p q : submodule R M) @[simp, norm_cast] theorem coe_sort_coe : ↥(p : set M) = p := rfl variables {p q} protected theorem «exists» {q : p → Prop} : (∃ x, q x) ↔ (∃ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.exists protected theorem «forall» {q : p → Prop} : (∀ x, q x) ↔ (∀ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.forall theorem coe_injective : injective (coe : submodule R M → set M) := λ p q h, by cases p; cases q; congr' @[simp, norm_cast] theorem coe_set_eq : (p : set M) = q ↔ p = q := coe_injective.eq_iff theorem ext'_iff : p = q ↔ (p : set M) = q := coe_set_eq.symm @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := coe_injective $ set.ext h theorem to_add_submonoid_injective : injective (to_add_submonoid : submodule R M → add_submonoid M) := λ p q h, ext'_iff.2 $ add_submonoid.ext'_iff.1 h @[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q := to_add_submonoid_injective.eq_iff theorem to_sub_mul_action_injective : injective (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ p q h, ext'_iff.2 $ sub_mul_action.ext'_iff.1 h @[simp] theorem to_sub_mul_action_eq : p.to_sub_mul_action = q.to_sub_mul_action ↔ p = q := to_sub_mul_action_injective.eq_iff end submodule namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variables {semimodule_M : semimodule R M} variables {p q : submodule R M} variables {r : R} {x y : M} variables (p) @[simp] lemma mem_carrier : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[simp] theorem mem_coe : x ∈ (p : set M) ↔ x ∈ p := iff.rfl @[simp] lemma zero_mem : (0 : M) ∈ p := p.zero_mem' lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add_mem' h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p := p.to_add_submonoid.sum_mem lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p := submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (hyp i hi)) @[simp] lemma smul_mem_iff' (u : units R) : (u:R) • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff' u instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance : has_scalar R p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩ @[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val variables {p} @[simp, norm_cast] lemma coe_eq_coe {x y : p} : (x : M) = y ↔ x = y := subtype.ext_iff_val.symm @[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := @coe_eq_coe _ _ _ _ _ _ x 0 @[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl @[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl @[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2 @[simp] protected lemma eta (x : p) (hx : (x : M) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx variables (p) instance : add_comm_monoid p := { add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid } instance : semimodule R p := by refine {smul := (•), ..p.to_sub_mul_action.mul_action, ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →ₗ[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((submodule.subtype p) : p → M) = subtype.val := rfl end add_comm_monoid section add_comm_group variables [ring R] [add_comm_group M] variables {semimodule_M : semimodule R M} variables (p p' : submodule R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := p.to_sub_mul_action.neg_mem hx /-- Reinterpret a submodule as an additive subgroup. -/ def to_add_subgroup : add_subgroup M := { neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid } @[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := p.to_add_subgroup.sub_mem @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := p.to_add_subgroup.neg_mem_iff lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := p.to_add_subgroup.add_mem_cancel_right lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := p.to_add_subgroup.add_mem_cancel_left instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl instance : add_comm_group p := { add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := rfl end add_comm_group end submodule namespace submodule variables [division_ring R] [add_comm_group M] [module R M] variables (p : submodule R M) {r : R} {x y : M} theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff r0 end submodule /-- Subspace of a vector space. Defined to equal `submodule`. -/ abbreviation subspace (R : Type u) (M : Type v) [field R] [add_comm_group M] [vector_space R M] := submodule R M
6a351ad39d5d62448f62f7afcd69f71309ee1df8
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/rec3.lean
e52ba103e2b0640aa3f5c28b52bbca6131b5d88e
[ "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
229
lean
set_option pp.implicit true set_option pp.notation false definition symm {A : Type} : Π {a b : A}, a = b → b = a, symm rfl := rfl definition trans {A : Type} : Π {a b c : A}, a = b → b = c → a = c, trans rfl rfl := rfl
2306b12ff1045731bc87087cd2a950c2e9f79c7b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/constructions.lean
dc5d5fce031c4bea50605d70e0f5f0984bf4160e
[ "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
42,030
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) := t.induced ulift.down lemma quotient.preimage_mem_nhds [topological_space α] [s : setoid α] {V : set $ quotient s} {a : α} (hs : V ∈ 𝓝 (quotient.mk a)) : quotient.mk ⁻¹' V ∈ 𝓝 a := preimage_nhds_coinduced hs /-- The image of a dense set under `quotient.mk` is a dense set. -/ lemma dense.quotient [setoid α] [topological_space α] {s : set α} (H : dense s) : dense (quotient.mk '' s) := (surjective_quotient_mk α).dense_range.dense_image continuous_coinduced_rng H /-- The composition of `quotient.mk` and a function with dense range has dense range. -/ lemma dense_range.quotient [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) : dense_range (quotient.mk ∘ f) := (surjective_quotient_mk α).dense_range.comp hf continuous_coinduced_rng instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t := mem_nhds_induced coe a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap coe (𝓝 (a : α)) := nhds_induced coe a end topα end constructions section prod variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] @[continuity] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p := continuous_fst.continuous_at @[continuity] lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p := continuous_snd.continuous_at @[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) @[continuity] lemma continuous.prod.mk (a : α) : continuous (prod.mk a : β → α × β) := continuous_const.prod_mk continuous_id' lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous (λ x : γ × δ, (f x.1, g x.2)) := (hf.comp continuous_fst).prod_mk (hg.comp continuous_snd) lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 := continuous_at_fst h lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 := continuous_at_snd h lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x) {pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) : ∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl_nhds b).and (hb.prod_inr_nhds a) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma continuous_uncurry_left {f : α → β → γ} (a : α) (h : continuous (function.uncurry f)) : continuous (f a) := show continuous (function.uncurry f ∘ (λ b, (a, b))), from h.comp (by continuity) lemma continuous_uncurry_right {f : α → β → γ} (b : β) (h : continuous (function.uncurry f)) : continuous (λ a, f a b) := show continuous (function.uncurry f ∘ (λ a, (a, b))), from h.comp (by continuity) lemma continuous_curry {g : α × β → γ} (a : α) (h : continuous g) : continuous (function.curry g a) := show continuous (g ∘ (λ b, (a, b))), from h.comp (by continuity) lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open.inter (hs.preimage continuous_fst) (ht.preimage continuous_snd) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), set.prod u v ⊆ s := by rw [nhds_prod_eq, mem_prod_iff] lemma mem_nhds_prod_iff' {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ u v, is_open u ∧ a ∈ u ∧ is_open v ∧ b ∈ v ∧ set.prod u v ⊆ s := begin rw mem_nhds_prod_iff, split, { rintros ⟨u, Hu, v, Hv, h⟩, rcases mem_nhds_iff.1 Hu with ⟨u', u'u, u'_open, Hu'⟩, rcases mem_nhds_iff.1 Hv with ⟨v', v'v, v'_open, Hv'⟩, exact ⟨u', v', u'_open, Hu', v'_open, Hv', (set.prod_mono u'u v'v).trans h⟩ }, { rintros ⟨u, v, u_open, au, v_open, bv, huv⟩, exact ⟨u, u_open.mem_nhds au, v, v_open.mem_nhds bv, huv⟩ } end lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa) (hb : (𝓝 b).has_basis pb sb) : (𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := by { rw nhds_prod_eq, exact ha.prod hb } lemma filter.has_basis.prod_nhds' {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {ab : α × β} (ha : (𝓝 ab.1).has_basis pa sa) (hb : (𝓝 ab.2).has_basis pb sb) : (𝓝 ab).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := by { cases ab, exact ha.prod_nhds hb } instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_iff {s : set α} {t : set β} {a : α} {b : β} : s.prod t ∈ 𝓝 (a, b) ↔ s ∈ 𝓝 a ∧ t ∈ 𝓝 b := by rw [nhds_prod_eq, prod_mem_prod_iff] lemma prod_is_open.mem_nhds {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := prod_mem_nhds_iff.2 ⟨ha, hb⟩ lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by { rw [nhds_prod_eq] at h, exact h.curry } lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f p.fst) (hg : continuous_at g p.snd) : continuous_at (λ p : α × β, (f p.1, g p.2)) p := (hf.comp continuous_at_fst).prod (hg.comp continuous_at_snd) lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) := have hf : continuous_at f (x, y).fst, from hf, have hg : continuous_at g (x, y).snd, from hg, hf.prod_map hg lemma prod_generate_from_generate_from_eq {α β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open.prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp_rw [le_principal_iff, prod.forall, ((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop], simp only [and_assoc, and.left_comm] end lemma continuous_uncurry_of_discrete_topology_left [discrete_topology α] {f : α → β → γ} (h : ∀ a, continuous (f a)) : continuous (function.uncurry f) := continuous_iff_continuous_at.2 $ λ ⟨a, b⟩, by simp only [continuous_at, nhds_prod_eq, nhds_discrete α, pure_prod, tendsto_map'_iff, (∘), function.uncurry, (h a).tendsto] /-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) : ∃U, is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s := by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx /-- `prod.fst` maps neighborhood of `x : α × β` within the section `prod.snd ⁻¹' {x.2}` to `𝓝 x.1`. -/ lemma map_fst_nhds_within (x : α × β) : map prod.fst (𝓝[prod.snd ⁻¹' {x.2}] x) = 𝓝 x.1 := begin refine le_antisymm (continuous_at_fst.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_sets_of_superset hu (λ z hz, H _ hz _ (mem_of_mem_nhds hv) rfl) end @[simp] lemma map_fst_nhds (x : α × β) : map prod.fst (𝓝 x) = 𝓝 x.1 := le_antisymm continuous_at_fst $ (map_fst_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_fst_nhds x).ge /-- `prod.snd` maps neighborhood of `x : α × β` within the section `prod.fst ⁻¹' {x.1}` to `𝓝 x.2`. -/ lemma map_snd_nhds_within (x : α × β) : map prod.snd (𝓝[prod.fst ⁻¹' {x.1}] x) = 𝓝 x.2 := begin refine le_antisymm (continuous_at_snd.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_sets_of_superset hv (λ z hz, H _ (mem_of_mem_nhds hu) _ hz rfl) end @[simp] lemma map_snd_nhds (x : α × β) : map prod.snd (𝓝 x) = 𝓝 x.2 := le_antisymm continuous_at_snd $ (map_snd_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_snd_nhds x).ge /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (set.prod s t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H, exact H.1.prod H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (set.prod s t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot lemma interior_prod_eq (s : set α) (t : set β) : interior (s.prod t) = (interior s).prod (interior t) := set.ext $ λ ⟨a, b⟩, by simp only [mem_interior_iff_mem_nhds, mem_prod, prod_mem_nhds_iff] lemma frontier_prod_eq (s : set α) (t : set β) : frontier (s.prod t) = (closure s).prod (frontier t) ∪ (frontier s).prod (closure t) := by simp only [frontier, closure_prod_eq, interior_prod_eq, prod_diff_prod] @[simp] lemma frontier_prod_univ_eq (s : set α) : frontier (s.prod (univ : set β)) = (frontier s).prod univ := by simp [frontier_prod_eq] @[simp] lemma frontier_univ_prod_eq (s : set β) : frontier ((univ : set α).prod s) = (univ : set α).prod (frontier s) := by simp [frontier_prod_eq] lemma map_mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from map_mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] /-- The product of two dense sets is a dense set. -/ lemma dense.prod {s : set α} {t : set β} (hs : dense s) (ht : dense t) : dense (s.prod t) := λ x, by { rw closure_prod_eq, exact ⟨hs x.1, ht x.2⟩ } /-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/ lemma dense_range.prod_map {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) := by simpa only [dense_range, prod_range_range_eq] using hf.prod hg lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum open sum variables [topological_space α] [topological_space β] [topological_space γ] @[continuity] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng @[continuity] lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng @[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := begin apply continuous_sup_dom; rw continuous_def at hf hg ⊢; assumption end lemma is_open_sum_iff {s : set (α ⊕ β)} : is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) := iff.rfl lemma is_open_map_sum {f : α ⊕ β → γ} (h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) : is_open_map f := begin intros u hu, rw is_open_sum_iff at hu, cases hu with hu₁ hu₂, have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u), { ext (_|_); simp }, rw [this, set.image_union, set.image_image, set.image_image], exact is_open.union (h₁ _ hu₁) (h₂ _ hu₂) end lemma embedding_inl : embedding (@inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_left }, { intros u hu, existsi (inl '' u), change (is_open (inl ⁻¹' (@inl α β '' u)) ∧ is_open (inr ⁻¹' (@inl α β '' u))) ∧ inl ⁻¹' (inl '' u) = u, have : inl ⁻¹' (@inl α β '' u) = u := preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this, have : inr ⁻¹' (@inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, inl.inj_iff.mp } lemma embedding_inr : embedding (@inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_right }, { intros u hu, existsi (inr '' u), change (is_open (inl ⁻¹' (@inr α β '' u)) ∧ is_open (inr ⁻¹' (@inr α β '' u))) ∧ inr ⁻¹' (inr '' u) = u, have : inl ⁻¹' (@inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this, have : inr ⁻¹' (@inr α β '' u) = u := preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, inr.inj_iff.mp } lemma is_open_range_inl : is_open (range (inl : α → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma is_open_range_inr : is_open (range (inr : β → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) := { open_range := is_open_range_inl, .. embedding_inl } lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) := { open_range := is_open_range_inr, .. embedding_inr } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_coe : embedding (coe : subtype p → α) := ⟨⟨rfl⟩, subtype.coe_injective⟩ lemma closed_embedding_subtype_coe (h : is_closed {a | p a}) : closed_embedding (coe : subtype p → α) := ⟨embedding_subtype_coe, by rwa [subtype.range_coe_subtype]⟩ @[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) : open_embedding (coe : s → α) := { induced := rfl, inj := subtype.coe_injective, open_range := (subtype.range_coe : range coe = s).symm ▸ hs } lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) : is_open_map (coe : s → α) := hs.open_embedding_subtype_coe.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_coe lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) : closed_embedding (coe : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.coe_injective, closed_range := (subtype.range_coe : range coe = s).symm ▸ hs } @[continuity] lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_coe lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} : continuous_at (coe : subtype p → α) a := continuous_iff_continuous_at.mp continuous_subtype_coe _ lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_of_mem $ by simpa only [subtype.coe_mk, subtype.range_coe] using h lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α)) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_mem_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map coe (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from assume i, (closed_embedding_subtype_coe (h_is_closed _)).is_closed_map _ (hs.preimage (f_cont i)), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from locally_finite.is_closed_Union (h_lf.subset $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) := closure_induced end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ @[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng @[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} @[continuity] lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i @[continuity] lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom lemma continuous_at_apply [∀i, topological_space (π i)] (i : ι) (x : Π i, π i) : continuous_at (λ p : Π i, π i, p i) x := (continuous_apply i).continuous_at lemma filter.tendsto.apply [∀i, topological_space (π i)] {l : filter α} {f : α → Π i, π i} {x : Π i, π i} (h : tendsto f l (𝓝 x)) (i : ι) : tendsto (λ a, f a i) l (𝓝 $ x i) := (continuous_at_apply i _).tendsto.comp h lemma continuous_pi_iff [topological_space α] [∀ i, topological_space (π i)] {f : α → Π i, π i} : continuous f ↔ ∀ i, continuous (λ y, f y i) := iff.intro (λ h i, (continuous_apply i).comp h) continuous_pi lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma tendsto_pi [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} : tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) := by simp [nhds_pi, filter.tendsto_comap_iff] lemma continuous_at_pi [∀ i, topological_space (π i)] [topological_space α] {f : α → Π i, π i} {x : α} : continuous_at f x ↔ ∀ i, continuous_at (λ y, f y i) x := tendsto_pi lemma filter.tendsto.update [∀i, topological_space (π i)] [decidable_eq ι] {l : filter α} {f : α → Π i, π i} {x : Π i, π i} (hf : tendsto f l (𝓝 x)) (i : ι) {g : α → π i} {xi : π i} (hg : tendsto g l (𝓝 xi)) : tendsto (λ a, function.update (f a) i (g a)) l (𝓝 $ function.update x i xi) := tendsto_pi.2 $ λ j, by { rcases em (j = i) with rfl|hj; simp [*, hf.apply] } lemma continuous_at.update [∀i, topological_space (π i)] [topological_space α] [decidable_eq ι] {f : α → Π i, π i} {a : α} (hf : continuous_at f a) (i : ι) {g : α → π i} (hg : continuous_at g a) : continuous_at (λ a, function.update (f a) i (g a)) a := hf.update i hg lemma continuous.update [∀i, topological_space (π i)] [topological_space α] [decidable_eq ι] {f : α → Π i, π i} (hf : continuous f) (i : ι) {g : α → π i} (hg : continuous g) : continuous (λ a, function.update (f a) i (g a)) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.update i hg.continuous_at /-- `function.update f i x` is continuous in `(f, x)`. -/ @[continuity] lemma continuous_update [∀i, topological_space (π i)] [decidable_eq ι] (i : ι) : continuous (λ f : (Π j, π j) × π i, function.update f.1 i f.2) := continuous_fst.update i continuous_snd lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, (hs _ ha).preimage (continuous_apply _)) lemma is_closed_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hs : ∀a∈i, is_closed (s a)) : is_closed (pi i s) := by rw [pi_def]; exact (is_closed_Inter $ λ a, is_closed_Inter $ λ ha, (hs _ ha).preimage (continuous_apply _)) lemma set_pi_mem_nhds [Π a, topological_space (π a)] {i : set ι} {s : Π a, set (π a)} {x : Π a, π a} (hi : finite i) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) : pi i s ∈ 𝓝 x := by { rw [pi_def, bInter_mem_sets hi], exact λ a ha, (continuous_apply a).continuous_at (hs a ha) } lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end /-- Suppose `π i` is a family of topological spaces indexed by `i : ι`, and `X` is a type endowed with a family of maps `f i : X → π i` for every `i : ι`, hence inducing a map `g : X → Π i, π i`. This lemma shows that infimum of the topologies on `X` induced by the `f i` as `i : ι` varies is simply the topology on `X` induced by `g : X → Π i, π i` where `Π i, π i` is endowed with the usual product topology. -/ lemma inducing_infi_to_pi {X : Type*} [∀ i, topological_space (π i)] (f : Π i, X → π i) : @inducing X (Π i, π i) (⨅ i, induced (f i) infer_instance) _ (λ x i, f i x) := begin constructor, erw induced_infi, congr' 1, funext, erw induced_compose, end variables [fintype ι] [∀ i, topological_space (π i)] [∀ i, discrete_topology (π i)] /-- A finite product of discrete spaces is discrete. -/ instance Pi.discrete_topology : discrete_topology (Π i, π i) := singletons_open_iff_discrete.mp (λ x, begin rw show {x} = ⋂ i, {y : Π i, π i | y i = x i}, { ext, simp only [function.funext_iff, set.mem_singleton_iff, set.mem_Inter, set.mem_set_of_eq] }, exact is_open_Inter (λ i, (continuous_apply i).is_open_preimage {x i} (is_open_discrete {x i})) end) end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] @[continuity] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := by simp [← is_open_compl_iff, is_open_sigma_iff] lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity] lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) @[continuity] lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma section ulift @[continuity] lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom @[continuity] lemma continuous_ulift_up [topological_space α] : continuous (ulift.up : α → ulift.{v u} α) := continuous_induced_rng continuous_id end ulift lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure t : closure_minimal h.image_subset is_closed_closure lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
e0cc648181ee049376de857e2f08212f65a29e9a
94e33a31faa76775069b071adea97e86e218a8ee
/src/probability/moments.lean
f3971855597176348d836330dc85bb2e4fb007e3
[ "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
11,085
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import probability.variance /-! # Moments and moment generating function ## Main definitions * `probability_theory.moment X p μ`: `p`th moment of a real random variable `X` with respect to measure `μ`, `μ[X^p]` * `probability_theory.central_moment X p μ`:`p`th central moment of `X` with respect to measure `μ`, `μ[(X - μ[X])^p]` * `probability_theory.mgf X μ t`: moment generating function of `X` with respect to measure `μ`, `μ[exp(t*X)]` * `probability_theory.cgf X μ t`: cumulant generating function, logarithm of the moment generating function ## Main results * `probability_theory.indep_fun.mgf_add`: if two real random variables `X` and `Y` are independent and their mgf are defined at `t`, then `mgf (X + Y) μ t = mgf X μ t * mgf Y μ t` * `probability_theory.indep_fun.cgf_add`: if two real random variables `X` and `Y` are independent and their mgf are defined at `t`, then `cgf (X + Y) μ t = cgf X μ t + cgf Y μ t` * `probability_theory.measure_ge_le_exp_cgf` and `probability_theory.measure_le_le_exp_cgf`: Chernoff bound on the upper (resp. lower) tail of a random variable. For `t` nonnegative such that the cgf exists, `ℙ(ε ≤ X) ≤ exp(- t*ε + cgf X ℙ t)`. See also `probability_theory.measure_ge_le_exp_mul_mgf` and `probability_theory.measure_le_le_exp_mul_mgf` for versions of these results using `mgf` instead of `cgf`. -/ open measure_theory filter finset real noncomputable theory open_locale big_operators measure_theory probability_theory ennreal nnreal namespace probability_theory variables {Ω : Type*} {m : measurable_space Ω} {X : Ω → ℝ} {p : ℕ} {μ : measure Ω} include m /-- Moment of a real random variable, `μ[X ^ p]`. -/ def moment (X : Ω → ℝ) (p : ℕ) (μ : measure Ω) : ℝ := μ[X ^ p] /-- Central moment of a real random variable, `μ[(X - μ[X]) ^ p]`. -/ def central_moment (X : Ω → ℝ) (p : ℕ) (μ : measure Ω) : ℝ := μ[(X - (λ x, μ[X])) ^ p] @[simp] lemma moment_zero (hp : p ≠ 0) : moment 0 p μ = 0 := by simp only [moment, hp, zero_pow', ne.def, not_false_iff, pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero] @[simp] lemma central_moment_zero (hp : p ≠ 0) : central_moment 0 p μ = 0 := by simp only [central_moment, hp, pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero, zero_sub, pi.pow_apply, pi.neg_apply, neg_zero', zero_pow', ne.def, not_false_iff] lemma central_moment_one' [is_finite_measure μ] (h_int : integrable X μ) : central_moment X 1 μ = (1 - (μ set.univ).to_real) * μ[X] := begin simp only [central_moment, pi.sub_apply, pow_one], rw integral_sub h_int (integrable_const _), simp only [sub_mul, integral_const, algebra.id.smul_eq_mul, one_mul], end @[simp] lemma central_moment_one [is_probability_measure μ] : central_moment X 1 μ = 0 := begin by_cases h_int : integrable X μ, { rw central_moment_one' h_int, simp only [measure_univ, ennreal.one_to_real, sub_self, zero_mul], }, { simp only [central_moment, pi.sub_apply, pow_one], have : ¬ integrable (λ x, X x - integral μ X) μ, { refine λ h_sub, h_int _, have h_add : X = (λ x, X x - integral μ X) + (λ x, integral μ X), { ext1 x, simp, }, rw h_add, exact h_sub.add (integrable_const _), }, rw integral_undef this, }, end @[simp] lemma central_moment_two_eq_variance : central_moment X 2 μ = variance X μ := rfl section moment_generating_function variables {t : ℝ} /-- Moment generating function of a real random variable `X`: `λ t, μ[exp(t*X)]`. -/ def mgf (X : Ω → ℝ) (μ : measure Ω) (t : ℝ) : ℝ := μ[λ ω, exp (t * X ω)] /-- Cumulant generating function of a real random variable `X`: `λ t, log μ[exp(t*X)]`. -/ def cgf (X : Ω → ℝ) (μ : measure Ω) (t : ℝ) : ℝ := log (mgf X μ t) @[simp] lemma mgf_zero_fun : mgf 0 μ t = (μ set.univ).to_real := by simp only [mgf, pi.zero_apply, mul_zero, exp_zero, integral_const, algebra.id.smul_eq_mul, mul_one] @[simp] lemma cgf_zero_fun : cgf 0 μ t = log (μ set.univ).to_real := by simp only [cgf, mgf_zero_fun] @[simp] lemma mgf_zero_measure : mgf X (0 : measure Ω) t = 0 := by simp only [mgf, integral_zero_measure] @[simp] lemma cgf_zero_measure : cgf X (0 : measure Ω) t = 0 := by simp only [cgf, log_zero, mgf_zero_measure] @[simp] lemma mgf_const' (c : ℝ) : mgf (λ _, c) μ t = (μ set.univ).to_real * exp (t * c) := by simp only [mgf, integral_const, algebra.id.smul_eq_mul] @[simp] lemma mgf_const (c : ℝ) [is_probability_measure μ] : mgf (λ _, c) μ t = exp (t * c) := by simp only [mgf_const', measure_univ, ennreal.one_to_real, one_mul] @[simp] lemma cgf_const' [is_finite_measure μ] (hμ : μ ≠ 0) (c : ℝ) : cgf (λ _, c) μ t = log (μ set.univ).to_real + t * c := begin simp only [cgf, mgf_const'], rw log_mul _ (exp_pos _).ne', { rw log_exp _, }, { rw [ne.def, ennreal.to_real_eq_zero_iff, measure.measure_univ_eq_zero], simp only [hμ, measure_ne_top μ set.univ, or_self, not_false_iff], }, end @[simp] lemma cgf_const [is_probability_measure μ] (c : ℝ) : cgf (λ _, c) μ t = t * c := by simp only [cgf, mgf_const, log_exp] @[simp] lemma mgf_zero' : mgf X μ 0 = (μ set.univ).to_real := by simp only [mgf, zero_mul, exp_zero, integral_const, algebra.id.smul_eq_mul, mul_one] @[simp] lemma mgf_zero [is_probability_measure μ] : mgf X μ 0 = 1 := by simp only [mgf_zero', measure_univ, ennreal.one_to_real] @[simp] lemma cgf_zero' : cgf X μ 0 = log (μ set.univ).to_real := by simp only [cgf, mgf_zero'] @[simp] lemma cgf_zero [is_probability_measure μ] : cgf X μ 0 = 0 := by simp only [cgf_zero', measure_univ, ennreal.one_to_real, log_one] lemma mgf_undef (hX : ¬ integrable (λ ω, exp (t * X ω)) μ) : mgf X μ t = 0 := by simp only [mgf, integral_undef hX] lemma cgf_undef (hX : ¬ integrable (λ ω, exp (t * X ω)) μ) : cgf X μ t = 0 := by simp only [cgf, mgf_undef hX, log_zero] lemma mgf_nonneg : 0 ≤ mgf X μ t := begin refine integral_nonneg _, intro ω, simp only [pi.zero_apply], exact (exp_pos _).le, end lemma mgf_pos' (hμ : μ ≠ 0) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) : 0 < mgf X μ t := begin simp_rw mgf, have : ∫ (x : Ω), exp (t * X x) ∂μ = ∫ (x : Ω) in set.univ, exp (t * X x) ∂μ, { simp only [measure.restrict_univ], }, rw [this, set_integral_pos_iff_support_of_nonneg_ae _ _], { have h_eq_univ : function.support (λ (x : Ω), exp (t * X x)) = set.univ, { ext1 x, simp only [function.mem_support, set.mem_univ, iff_true], exact (exp_pos _).ne', }, rw [h_eq_univ, set.inter_univ _], refine ne.bot_lt _, simp only [hμ, ennreal.bot_eq_zero, ne.def, measure.measure_univ_eq_zero, not_false_iff], }, { refine eventually_of_forall (λ x, _), rw pi.zero_apply, exact (exp_pos _).le, }, { rwa integrable_on_univ, }, end lemma mgf_pos [is_probability_measure μ] (h_int_X : integrable (λ ω, exp (t * X ω)) μ) : 0 < mgf X μ t := mgf_pos' (is_probability_measure.ne_zero μ) h_int_X lemma mgf_neg : mgf (-X) μ t = mgf X μ (-t) := by simp_rw [mgf, pi.neg_apply, mul_neg, neg_mul] lemma cgf_neg : cgf (-X) μ t = cgf X μ (-t) := by simp_rw [cgf, mgf_neg] lemma indep_fun.mgf_add {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) (h_int_Y : integrable (λ ω, exp (t * Y ω)) μ) : mgf (X + Y) μ t = mgf X μ t * mgf Y μ t := begin simp_rw [mgf, pi.add_apply, mul_add, exp_add], refine indep_fun.integral_mul_of_integrable' _ h_int_X h_int_Y, have h_meas : measurable (λ x, exp (t * x)) := (measurable_id'.const_mul t).exp, change indep_fun ((λ x, exp (t * x)) ∘ X) ((λ x, exp (t * x)) ∘ Y) μ, exact indep_fun.comp h_indep h_meas h_meas, end lemma indep_fun.cgf_add {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) (h_int_Y : integrable (λ ω, exp (t * Y ω)) μ) : cgf (X + Y) μ t = cgf X μ t + cgf Y μ t := begin by_cases hμ : μ = 0, { simp [hμ], }, simp only [cgf, h_indep.mgf_add h_int_X h_int_Y], exact log_mul (mgf_pos' hμ h_int_X).ne' (mgf_pos' hμ h_int_Y).ne', end /-- **Chernoff bound** on the upper tail of a real random variable. -/ lemma measure_ge_le_exp_mul_mgf [is_finite_measure μ] (ε : ℝ) (ht : 0 ≤ t) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | ε ≤ X ω}).to_real ≤ exp (- t * ε) * mgf X μ t := begin cases ht.eq_or_lt with ht_zero_eq ht_pos, { rw ht_zero_eq.symm, simp only [neg_zero', zero_mul, exp_zero, mgf_zero', one_mul], rw ennreal.to_real_le_to_real (measure_ne_top μ _) (measure_ne_top μ _), exact measure_mono (set.subset_univ _), }, calc (μ {ω | ε ≤ X ω}).to_real = (μ {ω | exp (t * ε) ≤ exp (t * X ω)}).to_real : begin congr' with ω, simp only [exp_le_exp, eq_iff_iff], exact ⟨λ h, mul_le_mul_of_nonneg_left h ht_pos.le, λ h, le_of_mul_le_mul_left h ht_pos⟩, end ... ≤ (exp (t * ε))⁻¹ * μ[λ ω, exp (t * X ω)] : begin have : exp (t * ε) * (μ {ω | exp (t * ε) ≤ exp (t * X ω)}).to_real ≤ μ[λ ω, exp (t * X ω)], from mul_meas_ge_le_integral_of_nonneg (λ x, (exp_pos _).le) h_int _, rwa [mul_comm (exp (t * ε))⁻¹, ← div_eq_mul_inv, le_div_iff' (exp_pos _)], end ... = exp (- t * ε) * mgf X μ t : by { rw [neg_mul, exp_neg], refl, }, end /-- **Chernoff bound** on the lower tail of a real random variable. -/ lemma measure_le_le_exp_mul_mgf [is_finite_measure μ] (ε : ℝ) (ht : t ≤ 0) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | X ω ≤ ε}).to_real ≤ exp (- t * ε) * mgf X μ t := begin rw [← neg_neg t, ← mgf_neg, neg_neg, ← neg_mul_neg (-t)], refine eq.trans_le _ (measure_ge_le_exp_mul_mgf (-ε) (neg_nonneg.mpr ht) _), { congr' with ω, simp only [pi.neg_apply, neg_le_neg_iff], }, { simp_rw [pi.neg_apply, neg_mul_neg], exact h_int, }, end /-- **Chernoff bound** on the upper tail of a real random variable. -/ lemma measure_ge_le_exp_cgf [is_finite_measure μ] (ε : ℝ) (ht : 0 ≤ t) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | ε ≤ X ω}).to_real ≤ exp (- t * ε + cgf X μ t) := begin refine (measure_ge_le_exp_mul_mgf ε ht h_int).trans _, rw exp_add, exact mul_le_mul le_rfl (le_exp_log _) mgf_nonneg (exp_pos _).le, end /-- **Chernoff bound** on the lower tail of a real random variable. -/ lemma measure_le_le_exp_cgf [is_finite_measure μ] (ε : ℝ) (ht : t ≤ 0) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | X ω ≤ ε}).to_real ≤ exp (- t * ε + cgf X μ t) := begin refine (measure_le_le_exp_mul_mgf ε ht h_int).trans _, rw exp_add, exact mul_le_mul le_rfl (le_exp_log _) mgf_nonneg (exp_pos _).le, end end moment_generating_function end probability_theory
fdc279f0b3a5bf9328265a4d6979fe26b0798676
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Util/ReplaceExpr.lean
d349e86dc5ca57e910fde7e3b713a1fcdbd0b3fb
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,002
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean namespace Expr namespace ReplaceImpl abbrev cacheSize : USize := 8192 structure State := (keys : Array Expr) -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr (results : Array Expr) abbrev ReplaceM := StateM State @[inline] unsafe def cache (i : USize) (key : Expr) (result : Expr) : ReplaceM Expr := do modify fun s => { keys := s.keys.uset i key lcProof, results := s.results.uset i result lcProof }; pure result @[inline] unsafe def replaceUnsafeM (f? : Expr → Option Expr) (size : USize) (e : Expr) : ReplaceM Expr := do let rec @[specialize] visit (e : Expr) := do let c ← get let h := ptrAddrUnsafe e let i := h % size if ptrAddrUnsafe (c.keys.uget i lcProof) == h then pure $ c.results.uget i lcProof else match f? e with | some eNew => cache i e eNew | none => match e with | Expr.forallE _ d b _ => cache i e $ e.updateForallE! (← visit d) (← visit b) | Expr.lam _ d b _ => cache i e $ e.updateLambdaE! (← visit d) (← visit b) | Expr.mdata _ b _ => cache i e $ e.updateMData! (← visit b) | Expr.letE _ t v b _ => cache i e $ e.updateLet! (← visit t) (← visit v) (← visit b) | Expr.app f a _ => cache i e $ e.updateApp! (← visit f) (← visit a) | Expr.proj _ _ b _ => cache i e $ e.updateProj! (← visit b) | e => pure e visit e unsafe def initCache : State := { keys := mkArray cacheSize.toNat (cast lcProof ()), -- `()` is not a valid `Expr` results := mkArray cacheSize.toNat (arbitrary _) } @[inline] unsafe def replaceUnsafe (f? : Expr → Option Expr) (e : Expr) : Expr := (replaceUnsafeM f? cacheSize e).run' initCache end ReplaceImpl /- TODO: use withPtrAddr, withPtrEq to avoid unsafe tricks above. We also need an invariant at `State` and proofs for the `uget` operations. -/ @[implementedBy ReplaceImpl.replaceUnsafe] partial def replace (f? : Expr → Option Expr) (e : Expr) : Expr := /- This is a reference implementation for the unsafe one above -/ match f? e with | some eNew => eNew | none => match e with | Expr.forallE _ d b _ => let d := replace f? d; let b := replace f? b; e.updateForallE! d b | Expr.lam _ d b _ => let d := replace f? d; let b := replace f? b; e.updateLambdaE! d b | Expr.mdata _ b _ => let b := replace f? b; e.updateMData! b | Expr.letE _ t v b _ => let t := replace f? t; let v := replace f? v; let b := replace f? b; e.updateLet! t v b | Expr.app f a _ => let f := replace f? f; let a := replace f? a; e.updateApp! f a | Expr.proj _ _ b _ => let b := replace f? b; e.updateProj! b | e => e end Expr end Lean
b81426dbc411ad1fe92085fb5cccb6d3fc4380c4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finsupp/default.lean
1853d56cd28fa1483fe9fc0033bc63b6eceaf35b
[ "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
248
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.finsupp.defs /-! # Default finsupp file This file imports `data.finsupp.basic` -/
c8c6c169ea90a81c9dd6625d21745620d14f2a89
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eqn_compiler_perf_issue2.lean
c71bf7da102d3da2db0f934e046424ff265014f5
[ "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
203
lean
def expensive (n : ℕ) : ℕ := 100000000000000 - 100000000000000 def foo : ℕ → ℕ | n := expensive n #print foo #print foo._main def bla : ℕ → ℕ | 100 := expensive 0 | _ := expensive 1
441937148c60fc206b0c67bffb70eebccfd267ff
367134ba5a65885e863bdc4507601606690974c1
/src/data/mv_polynomial/variables.lean
6a508d8c6cdd1d98a3c84b42eeb7fdbfff40c8e7
[ "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
23,037
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.monad import data.set.disjointed /-! # Degrees and variables of polynomials This file establishes many results about the degree and variable sets of a multivariate polynomial. The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$ that appears in a monomial in $P$. The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a monomial of $P$. ## Main declarations * `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets corresponding to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}` * `mv_polynomial.vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then `vars p = {x, y, z}` * `mv_polynomial.degree_of n p : ℕ` : the total degree of `p` with respect to the variable `n`. For example if `p = x⁴y+yz` then `degree_of y p = 1`. * `mv_polynomial.total_degree p : ℕ` : the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`. ## Notation As in other polynomial files, we typically use the 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` + `r : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ τ : Type*} {r : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} section degrees /-! ### `degrees` -/ /-- The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset. (For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.) -/ def degrees (p : mv_polynomial σ R) : multiset σ := p.support.sup (λs:σ →₀ ℕ, s.to_multiset) lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset := finset.sup_le $ assume t h, begin have := finsupp.support_single_subset h, rw [finset.mem_singleton] at this, rw this end lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) : degrees (monomial s a) = s.to_multiset := le_antisymm (degrees_monomial s a) $ finset.le_sup $ by rw [support_monomial, if_neg ha, finset.mem_singleton] lemma degrees_C (a : R) : degrees (C a : mv_polynomial σ R) = 0 := multiset.le_zero.1 $ degrees_monomial _ _ lemma degrees_X' (n : σ) : degrees (X n : mv_polynomial σ R) ≤ {n} := le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _ @[simp] lemma degrees_X [nontrivial R] (n : σ) : degrees (X n : mv_polynomial σ R) = {n} := (degrees_monomial_eq _ _ one_ne_zero).trans (to_multiset_single _ _) @[simp] lemma degrees_zero : degrees (0 : mv_polynomial σ R) = 0 := by { rw ← C_0, exact degrees_C 0 } @[simp] lemma degrees_one : degrees (1 : mv_polynomial σ R) = 0 := degrees_C 1 lemma degrees_add (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees := begin refine finset.sup_le (assume b hb, _), have := finsupp.support_add hb, rw finset.mem_union at this, cases this, { exact le_sup_left_of_le (finset.le_sup this) }, { exact le_sup_right_of_le (finset.le_sup this) }, end lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) := begin refine s.induction _ _, { simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ }, { assume i s his ih, rw [finset.sup_insert, finset.sum_insert his], exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) } end lemma degrees_mul (p q : mv_polynomial σ R) : (p * q).degrees ≤ p.degrees + q.degrees := begin refine finset.sup_le (assume b hb, _), have := support_mul p q hb, simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.to_multiset_add], exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) end lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees := begin refine s.induction _ _, { simp only [finset.prod_empty, finset.sum_empty, degrees_one] }, { assume i s his ih, rw [finset.prod_insert his, finset.sum_insert his], exact le_trans (degrees_mul _ _) (add_le_add_left ih _) } end lemma degrees_pow (p : mv_polynomial σ R) : ∀(n : ℕ), (p^n).degrees ≤ n •ℕ p.degrees | 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end | (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _) lemma mem_degrees {p : mv_polynomial σ R} {i : σ} : i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support := by simp only [degrees, multiset.mem_sup, ← mem_support_iff, finsupp.mem_to_multiset, exists_prop] lemma le_degrees_add {p q : mv_polynomial σ R} (h : p.degrees.disjoint q.degrees) : p.degrees ≤ (p + q).degrees := begin apply finset.sup_le, intros d hd, rw multiset.disjoint_iff_ne at h, rw multiset.le_iff_count, intros i, rw [degrees, multiset.count_sup], simp only [finsupp.count_to_multiset], by_cases h0 : d = 0, { simp only [h0, zero_le, finsupp.zero_apply], }, { refine @finset.le_sup _ _ _ (p + q).support _ d _, rw [mem_support_iff, coeff_add], suffices : q.coeff d = 0, { rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], }, rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0, obtain ⟨j, hj⟩ := h0, contrapose! h, rw mem_support_iff at hd, refine ⟨j, _, j, _, rfl⟩, all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } } end lemma degrees_add_of_disjoint {p q : mv_polynomial σ R} (h : multiset.disjoint p.degrees q.degrees) : (p + q).degrees = p.degrees ∪ q.degrees := begin apply le_antisymm, { apply degrees_add }, { apply multiset.union_le, { apply le_degrees_add h }, { rw add_comm, apply le_degrees_add h.symm } } end lemma degrees_map [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) : (map f p).degrees ⊆ p.degrees := begin dsimp only [degrees], apply multiset.subset_of_le, convert finset.sup_subset _ _, apply mv_polynomial.support_map_subset end lemma degrees_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).degrees ⊆ (φ.degrees.map f) := begin intros i, rw [mem_degrees, multiset.mem_map], rintro ⟨d, hd, hi⟩, obtain ⟨x, rfl, hx⟩ := coeff_rename_ne_zero _ _ _ hd, simp only [map_domain, finsupp.mem_support_iff] at hi, rw [sum_apply, finsupp.sum] at hi, contrapose! hi, rw [finset.sum_eq_zero], intros j hj, simp only [exists_prop, mem_degrees] at hi, specialize hi j ⟨x, hx, hj⟩, rw [single_apply, if_neg hi], end lemma degrees_map_of_injective [comm_semiring S] (p : mv_polynomial σ R) {f : R →+* S} (hf : injective f) : (map f p).degrees = p.degrees := by simp only [degrees, mv_polynomial.support_map_of_injective _ hf] end degrees section vars /-! ### `vars` -/ /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars (p : mv_polynomial σ R) : finset σ := p.degrees.to_finset @[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_zero, multiset.to_finset_zero] @[simp] lemma vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support := by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset] @[simp] lemma vars_C : (C r : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_C, multiset.to_finset_zero] @[simp] lemma vars_X [nontrivial R] : (X n : mv_polynomial σ R).vars = {n} := by rw [X, vars_monomial (@one_ne_zero R _ _), finsupp.support_single_ne_zero (one_ne_zero : 1 ≠ 0)] lemma mem_vars (i : σ) : i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support := by simp only [vars, multiset.mem_to_finset, mem_degrees, mem_support_iff, exists_prop] lemma mem_support_not_mem_vars_zero {f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) : x v = 0 := begin rw [vars, multiset.mem_to_finset] at h, rw ← finsupp.not_mem_support_iff, contrapose! h, unfold degrees, rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H), rw finset.sup_insert, simp only [multiset.mem_union, multiset.sup_eq_union], left, rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h, end lemma vars_add_subset (p q : mv_polynomial σ R) : (p + q).vars ⊆ p.vars ∪ q.vars := begin intros x hx, simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢, simpa using multiset.mem_of_le (degrees_add _ _) hx, end lemma vars_add_of_disjoint (h : disjoint p.vars q.vars) : (p + q).vars = p.vars ∪ q.vars := begin apply finset.subset.antisymm (vars_add_subset p q), intros x hx, simp only [vars, multiset.disjoint_to_finset] at h hx ⊢, rw [degrees_add_of_disjoint h, multiset.to_finset_union], exact hx end section mul lemma vars_mul (φ ψ : mv_polynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars := begin intro i, simp only [mem_vars, finset.mem_union], rintro ⟨d, hd, hi⟩, rw [mem_support_iff, coeff_mul] at hd, contrapose! hd, cases hd, rw finset.sum_eq_zero, rintro ⟨d₁, d₂⟩ H, rw finsupp.mem_antidiagonal_support at H, subst H, obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support, { simpa only [finset.mem_union] using finsupp.support_add hi, }, { suffices : coeff d₁ φ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, { suffices : coeff d₂ ψ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, end @[simp] lemma vars_one : (1 : mv_polynomial σ R).vars = ∅ := vars_C lemma vars_pow (φ : mv_polynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars := begin induction n with n ih, { simp }, { rw pow_succ, apply finset.subset.trans (vars_mul _ _), exact finset.union_subset (finset.subset.refl _) ih } end /-- The variables of the product of a family of polynomials are a subset of the union of the sets of variables of each polynomial. -/ lemma vars_prod {ι : Type*} {s : finset ι} (f : ι → mv_polynomial σ R) : (∏ i in s, f i).vars ⊆ s.bUnion (λ i, (f i).vars) := begin apply s.induction_on, { simp }, { intros a s hs hsub, simp only [hs, finset.bUnion_insert, finset.prod_insert, not_false_iff], apply finset.subset.trans (vars_mul _ _), exact finset.union_subset_union (finset.subset.refl _) hsub } end section integral_domain variables {A : Type*} [integral_domain A] lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars := begin ext1 i, simp only [mem_vars, exists_prop, mem_support_iff], apply exists_congr, intro d, apply and_congr _ iff.rfl, rw [coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and], end end integral_domain end mul section sum variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ R) lemma vars_sum_subset : (∑ i in t, φ i).vars ⊆ finset.bUnion t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has], refine finset.subset.trans (vars_add_subset _ _) (finset.union_subset_union (finset.subset.refl _) _), assumption } end lemma vars_sum_of_disjoint (h : pairwise $ disjoint on (λ i, (φ i).vars)) : (∑ i in t, φ i).vars = finset.bUnion t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has, vars_add_of_disjoint, hsum], unfold pairwise on_fun at h, rw hsum, simp only [finset.disjoint_iff_ne] at h ⊢, intros v hv v2 hv2, rw finset.mem_bUnion at hv2, rcases hv2 with ⟨i, his, hi⟩, refine h a i _ _ hv _ hi, rintro rfl, contradiction } end end sum section map variables [comm_semiring S] (f : R →+* S) variable (p) lemma vars_map : (map f p).vars ⊆ p.vars := by simp [vars, degrees_map] variable {f} lemma vars_map_of_injective (hf : injective f) : (map f p).vars = p.vars := by simp [vars, degrees_map_of_injective _ hf] lemma vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) : (monomial (finsupp.single i e) r).vars = {i} := by rw [vars_monomial hr, finsupp.support_single_ne_zero he] lemma vars_eq_support_bUnion_support : p.vars = p.support.bUnion finsupp.support := by { ext i, rw [mem_vars, finset.mem_bUnion] } end map end vars section degree_of /-! ### `degree_of` -/ /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of (n : σ) (p : mv_polynomial σ R) : ℕ := p.degrees.count n end degree_of section total_degree /-! ### `total_degree` -/ /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree (p : mv_polynomial σ R) : ℕ := p.support.sup (λs, s.sum $ λn e, e) lemma total_degree_eq (p : mv_polynomial σ R) : p.total_degree = p.support.sup (λm, m.to_multiset.card) := begin rw [total_degree], congr, funext m, exact (finsupp.card_to_multiset _).symm end lemma total_degree_le_degrees_card (p : mv_polynomial σ R) : p.total_degree ≤ p.degrees.card := begin rw [total_degree_eq], exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs) end @[simp] lemma total_degree_C (a : R) : (C a : mv_polynomial σ R).total_degree = 0 := nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn, have _ := finsupp.support_single_subset hn, begin rw [finset.mem_singleton] at this, subst this, exact le_refl _ end @[simp] lemma total_degree_zero : (0 : mv_polynomial σ R).total_degree = 0 := by rw [← C_0]; exact total_degree_C (0 : R) @[simp] lemma total_degree_one : (1 : mv_polynomial σ R).total_degree = 0 := total_degree_C (1 : R) @[simp] lemma total_degree_X {R} [comm_semiring R] [nontrivial R] (s : σ) : (X s : mv_polynomial σ R).total_degree = 1 := begin rw [total_degree, support_X], simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq], end lemma total_degree_add (a b : mv_polynomial σ R) : (a + b).total_degree ≤ max a.total_degree b.total_degree := finset.sup_le $ assume n hn, have _ := finsupp.support_add hn, begin rw finset.mem_union at this, cases this, { exact le_max_left_of_le (finset.le_sup this) }, { exact le_max_right_of_le (finset.le_sup this) } end lemma total_degree_mul (a b : mv_polynomial σ R) : (a * b).total_degree ≤ a.total_degree + b.total_degree := finset.sup_le $ assume n hn, have _ := add_monoid_algebra.support_mul a b hn, begin simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.sum_add_index], { exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) }, { assume a, refl }, { assume a b₁ b₂, refl } end lemma total_degree_pow (a : mv_polynomial σ R) (n : ℕ) : (a ^ n).total_degree ≤ n * a.total_degree := begin induction n with n ih, { simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] }, rw pow_succ, calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _ ... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _ ... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm] end lemma total_degree_list_prod : ∀(s : list (mv_polynomial σ R)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum | [] := by rw [@list.prod_nil (mv_polynomial σ R) _, total_degree_one]; refl | (p :: ps) := begin rw [@list.prod_cons (mv_polynomial σ R) _, list.map, list.sum_cons], exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _) end lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ R)) : s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum := begin refine quotient.induction_on s (assume l, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum], exact total_degree_list_prod l end lemma total_degree_finset_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree := begin refine le_trans (total_degree_multiset_prod _) _, rw [multiset.map_map], refl end lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ R) (n : ℕ) (h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) : ∃ i, d i < n := begin contrapose! h, calc n * fintype.card σ = ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ] ... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s) ... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl } ... ≤ f.total_degree : finset.le_sup hd, end lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ R} {d : σ →₀ ℕ} (h : f.total_degree < ∑ i in d.support, d i) : coeff d f = 0 := begin classical, rw [total_degree, finset.sup_lt_iff] at h, { specialize h d, rw mem_support_iff at h, refine not_not.mp (mt h _), exact lt_irrefl _, }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma total_degree_rename_le (f : σ → τ) (p : mv_polynomial σ R) : (rename f p).total_degree ≤ p.total_degree := finset.sup_le $ assume b, begin assume h, rw rename_eq at h, have h' := finsupp.map_domain_support h, rw finset.mem_image at h', rcases h' with ⟨s, hs, rfl⟩, rw finsupp.sum_map_domain_index, exact le_trans (le_refl _) (finset.le_sup hs), exact assume _, rfl, exact assume _ _ _, rfl end end total_degree section eval_vars /-! ### `vars` and `eval` -/ variables [comm_semiring S] lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S) {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : eval₂_hom f g p = f (constant_coeff p) := begin conv_lhs { rw p.as_sum }, simp only [ring_hom.map_sum, eval₂_hom_monomial], by_cases h0 : constant_coeff p = 0, work_on_goal 0 { rw [h0, f.map_zero, finset.sum_eq_zero], intros d hd }, work_on_goal 1 { rw [finset.sum_eq_single (0 : σ →₀ ℕ)], { rw [finsupp.prod_zero_index, mul_one], refl }, intros d hd hd0, }, repeat { obtain ⟨i, hi⟩ : d.support.nonempty, { rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0, rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty], rintro rfl, contradiction }, rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)], rw [mem_vars], exact ⟨d, hd, hi⟩ }, { rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0, intro, contradiction } end lemma aeval_eq_constant_coeff_of_vars [algebra R S] {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : aeval g p = algebra_map _ _ (constant_coeff p) := eval₂_hom_eq_constant_coeff_of_vars _ hp lemma eval₂_hom_congr' {f₁ f₂ : R →+* S} {g₁ g₂ : σ → S} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → (∀ i, i ∈ p₁.vars → i ∈ p₂.vars → g₁ i = g₂ i) → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := begin rintro rfl h rfl, rename [p₁ p, f₁ f], rw p.as_sum, simp only [ring_hom.map_sum, eval₂_hom_monomial], apply finset.sum_congr rfl, intros d hd, congr' 1, simp only [finsupp.prod], apply finset.prod_congr rfl, intros i hi, have : i ∈ p.vars, { rw mem_vars, exact ⟨d, hd, hi⟩ }, rw h i this this, end lemma vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : (bind₁ f φ).vars ⊆ φ.vars.bUnion (λ i, (f i).vars) := begin calc (bind₁ f φ).vars = (φ.support.sum (λ (x : σ →₀ ℕ), (bind₁ f) (monomial x (coeff x φ)))).vars : by { rw [← alg_hom.map_sum, ← φ.as_sum], } ... ≤ φ.support.bUnion (λ (i : σ →₀ ℕ), ((bind₁ f) (monomial i (coeff i φ))).vars) : vars_sum_subset _ _ ... = φ.support.bUnion (λ (d : σ →₀ ℕ), (C (coeff d φ) * ∏ i in d.support, f i ^ d i).vars) : by simp only [bind₁_monomial] ... ≤ φ.support.bUnion (λ (d : σ →₀ ℕ), d.support.bUnion (λ i, (f i).vars)) : _ -- proof below ... ≤ φ.vars.bUnion (λ (i : σ), (f i).vars) : _, -- proof below { apply finset.bUnion_mono, intros d hd, calc (C (coeff d φ) * ∏ (i : σ) in d.support, f i ^ d i).vars ≤ (C (coeff d φ)).vars ∪ (∏ (i : σ) in d.support, f i ^ d i).vars : vars_mul _ _ ... ≤ (∏ (i : σ) in d.support, f i ^ d i).vars : by simp only [finset.empty_union, vars_C, finset.le_iff_subset, finset.subset.refl] ... ≤ d.support.bUnion (λ (i : σ), (f i ^ d i).vars) : vars_prod _ ... ≤ d.support.bUnion (λ (i : σ), (f i).vars) : _, apply finset.bUnion_mono, intros i hi, apply vars_pow, }, { intro j, simp_rw finset.mem_bUnion, rintro ⟨d, hd, ⟨i, hi, hj⟩⟩, exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ } end lemma mem_vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (bind₁ f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ j ∈ (f i).vars := by simpa only [exists_prop, finset.mem_bUnion, mem_support_iff, ne.def] using vars_bind₁ f φ h lemma vars_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).vars ⊆ (φ.vars.image f) := begin intros i hi, simp only [vars, exists_prop, multiset.mem_to_finset, finset.mem_image] at hi ⊢, simpa only [multiset.mem_map] using degrees_rename _ _ hi end lemma mem_vars_rename (f : σ → τ) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (rename f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ f i = j := by simpa only [exists_prop, finset.mem_image] using vars_rename f φ h end eval_vars end comm_semiring end mv_polynomial
25395eee4c3523639c671d74298ac7fb8a055b2e
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/module/hom.lean
232b20064ec5193a00d7d913a87eb23b00947bee
[ "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,817
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.module.pi /-! # Bundled hom instances for module and multiplicative actions This file defines instances for module, mul_action and related structures on bundled `_hom` types. These are analogous to the instances in `algebra.module.pi`, but for bundled instead of unbundled functions. -/ variables {R S A B : Type*} namespace add_monoid_hom section variables [monoid R] [monoid S] [add_monoid A] [add_comm_monoid B] variables [distrib_mul_action R B] [distrib_mul_action S B] instance : distrib_mul_action R (A →+ B) := { smul := λ r f, { to_fun := r • f, map_zero' := by simp, map_add' := λ x y, by simp [smul_add] }, one_smul := λ f, by simp, mul_smul := λ r s f, by simp [mul_smul], smul_add := λ r f g, ext $ λ x, by simp [smul_add], smul_zero := λ r, ext $ λ x, by simp [smul_zero] } @[simp] lemma coe_smul (r : R) (f : A →+ B) : ⇑(r • f) = r • f := rfl lemma smul_apply (r : R) (f : A →+ B) (x : A) : (r • f) x = r • f x := rfl instance [smul_comm_class R S B] : smul_comm_class R S (A →+ B) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ instance [has_scalar R S] [is_scalar_tower R S B] : is_scalar_tower R S (A →+ B) := ⟨λ a b f, ext $ λ x, smul_assoc _ _ _⟩ instance [distrib_mul_action Rᵐᵒᵖ B] [is_central_scalar R B] : is_central_scalar R (A →+ B) := ⟨λ a b, ext $ λ x, op_smul_eq_smul _ _⟩ end instance [semiring R] [add_monoid A] [add_comm_monoid B] [module R B] : module R (A →+ B) := { add_smul := λ r s x, ext $ λ y, by simp [add_smul], zero_smul := λ x, ext $ λ y, by simp [zero_smul], ..add_monoid_hom.distrib_mul_action } end add_monoid_hom
b0e3ed4a9f658c1c7ca4df3301e73220c135c2ec
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/order/filter/partial.lean
5a6ddeaf661a983211c3201ddc630453e2461754
[ "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,452
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Extends `tendsto` to relations and partial functions. -/ import order.filter.basic import data.pfun universes u v w namespace filter variables {α : Type u} {β : Type v} {γ : Type w} /- Relations. -/ def rmap (r : rel α β) (f : filter α) : filter β := { sets := r.core ⁻¹' f.sets, univ_sets := by { simp [rel.core], apply univ_mem_sets }, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ rel.core_mono _ st, inter_sets := by { simp [set.preimage, rel.core_inter], exact λ s t, inter_mem_sets } } theorem rmap_sets (r : rel α β) (f : filter α) : (rmap r f).sets = r.core ⁻¹' f.sets := rfl @[simp] theorem mem_rmap (r : rel α β) (l : filter α) (s : set β) : s ∈ l.rmap r ↔ r.core s ∈ l := iff.rfl @[simp] theorem rmap_rmap (r : rel α β) (s : rel β γ) (l : filter α) : rmap s (rmap r l) = rmap (r.comp s) l := filter_eq $ by simp [rmap_sets, set.preimage, rel.core_comp] @[simp] lemma rmap_compose (r : rel α β) (s : rel β γ) : rmap s ∘ rmap r = rmap (r.comp s) := funext $ rmap_rmap _ _ def rtendsto (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁.rmap r ≤ l₂ theorem rtendsto_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ ∀ s ∈ l₂, r.core s ∈ l₁ := iff.rfl def rcomap (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.core s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (by rw rel.core_inter) (set.inter_subset_inter ha₂ hb₂)⟩ } theorem rcomap_sets (r : rel α β) (f : filter β) : (rcomap r f).sets = rel.image (λ s t, r.core s ⊆ t) f.sets := rfl @[simp] theorem rcomap_rcomap (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap r (rcomap s l) = rcomap (r.comp s) l := filter_eq $ begin ext t, simp [rcomap_sets, rel.image, rel.core_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.core_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.core s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap_compose (r : rel α β) (s : rel β γ) : rcomap r ∘ rcomap s = rcomap (r.comp s) := funext $ rcomap_rcomap _ _ theorem rtendsto_iff_le_comap (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ l₁ ≤ l₂.rcomap r := begin rw rtendsto_def, change (∀ (s : set β), s ∈ l₂.sets → rel.core r s ∈ l₁) ↔ l₁ ≤ rcomap r l₂, simp [filter.le_def, rcomap, rel.mem_image], split, intros h s t tl₂ h', { exact mem_sets_of_superset (h t tl₂) h' }, intros h t tl₂, apply h _ t tl₂ (set.subset.refl _), end -- Interestingly, there does not seem to be a way to express this relation using a forward map. -- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f` if -- and only if `s ∈ f'`. But the intersection of two sets satsifying the lhs may be empty. def rcomap' (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.preimage s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (@rel.preimage_inter _ _ r _ _) (set.inter_subset_inter ha₂ hb₂)⟩ } @[simp] lemma mem_rcomap' (r : rel α β) (l : filter β) (s : set α) : s ∈ l.rcomap' r ↔ ∃ t ∈ l, rel.preimage r t ⊆ s := iff.rfl theorem rcomap'_sets (r : rel α β) (f : filter β) : (rcomap' r f).sets = rel.image (λ s t, r.preimage s ⊆ t) f.sets := rfl @[simp] theorem rcomap'_rcomap' (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap' r (rcomap' s l) = rcomap' (r.comp s) l := filter_eq $ begin ext t, simp [rcomap'_sets, rel.image, rel.preimage_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.preimage_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.preimage s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap'_compose (r : rel α β) (s : rel β γ) : rcomap' r ∘ rcomap' s = rcomap' (r.comp s) := funext $ rcomap'_rcomap' _ _ def rtendsto' (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' r theorem rtendsto'_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto' r l₁ l₂ ↔ ∀ s ∈ l₂, r.preimage s ∈ l₁ := begin unfold rtendsto', unfold rcomap', simp [le_def, rel.mem_image], split, { intros h s hs, apply (h _ _ hs (set.subset.refl _)) }, intros h s t ht h', apply mem_sets_of_superset (h t ht) h' end theorem tendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto_def, rel.core, set.preimage] } theorem tendsto_iff_rtendsto' (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto'_def, rel.preimage_def, set.preimage] } /- Partial functions. -/ def pmap (f : α →. β) (l : filter α) : filter β := filter.rmap f.graph' l @[simp] lemma mem_pmap (f : α →. β) (l : filter α) (s : set β) : s ∈ l.pmap f ↔ f.core s ∈ l := iff.rfl def ptendsto (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁.pmap f ≤ l₂ theorem ptendsto_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f.core s ∈ l₁ := iff.rfl theorem ptendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α →. β) : ptendsto f l₁ l₂ ↔ rtendsto f.graph' l₁ l₂ := iff.rfl theorem pmap_res (l : filter α) (s : set α) (f : α → β) : pmap (pfun.res f s) l = map f (l ⊓ principal s) := filter_eq $ begin apply set.ext, intro t, simp [pfun.core_res], split, { intro h, constructor, split, { exact h }, constructor, split, { reflexivity }, simp [set.inter_distrib_right], apply set.inter_subset_left }, rintro ⟨t₁, h₁, t₂, h₂, h₃⟩, apply mem_sets_of_superset h₁, rw ← set.inter_subset, exact set.subset.trans (set.inter_subset_inter_right _ h₂) h₃ end theorem tendsto_iff_ptendsto (l₁ : filter α) (l₂ : filter β) (s : set α) (f : α → β) : tendsto f (l₁ ⊓ principal s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ := by simp only [tendsto, ptendsto, pmap_res] theorem tendsto_iff_ptendsto_univ (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ := by { rw ← tendsto_iff_ptendsto, simp [principal_univ] } def pcomap' (f : α →. β) (l : filter β) : filter α := filter.rcomap' f.graph' l def ptendsto' (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' f.graph' theorem ptendsto'_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto' f l₁ l₂ ↔ ∀ s ∈ l₂, f.preimage s ∈ l₁ := rtendsto'_def _ _ _ theorem ptendsto_of_ptendsto' {f : α →. β} {l₁ : filter α} {l₂ : filter β} : ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h s sl₂, exacts mem_sets_of_superset (h s sl₂) (pfun.preimage_subset_core _ _), end theorem ptendsto'_of_ptendsto {f : α →. β} {l₁ : filter α} {l₂ : filter β} (h : f.dom ∈ l₁) : ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h' s sl₂, rw pfun.preimage_eq, show pfun.core f s ∩ pfun.dom f ∈ l₁, exact inter_mem_sets (h' s sl₂) h end end filter
d055491186b3899628aac6d3d4a43c367c1e1d85
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/tests/lean/run/depElim1.lean
2ea72d833a029b1e23c932e90203167073eee4f5
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
13,827
lean
import Lean.Meta.Match open Lean open Lean.Meta open Lean.Meta.Match /- Infrastructure for testing -/ universes u v def check (x : Bool) : IO Unit := do unless x do 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.numParams + v.numFields then return some (v, fn, args) else return none | _ => return 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 => do if e.isAppOfArity `val 2 then return Pattern.val e.appArg! else if e.isAppOfArity `inaccessible 2 then return Pattern.inaccessible e.appArg! else if e.isFVar then return Pattern.var e.fvarId! else if e.isAppOfArity `As 3 && (e.getArg! 1).isFVar then let v := e.getArg! 1 let p := e.getArg! 2 let p ← mkPattern p return 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 let args := e.getAppArgs let type := args[0] let ps := args.extract 1 args.size let ps ← ps.toList.mapM mkPattern return Pattern.arrayLit type ps else match e.arrayLit? with | some (_, es) => let pats ← es.mapM mkPattern let type ← inferType e let type ← whnfD type let elemType := type.appArg! return Pattern.arrayLit elemType pats | none => let e ← whnfD e let r? ← constructorApp? e match r? with | none => throwError "unexpected pattern" | some (cval, fn, args) => let params := args.extract 0 cval.numParams let fields := args.extract cval.numParams args.size let pats ← fields.toList.mapM mkPattern return Pattern.ctor cval.name fn.constLevels! params.toList pats partial def decodePats : Expr → MetaM (List Pattern) | e => do match e.app2? `Pat with | some (_, pat) => let pat ← mkPattern pat; return [pat] | none => match e.prod? with | none => throwError "unexpected pattern" | some (pat, pats) => let pat ← decodePats pat let pats ← decodePats pats return 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 return { ref := Syntax.missing, fvarDecls := decls, patterns := pats } partial def decodeAltLHSs : Expr → MetaM (List AltLHS) | e => do match e.app2? `LHS with | some (_, lhs) => let lhs ← decodeAltLHS lhs; return [lhs] | none => match e.prod? with | none => throwError "unexpected LHS" | some (lhs, lhss) => let lhs ← decodeAltLHSs lhs let lhss ← decodeAltLHSs lhss return 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 mut s := {} for major in majors do let major ← instantiateMVars major let majorType ← inferType major let majorType ← instantiateMVars majorType s := collectLevelParams s major s := collectLevelParams s majorType return 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 := do if inProp then return mkSort levelZero else let v ← getUnusedLevelParam majors lhss return mkSort $ v def mkTester (elimName : Name) (majors : List Expr) (lhss : List AltLHS) (inProp : Bool := false) : MetaM MatcherResult := do generalizeTelescope majors.toArray fun majors => do let resultType := if inProp then mkConst `True /- some proposition -/ else mkConst `Nat let matchType ← mkForallFVars majors resultType Match.mkMatcher { matcherName := elimName, matchType, numDiscrs := 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] m!"majors: {majors.toArray}" let r ← mkTester elimName majors alts inProp r.addMatcher unless r.counterExamples.isEmpty do throwError m!"missing cases:\n{counterExamplesToMessageData r.counterExamples}" unless r.unusedAltIdxs.isEmpty do throwError (m!"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 ← tryCatch (do test ex numPats elimName inProp; pure true) (fun ex => pure false) if worked then 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])
7e07e6d7dcb94237a481ef65f390dadec3696552
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/quadratic_form/basic.lean
663a7df5eafb59fd082bfb51d764a393b4a8ed45
[ "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
38,136
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Kexing Ying, Eric Wieser -/ import algebra.invertible import linear_algebra.matrix.determinant import linear_algebra.matrix.bilinear_form import linear_algebra.matrix.symmetric /-! # Quadratic forms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines quadratic forms over a `R`-module `M`. A quadratic form on a ring `R` is a map `Q : M → R` such that: * `quadratic_form.map_smul`: `Q (a • x) = a * a * Q x` * `quadratic_form.polar_add_left`, `quadratic_form.polar_add_right`, `quadratic_form.polar_smul_left`, `quadratic_form.polar_smul_right`: the map `quadratic_form.polar Q := λ x y, Q (x + y) - Q x - Q y` is bilinear. This notion generalizes to semirings using the approach in [izhakian2016][] which requires that there be a (possibly non-unique) companion bilinear form `B` such that `∀ x y, Q (x + y) = Q x + Q y + B x y`. Over a ring, this `B` is precisely `quadratic_form.polar Q`. To build a `quadratic_form` from the `polar` axioms, use `quadratic_form.of_polar`. Quadratic forms come with a scalar multiplication, `(a • Q) x = Q (a • x) = a * a * Q x`, and composition with linear maps `f`, `Q.comp f x = Q (f x)`. ## Main definitions * `quadratic_form.of_polar`: a more familiar constructor that works on rings * `quadratic_form.associated`: associated bilinear form * `quadratic_form.pos_def`: positive definite quadratic forms * `quadratic_form.anisotropic`: anisotropic quadratic forms * `quadratic_form.discr`: discriminant of a quadratic form ## Main statements * `quadratic_form.associated_left_inverse`, * `quadratic_form.associated_right_inverse`: in a commutative ring where 2 has an inverse, there is a correspondence between quadratic forms and symmetric bilinear forms * `bilin_form.exists_orthogonal_basis`: There exists an orthogonal basis with respect to any nondegenerate, symmetric bilinear form `B`. ## Notation In this file, the variable `R` is used when a `ring` structure is sufficient and `R₁` is used when specifically a `comm_ring` is required. This allows us to keep `[module R M]` and `[module R₁ M]` assumptions in the variables without confusion between `*` from `ring` and `*` from `comm_ring`. The variable `S` is used when `R` itself has a `•` action. ## References * https://en.wikipedia.org/wiki/Quadratic_form * https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms ## Tags quadratic form, homogeneous polynomial, quadratic polynomial -/ universes u v w variables {S : Type*} variables {R R₁: Type*} {M : Type*} open_locale big_operators section polar variables [ring R] [comm_ring R₁] [add_comm_group M] namespace quadratic_form /-- Up to a factor 2, `Q.polar` is the associated bilinear form for a quadratic form `Q`. Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization -/ def polar (f : M → R) (x y : M) := f (x + y) - f x - f y lemma polar_add (f g : M → R) (x y : M) : polar (f + g) x y = polar f x y + polar g x y := by { simp only [polar, pi.add_apply], abel } lemma polar_neg (f : M → R) (x y : M) : polar (-f) x y = - polar f x y := by { simp only [polar, pi.neg_apply, sub_eq_add_neg, neg_add] } lemma polar_smul [monoid S] [distrib_mul_action S R] (f : M → R) (s : S) (x y : M) : polar (s • f) x y = s • polar f x y := by { simp only [polar, pi.smul_apply, smul_sub] } lemma polar_comm (f : M → R) (x y : M) : polar f x y = polar f y x := by rw [polar, polar, add_comm, sub_sub, sub_sub, add_comm (f x) (f y)] /-- Auxiliary lemma to express bilinearity of `quadratic_form.polar` without subtraction. -/ lemma polar_add_left_iff {f : M → R} {x x' y : M} : polar f (x + x') y = polar f x y + polar f x' y ↔ f (x + x' + y) + (f x + f x' + f y) = f (x + x') + f (x' + y) + f (y + x) := begin simp only [←add_assoc], simp only [polar, sub_eq_iff_eq_add, eq_sub_iff_add_eq, sub_add_eq_add_sub, add_sub], simp only [add_right_comm _ (f y) _, add_right_comm _ (f x') (f x)], rw [add_comm y x, add_right_comm _ _ (f (x + y)), add_comm _ (f (x + y)), add_right_comm (f (x + y)), add_left_inj], end lemma polar_comp {F : Type*} [ring S] [add_monoid_hom_class F R S] (f : M → R) (g : F) (x y : M) : polar (g ∘ f) x y = g (polar f x y) := by simp only [polar, pi.smul_apply, function.comp_apply, map_sub] end quadratic_form end polar /-- A quadratic form over a module. For a more familiar constructor when `R` is a ring, see `quadratic_form.of_polar`. -/ structure quadratic_form (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] := (to_fun : M → R) (to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x) (exists_companion' : ∃ B : bilin_form R M, ∀ x y, to_fun (x + y) = to_fun x + to_fun y + B x y) namespace quadratic_form section fun_like variables [semiring R] [add_comm_monoid M] [module R M] variables {Q Q' : quadratic_form R M} instance fun_like : fun_like (quadratic_form R M) M (λ _, R) := { coe := to_fun, coe_injective' := λ x y h, by cases x; cases y; congr' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (quadratic_form R M) (λ _, M → R) := ⟨to_fun⟩ variables (Q) /-- The `simp` normal form for a quadratic form is `coe_fn`, not `to_fun`. -/ @[simp] lemma to_fun_eq_coe : Q.to_fun = ⇑Q := rfl -- this must come after the coe_to_fun definition initialize_simps_projections quadratic_form (to_fun → apply) variables {Q} @[ext] lemma ext (H : ∀ (x : M), Q x = Q' x) : Q = Q' := fun_like.ext _ _ H lemma congr_fun (h : Q = Q') (x : M) : Q x = Q' x := fun_like.congr_fun h _ lemma ext_iff : Q = Q' ↔ (∀ x, Q x = Q' x) := fun_like.ext_iff /-- Copy of a `quadratic_form` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (Q : quadratic_form R M) (Q' : M → R) (h : Q' = ⇑Q) : quadratic_form R M := { to_fun := Q', to_fun_smul := h.symm ▸ Q.to_fun_smul, exists_companion' := h.symm ▸ Q.exists_companion' } @[simp] lemma coe_copy (Q : quadratic_form R M) (Q' : M → R) (h : Q' = ⇑Q) : ⇑(Q.copy Q' h) = Q' := rfl lemma copy_eq (Q : quadratic_form R M) (Q' : M → R) (h : Q' = ⇑Q) : Q.copy Q' h = Q := fun_like.ext' h end fun_like section semiring variables [semiring R] [add_comm_monoid M] [module R M] variables (Q : quadratic_form R M) lemma map_smul (a : R) (x : M) : Q (a • x) = a * a * Q x := Q.to_fun_smul a x lemma exists_companion : ∃ B : bilin_form R M, ∀ x y, Q (x + y) = Q x + Q y + B x y := Q.exists_companion' lemma map_add_add_add_map (x y z : M) : Q (x + y + z) + (Q x + Q y + Q z) = Q (x + y) + Q (y + z) + Q (z + x) := begin obtain ⟨B, h⟩ := Q.exists_companion, rw [add_comm z x], simp [h], abel, end lemma map_add_self (x : M) : Q (x + x) = 4 * Q x := by { rw [←one_smul R x, ←add_smul, map_smul], norm_num } @[simp] lemma map_zero : Q 0 = 0 := by rw [←@zero_smul R _ _ _ _ (0 : M), map_smul, zero_mul, zero_mul] instance zero_hom_class : zero_hom_class (quadratic_form R M) M R := { map_zero := map_zero, ..quadratic_form.fun_like } lemma map_smul_of_tower [comm_semiring S] [algebra S R] [module S M] [is_scalar_tower S R M] (a : S) (x : M) : Q (a • x) = (a * a) • Q x := by rw [←is_scalar_tower.algebra_map_smul R a x, map_smul, ←ring_hom.map_mul, algebra.smul_def] end semiring section ring variables [ring R] [comm_ring R₁] [add_comm_group M] variables [module R M] (Q : quadratic_form R M) @[simp] lemma map_neg (x : M) : Q (-x) = Q x := by rw [←@neg_one_smul R _ _ _ _ x, map_smul, neg_one_mul, neg_neg, one_mul] lemma map_sub (x y : M) : Q (x - y) = Q (y - x) := by rw [←neg_sub, map_neg] @[simp] lemma polar_zero_left (y : M) : polar Q 0 y = 0 := by simp only [polar, zero_add, quadratic_form.map_zero, sub_zero, sub_self] @[simp] lemma polar_add_left (x x' y : M) : polar Q (x + x') y = polar Q x y + polar Q x' y := polar_add_left_iff.mpr $ Q.map_add_add_add_map x x' y @[simp] lemma polar_smul_left (a : R) (x y : M) : polar Q (a • x) y = a * polar Q x y := begin obtain ⟨B, h⟩ := Q.exists_companion, simp_rw [polar, h, Q.map_smul, bilin_form.smul_left, sub_sub, add_sub_cancel'], end @[simp] lemma polar_neg_left (x y : M) : polar Q (-x) y = -polar Q x y := by rw [←neg_one_smul R x, polar_smul_left, neg_one_mul] @[simp] lemma polar_sub_left (x x' y : M) : polar Q (x - x') y = polar Q x y - polar Q x' y := by rw [sub_eq_add_neg, sub_eq_add_neg, polar_add_left, polar_neg_left] @[simp] lemma polar_zero_right (y : M) : polar Q y 0 = 0 := by simp only [add_zero, polar, quadratic_form.map_zero, sub_self] @[simp] lemma polar_add_right (x y y' : M) : polar Q x (y + y') = polar Q x y + polar Q x y' := by rw [polar_comm Q x, polar_comm Q x, polar_comm Q x, polar_add_left] @[simp] lemma polar_smul_right (a : R) (x y : M) : polar Q x (a • y) = a * polar Q x y := by rw [polar_comm Q x, polar_comm Q x, polar_smul_left] @[simp] lemma polar_neg_right (x y : M) : polar Q x (-y) = -polar Q x y := by rw [←neg_one_smul R y, polar_smul_right, neg_one_mul] @[simp] lemma polar_sub_right (x y y' : M) : polar Q x (y - y') = polar Q x y - polar Q x y' := by rw [sub_eq_add_neg, sub_eq_add_neg, polar_add_right, polar_neg_right] @[simp] lemma polar_self (x : M) : polar Q x x = 2 * Q x := begin rw [polar, map_add_self, sub_sub, sub_eq_iff_eq_add, ←two_mul, ←two_mul, ←mul_assoc], norm_num end /-- `quadratic_form.polar` as a bilinear form -/ @[simps] def polar_bilin : bilin_form R M := { bilin := polar Q, bilin_add_left := polar_add_left Q, bilin_smul_left := polar_smul_left Q, bilin_add_right := λ x y z, by simp_rw [polar_comm _ x, polar_add_left Q], bilin_smul_right := λ r x y, by simp_rw [polar_comm _ x, polar_smul_left Q] } variables [comm_semiring S] [algebra S R] [module S M] [is_scalar_tower S R M] @[simp] lemma polar_smul_left_of_tower (a : S) (x y : M) : polar Q (a • x) y = a • polar Q x y := by rw [←is_scalar_tower.algebra_map_smul R a x, polar_smul_left, algebra.smul_def] @[simp] lemma polar_smul_right_of_tower (a : S) (x y : M) : polar Q x (a • y) = a • polar Q x y := by rw [←is_scalar_tower.algebra_map_smul R a y, polar_smul_right, algebra.smul_def] /-- An alternative constructor to `quadratic_form.mk`, for rings where `polar` can be used. -/ @[simps] def of_polar (to_fun : M → R) (to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x) (polar_add_left : ∀ (x x' y : M), polar to_fun (x + x') y = polar to_fun x y + polar to_fun x' y) (polar_smul_left : ∀ (a : R) (x y : M), polar to_fun (a • x) y = a • polar to_fun x y) : quadratic_form R M := { to_fun := to_fun, to_fun_smul := to_fun_smul, exists_companion' := ⟨ { bilin := polar to_fun, bilin_add_left := polar_add_left, bilin_smul_left := polar_smul_left, bilin_add_right := λ x y z, by simp_rw [polar_comm _ x, polar_add_left], bilin_smul_right := λ r x y, by simp_rw [polar_comm _ x, polar_smul_left, smul_eq_mul] }, λ x y, by rw [bilin_form.coe_fn_mk, polar, sub_sub, add_sub_cancel'_right]⟩ } /-- In a ring the companion bilinear form is unique and equal to `quadratic_form.polar`. -/ lemma some_exists_companion : Q.exists_companion.some = polar_bilin Q := bilin_form.ext $ λ x y, by rw [polar_bilin_apply, polar, Q.exists_companion.some_spec, sub_sub, add_sub_cancel'] end ring section semiring_operators variables [semiring R] [add_comm_monoid M] [module R M] section has_smul variables [monoid S] [distrib_mul_action S R] [smul_comm_class S R R] /-- `quadratic_form R M` inherits the scalar action from any algebra over `R`. When `R` is commutative, this provides an `R`-action via `algebra.id`. -/ instance : has_smul S (quadratic_form R M) := ⟨ λ a Q, { to_fun := a • Q, to_fun_smul := λ b x, by rw [pi.smul_apply, map_smul, pi.smul_apply, mul_smul_comm], exists_companion' := let ⟨B, h⟩ := Q.exists_companion in ⟨a • B, by simp [h]⟩ } ⟩ @[simp] lemma coe_fn_smul (a : S) (Q : quadratic_form R M) : ⇑(a • Q) = a • Q := rfl @[simp] lemma smul_apply (a : S) (Q : quadratic_form R M) (x : M) : (a • Q) x = a • Q x := rfl end has_smul instance : has_zero (quadratic_form R M) := ⟨ { to_fun := λ x, 0, to_fun_smul := λ a x, by simp only [mul_zero], exists_companion' := ⟨0, λ x y, by simp only [add_zero, bilin_form.zero_apply]⟩ } ⟩ @[simp] lemma coe_fn_zero : ⇑(0 : quadratic_form R M) = 0 := rfl @[simp] lemma zero_apply (x : M) : (0 : quadratic_form R M) x = 0 := rfl instance : inhabited (quadratic_form R M) := ⟨0⟩ instance : has_add (quadratic_form R M) := ⟨ λ Q Q', { to_fun := Q + Q', to_fun_smul := λ a x, by simp only [pi.add_apply, map_smul, mul_add], exists_companion' := let ⟨B, h⟩ := Q.exists_companion, ⟨B', h'⟩ := Q'.exists_companion in ⟨B + B', λ x y, by simp_rw [pi.add_apply, h, h', bilin_form.add_apply, add_add_add_comm] ⟩ } ⟩ @[simp] lemma coe_fn_add (Q Q' : quadratic_form R M) : ⇑(Q + Q') = Q + Q' := rfl @[simp] lemma add_apply (Q Q' : quadratic_form R M) (x : M) : (Q + Q') x = Q x + Q' x := rfl instance : add_comm_monoid (quadratic_form R M) := fun_like.coe_injective.add_comm_monoid _ coe_fn_zero coe_fn_add (λ _ _, coe_fn_smul _ _) /-- `@coe_fn (quadratic_form R M)` as an `add_monoid_hom`. This API mirrors `add_monoid_hom.coe_fn`. -/ @[simps apply] def coe_fn_add_monoid_hom : quadratic_form R M →+ (M → R) := { to_fun := coe_fn, map_zero' := coe_fn_zero, map_add' := coe_fn_add } /-- Evaluation on a particular element of the module `M` is an additive map over quadratic forms. -/ @[simps apply] def eval_add_monoid_hom (m : M) : quadratic_form R M →+ R := (pi.eval_add_monoid_hom _ m).comp coe_fn_add_monoid_hom section sum @[simp] lemma coe_fn_sum {ι : Type*} (Q : ι → quadratic_form R M) (s : finset ι) : ⇑(∑ i in s, Q i) = ∑ i in s, Q i := (coe_fn_add_monoid_hom : _ →+ (M → R)).map_sum Q s @[simp] lemma sum_apply {ι : Type*} (Q : ι → quadratic_form R M) (s : finset ι) (x : M) : (∑ i in s, Q i) x = ∑ i in s, Q i x := (eval_add_monoid_hom x : _ →+ R).map_sum Q s end sum instance [monoid S] [distrib_mul_action S R] [smul_comm_class S R R] : distrib_mul_action S (quadratic_form R M) := { mul_smul := λ a b Q, ext (λ x, by simp only [smul_apply, mul_smul]), one_smul := λ Q, ext (λ x, by simp only [quadratic_form.smul_apply, one_smul]), smul_add := λ a Q Q', by { ext, simp only [add_apply, smul_apply, smul_add] }, smul_zero := λ a, by { ext, simp only [zero_apply, smul_apply, smul_zero] }, } instance [semiring S] [module S R] [smul_comm_class S R R] : module S (quadratic_form R M) := { zero_smul := λ Q, by { ext, simp only [zero_apply, smul_apply, zero_smul] }, add_smul := λ a b Q, by { ext, simp only [add_apply, smul_apply, add_smul] } } end semiring_operators section ring_operators variables [ring R] [add_comm_group M] [module R M] instance : has_neg (quadratic_form R M) := ⟨ λ Q, { to_fun := -Q, to_fun_smul := λ a x, by simp only [pi.neg_apply, map_smul, mul_neg], exists_companion' := let ⟨B, h⟩ := Q.exists_companion in ⟨-B, λ x y, by simp_rw [pi.neg_apply, h, bilin_form.neg_apply, neg_add] ⟩ } ⟩ @[simp] lemma coe_fn_neg (Q : quadratic_form R M) : ⇑(-Q) = -Q := rfl @[simp] lemma neg_apply (Q : quadratic_form R M) (x : M) : (-Q) x = -Q x := rfl instance : has_sub (quadratic_form R M) := ⟨ λ Q Q', (Q + -Q').copy (Q - Q') (sub_eq_add_neg _ _) ⟩ @[simp] lemma coe_fn_sub (Q Q' : quadratic_form R M) : ⇑(Q - Q') = Q - Q' := rfl @[simp] lemma sub_apply (Q Q' : quadratic_form R M) (x : M) : (Q - Q') x = Q x - Q' x := rfl instance : add_comm_group (quadratic_form R M) := fun_like.coe_injective.add_comm_group _ coe_fn_zero coe_fn_add coe_fn_neg coe_fn_sub (λ _ _, coe_fn_smul _ _) (λ _ _, coe_fn_smul _ _) end ring_operators section comp variables [semiring R] [add_comm_monoid M] [module R M] variables {N : Type v} [add_comm_monoid N] [module R N] /-- Compose the quadratic form with a linear function. -/ def comp (Q : quadratic_form R N) (f : M →ₗ[R] N) : quadratic_form R M := { to_fun := λ x, Q (f x), to_fun_smul := λ a x, by simp only [map_smul, f.map_smul], exists_companion' := let ⟨B, h⟩ := Q.exists_companion in ⟨B.comp f f, λ x y, by simp_rw [f.map_add, h, bilin_form.comp_apply]⟩ } @[simp] lemma comp_apply (Q : quadratic_form R N) (f : M →ₗ[R] N) (x : M) : (Q.comp f) x = Q (f x) := rfl /-- Compose a quadratic form with a linear function on the left. -/ @[simps {simp_rhs := tt}] def _root_.linear_map.comp_quadratic_form {S : Type*} [comm_semiring S] [algebra S R] [module S M] [is_scalar_tower S R M] (f : R →ₗ[S] S) (Q : quadratic_form R M) : quadratic_form S M := { to_fun := λ x, f (Q x), to_fun_smul := λ b x, by rw [Q.map_smul_of_tower b x, f.map_smul, smul_eq_mul], exists_companion' := let ⟨B, h⟩ := Q.exists_companion in ⟨f.comp_bilin_form B, λ x y, by simp_rw [h, f.map_add, linear_map.comp_bilin_form_apply]⟩ } end comp section comm_ring variables [comm_semiring R] [add_comm_monoid M] [module R M] /-- The product of linear forms is a quadratic form. -/ def lin_mul_lin (f g : M →ₗ[R] R) : quadratic_form R M := { to_fun := f * g, to_fun_smul := λ a x, by { simp only [smul_eq_mul, ring_hom.id_apply, pi.mul_apply, linear_map.map_smulₛₗ], ring }, exists_companion' := ⟨ bilin_form.lin_mul_lin f g + bilin_form.lin_mul_lin g f, λ x y, by { simp, ring }⟩ } @[simp] lemma lin_mul_lin_apply (f g : M →ₗ[R] R) (x) : lin_mul_lin f g x = f x * g x := rfl @[simp] lemma add_lin_mul_lin (f g h : M →ₗ[R] R) : lin_mul_lin (f + g) h = lin_mul_lin f h + lin_mul_lin g h := ext (λ x, add_mul _ _ _) @[simp] lemma lin_mul_lin_add (f g h : M →ₗ[R] R) : lin_mul_lin f (g + h) = lin_mul_lin f g + lin_mul_lin f h := ext (λ x, mul_add _ _ _) variables {N : Type v} [add_comm_monoid N] [module R N] @[simp] lemma lin_mul_lin_comp (f g : M →ₗ[R] R) (h : N →ₗ[R] M) : (lin_mul_lin f g).comp h = lin_mul_lin (f.comp h) (g.comp h) := rfl variables {n : Type*} /-- `sq` is the quadratic form mapping the vector `x : R₁` to `x * x` -/ @[simps] def sq : quadratic_form R R := lin_mul_lin linear_map.id linear_map.id /-- `proj i j` is the quadratic form mapping the vector `x : n → R₁` to `x i * x j` -/ def proj (i j : n) : quadratic_form R (n → R) := lin_mul_lin (@linear_map.proj _ _ _ (λ _, R) _ _ i) (@linear_map.proj _ _ _ (λ _, R) _ _ j) @[simp] lemma proj_apply (i j : n) (x : n → R) : proj i j x = x i * x j := rfl end comm_ring end quadratic_form /-! ### Associated bilinear forms Over a commutative ring with an inverse of 2, the theory of quadratic forms is basically identical to that of symmetric bilinear forms. The map from quadratic forms to bilinear forms giving this identification is called the `associated` quadratic form. -/ namespace bilin_form open quadratic_form section semiring variables [semiring R] [add_comm_monoid M] [module R M] variables {B : bilin_form R M} /-- A bilinear form gives a quadratic form by applying the argument twice. -/ def to_quadratic_form (B : bilin_form R M) : quadratic_form R M := { to_fun := λ x, B x x, to_fun_smul := λ a x, by simp only [mul_assoc, smul_right, smul_left], exists_companion' := ⟨B + bilin_form.flip_hom ℕ B, λ x y, by { simp [add_add_add_comm, add_comm] }⟩ } @[simp] lemma to_quadratic_form_apply (B : bilin_form R M) (x : M) : B.to_quadratic_form x = B x x := rfl section variables (R M) @[simp] lemma to_quadratic_form_zero : (0 : bilin_form R M).to_quadratic_form = 0 := rfl end @[simp] lemma to_quadratic_form_add (B₁ B₂ : bilin_form R M) : (B₁ + B₂).to_quadratic_form = B₁.to_quadratic_form + B₂.to_quadratic_form := rfl @[simp] lemma to_quadratic_form_smul [monoid S] [distrib_mul_action S R] [smul_comm_class S R R] (a : S) (B : bilin_form R M) : (a • B).to_quadratic_form = a • B.to_quadratic_form := rfl section variables (R M) /-- `bilin_form.to_quadratic_form` as an additive homomorphism -/ @[simps] def to_quadratic_form_add_monoid_hom : bilin_form R M →+ quadratic_form R M := { to_fun := to_quadratic_form, map_zero' := to_quadratic_form_zero _ _, map_add' := to_quadratic_form_add } end @[simp] lemma to_quadratic_form_list_sum (B : list (bilin_form R M)) : B.sum.to_quadratic_form = (B.map to_quadratic_form).sum := map_list_sum (to_quadratic_form_add_monoid_hom R M) B @[simp] lemma to_quadratic_form_multiset_sum (B : multiset (bilin_form R M)) : B.sum.to_quadratic_form = (B.map to_quadratic_form).sum := map_multiset_sum (to_quadratic_form_add_monoid_hom R M) B @[simp] lemma to_quadratic_form_sum {ι : Type*} (s : finset ι) (B : ι → bilin_form R M) : (∑ i in s, B i).to_quadratic_form = ∑ i in s, (B i).to_quadratic_form := map_sum (to_quadratic_form_add_monoid_hom R M) B s @[simp] lemma to_quadratic_form_eq_zero {B : bilin_form R M} : B.to_quadratic_form = 0 ↔ B.is_alt := quadratic_form.ext_iff end semiring section ring variables [ring R] [add_comm_group M] [module R M] variables {B : bilin_form R M} lemma polar_to_quadratic_form (x y : M) : polar (λ x, B x x) x y = B x y + B y x := by { simp only [add_assoc, add_sub_cancel', add_right, polar, add_left_inj, add_neg_cancel_left, add_left, sub_eq_add_neg _ (B y y), add_comm (B y x) _] } @[simp] lemma to_quadratic_form_neg (B : bilin_form R M) : (-B).to_quadratic_form = -B.to_quadratic_form := rfl @[simp] lemma to_quadratic_form_sub (B₁ B₂ : bilin_form R M) : (B₁ - B₂).to_quadratic_form = B₁.to_quadratic_form - B₂.to_quadratic_form := rfl end ring end bilin_form namespace quadratic_form open bilin_form section associated_hom variables [ring R] [comm_ring R₁] [add_comm_group M] [module R M] [module R₁ M] variables (S) [comm_semiring S] [algebra S R] variables [invertible (2 : R)] {B₁ : bilin_form R M} /-- `associated_hom` is the map that sends a quadratic form on a module `M` over `R` to its associated symmetric bilinear form. As provided here, this has the structure of an `S`-linear map where `S` is a commutative subring of `R`. Over a commutative ring, use `associated`, which gives an `R`-linear map. Over a general ring with no nontrivial distinguished commutative subring, use `associated'`, which gives an additive homomorphism (or more precisely a `ℤ`-linear map.) -/ def associated_hom : quadratic_form R M →ₗ[S] bilin_form R M := { to_fun := λ Q, ((•) : submonoid.center R → bilin_form R M → bilin_form R M) (⟨⅟2, λ x, (commute.one_right x).bit0_right.inv_of_right⟩) Q.polar_bilin, map_add' := λ Q Q', by { ext, simp only [bilin_form.add_apply, bilin_form.smul_apply, coe_fn_mk, polar_bilin_apply, polar_add, coe_fn_add, smul_add] }, map_smul' := λ s Q, by { ext, simp only [ring_hom.id_apply, polar_smul, smul_comm s, polar_bilin_apply, coe_fn_mk, coe_fn_smul, bilin_form.smul_apply] } } variables (Q : quadratic_form R M) (S) @[simp] lemma associated_apply (x y : M) : associated_hom S Q x y = ⅟2 * (Q (x + y) - Q x - Q y) := rfl lemma associated_is_symm : (associated_hom S Q).is_symm := λ x y, by simp only [associated_apply, add_comm, add_left_comm, sub_eq_add_neg] @[simp] lemma associated_comp {N : Type v} [add_comm_group N] [module R N] (f : N →ₗ[R] M) : associated_hom S (Q.comp f) = (associated_hom S Q).comp f f := by { ext, simp only [quadratic_form.comp_apply, bilin_form.comp_apply, associated_apply, linear_map.map_add] } lemma associated_to_quadratic_form (B : bilin_form R M) (x y : M) : associated_hom S B.to_quadratic_form x y = ⅟2 * (B x y + B y x) := by simp only [associated_apply, ← polar_to_quadratic_form, polar, to_quadratic_form_apply] lemma associated_left_inverse (h : B₁.is_symm) : associated_hom S (B₁.to_quadratic_form) = B₁ := bilin_form.ext $ λ x y, by rw [associated_to_quadratic_form, is_symm.eq h x y, ←two_mul, ←mul_assoc, inv_of_mul_self, one_mul] lemma to_quadratic_form_associated : (associated_hom S Q).to_quadratic_form = Q := quadratic_form.ext $ λ x, calc (associated_hom S Q).to_quadratic_form x = ⅟2 * (Q x + Q x) : by simp only [add_assoc, add_sub_cancel', one_mul, to_quadratic_form_apply, add_mul, associated_apply, map_add_self, bit0] ... = Q x : by rw [← two_mul (Q x), ←mul_assoc, inv_of_mul_self, one_mul] -- note: usually `right_inverse` lemmas are named the other way around, but this is consistent -- with historical naming in this file. lemma associated_right_inverse : function.right_inverse (associated_hom S) (bilin_form.to_quadratic_form : _ → quadratic_form R M) := λ Q, to_quadratic_form_associated S Q lemma associated_eq_self_apply (x : M) : associated_hom S Q x x = Q x := begin rw [associated_apply, map_add_self], suffices : (⅟2) * (2 * Q x) = Q x, { convert this, simp only [bit0, add_mul, one_mul], abel }, simp only [← mul_assoc, one_mul, inv_of_mul_self], end /-- `associated'` is the `ℤ`-linear map that sends a quadratic form on a module `M` over `R` to its associated symmetric bilinear form. -/ abbreviation associated' : quadratic_form R M →ₗ[ℤ] bilin_form R M := associated_hom ℤ /-- Symmetric bilinear forms can be lifted to quadratic forms -/ instance can_lift : can_lift (bilin_form R M) (quadratic_form R M) (associated_hom ℕ) bilin_form.is_symm := { prf := λ B hB, ⟨B.to_quadratic_form, associated_left_inverse _ hB⟩ } /-- There exists a non-null vector with respect to any quadratic form `Q` whose associated bilinear form is non-zero, i.e. there exists `x` such that `Q x ≠ 0`. -/ lemma exists_quadratic_form_ne_zero {Q : quadratic_form R M} (hB₁ : Q.associated' ≠ 0) : ∃ x, Q x ≠ 0 := begin rw ←not_forall, intro h, apply hB₁, rw [(quadratic_form.ext h : Q = 0), linear_map.map_zero], end end associated_hom section associated variables [comm_ring R₁] [add_comm_group M] [module R₁ M] variables [invertible (2 : R₁)] -- Note: When possible, rather than writing lemmas about `associated`, write a lemma applying to -- the more general `associated_hom` and place it in the previous section. /-- `associated` is the linear map that sends a quadratic form over a commutative ring to its associated symmetric bilinear form. -/ @[reducible] def associated : quadratic_form R₁ M →ₗ[R₁] bilin_form R₁ M := associated_hom R₁ @[simp] lemma associated_lin_mul_lin (f g : M →ₗ[R₁] R₁) : (lin_mul_lin f g).associated = ⅟(2 : R₁) • (bilin_form.lin_mul_lin f g + bilin_form.lin_mul_lin g f) := by { ext, simp only [smul_add, algebra.id.smul_eq_mul, bilin_form.lin_mul_lin_apply, quadratic_form.lin_mul_lin_apply, bilin_form.smul_apply, associated_apply, bilin_form.add_apply, linear_map.map_add], ring } end associated section anisotropic section semiring variables [semiring R] [add_comm_monoid M] [module R M] /-- An anisotropic quadratic form is zero only on zero vectors. -/ def anisotropic (Q : quadratic_form R M) : Prop := ∀ x, Q x = 0 → x = 0 lemma not_anisotropic_iff_exists (Q : quadratic_form R M) : ¬anisotropic Q ↔ ∃ x ≠ 0, Q x = 0 := by simp only [anisotropic, not_forall, exists_prop, and_comm] lemma anisotropic.eq_zero_iff {Q : quadratic_form R M} (h : anisotropic Q) {x : M} : Q x = 0 ↔ x = 0 := ⟨h x, λ h, h.symm ▸ map_zero Q⟩ end semiring section ring variables [ring R] [add_comm_group M] [module R M] /-- The associated bilinear form of an anisotropic quadratic form is nondegenerate. -/ lemma nondegenerate_of_anisotropic [invertible (2 : R)] (Q : quadratic_form R M) (hB : Q.anisotropic) : Q.associated'.nondegenerate := begin intros x hx, refine hB _ _, rw ← hx x, exact (associated_eq_self_apply _ _ x).symm, end end ring end anisotropic section pos_def variables {R₂ : Type u} [ordered_ring R₂] [add_comm_monoid M] [module R₂ M] variables {Q₂ : quadratic_form R₂ M} /-- A positive definite quadratic form is positive on nonzero vectors. -/ def pos_def (Q₂ : quadratic_form R₂ M) : Prop := ∀ x ≠ 0, 0 < Q₂ x lemma pos_def.smul {R} [linear_ordered_comm_ring R] [module R M] {Q : quadratic_form R M} (h : pos_def Q) {a : R} (a_pos : 0 < a) : pos_def (a • Q) := λ x hx, mul_pos a_pos (h x hx) variables {n : Type*} lemma pos_def.nonneg {Q : quadratic_form R₂ M} (hQ : pos_def Q) (x : M) : 0 ≤ Q x := (eq_or_ne x 0).elim (λ h, h.symm ▸ (map_zero Q).symm.le) (λ h, (hQ _ h).le) lemma pos_def.anisotropic {Q : quadratic_form R₂ M} (hQ : Q.pos_def) : Q.anisotropic := λ x hQx, classical.by_contradiction $ λ hx, lt_irrefl (0 : R₂) $ begin have := hQ _ hx, rw hQx at this, exact this, end lemma pos_def_of_nonneg {Q : quadratic_form R₂ M} (h : ∀ x, 0 ≤ Q x) (h0 : Q.anisotropic) : pos_def Q := λ x hx, lt_of_le_of_ne (h x) (ne.symm $ λ hQx, hx $ h0 _ hQx) lemma pos_def_iff_nonneg {Q : quadratic_form R₂ M} : pos_def Q ↔ (∀ x, 0 ≤ Q x) ∧ Q.anisotropic := ⟨λ h, ⟨h.nonneg, h.anisotropic⟩, λ ⟨n, a⟩, pos_def_of_nonneg n a⟩ lemma pos_def.add (Q Q' : quadratic_form R₂ M) (hQ : pos_def Q) (hQ' : pos_def Q') : pos_def (Q + Q') := λ x hx, add_pos (hQ x hx) (hQ' x hx) lemma lin_mul_lin_self_pos_def {R} [linear_ordered_comm_ring R] [module R M] (f : M →ₗ[R] R) (hf : linear_map.ker f = ⊥) : pos_def (lin_mul_lin f f) := λ x hx, mul_self_pos.2 (λ h, hx $ linear_map.ker_eq_bot'.mp hf _ h) end pos_def end quadratic_form section /-! ### Quadratic forms and matrices Connect quadratic forms and matrices, in order to explicitly compute with them. The convention is twos out, so there might be a factor 2⁻¹ in the entries of the matrix. The determinant of the matrix is the discriminant of the quadratic form. -/ variables {n : Type w} [fintype n] [decidable_eq n] variables [comm_ring R₁] [add_comm_monoid M] [module R₁ M] /-- `M.to_quadratic_form` is the map `λ x, col x ⬝ M ⬝ row x` as a quadratic form. -/ def matrix.to_quadratic_form' (M : matrix n n R₁) : quadratic_form R₁ (n → R₁) := M.to_bilin'.to_quadratic_form variables [invertible (2 : R₁)] /-- A matrix representation of the quadratic form. -/ def quadratic_form.to_matrix' (Q : quadratic_form R₁ (n → R₁)) : matrix n n R₁ := Q.associated.to_matrix' open quadratic_form lemma quadratic_form.to_matrix'_smul (a : R₁) (Q : quadratic_form R₁ (n → R₁)) : (a • Q).to_matrix' = a • Q.to_matrix' := by simp only [to_matrix', linear_equiv.map_smul, linear_map.map_smul] lemma quadratic_form.is_symm_to_matrix' (Q : quadratic_form R₁ (n → R₁)) : Q.to_matrix'.is_symm := begin ext i j, rw [to_matrix', bilin_form.to_matrix'_apply, bilin_form.to_matrix'_apply, associated_is_symm] end end namespace quadratic_form variables {n : Type w} [fintype n] variables [comm_ring R₁] [decidable_eq n] [invertible (2 : R₁)] variables {m : Type w} [decidable_eq m] [fintype m] open_locale matrix @[simp] lemma to_matrix'_comp (Q : quadratic_form R₁ (m → R₁)) (f : (n → R₁) →ₗ[R₁] (m → R₁)) : (Q.comp f).to_matrix' = f.to_matrix'ᵀ ⬝ Q.to_matrix' ⬝ f.to_matrix' := by { ext, simp only [quadratic_form.associated_comp, bilin_form.to_matrix'_comp, to_matrix'] } section discriminant variables {Q : quadratic_form R₁ (n → R₁)} /-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/ def discr (Q : quadratic_form R₁ (n → R₁)) : R₁ := Q.to_matrix'.det lemma discr_smul (a : R₁) : (a • Q).discr = a ^ fintype.card n * Q.discr := by simp only [discr, to_matrix'_smul, matrix.det_smul] lemma discr_comp (f : (n → R₁) →ₗ[R₁] (n → R₁)) : (Q.comp f).discr = f.to_matrix'.det * f.to_matrix'.det * Q.discr := by simp only [matrix.det_transpose, mul_left_comm, quadratic_form.to_matrix'_comp, mul_comm, matrix.det_mul, discr] end discriminant end quadratic_form namespace quadratic_form end quadratic_form namespace bilin_form section semiring variables [semiring R] [add_comm_monoid M] [module R M] /-- A bilinear form is nondegenerate if the quadratic form it is associated with is anisotropic. -/ lemma nondegenerate_of_anisotropic {B : bilin_form R M} (hB : B.to_quadratic_form.anisotropic) : B.nondegenerate := λ x hx, hB _ (hx x) end semiring variables [ring R] [add_comm_group M] [module R M] /-- There exists a non-null vector with respect to any symmetric, nonzero bilinear form `B` on a module `M` over a ring `R` with invertible `2`, i.e. there exists some `x : M` such that `B x x ≠ 0`. -/ lemma exists_bilin_form_self_ne_zero [htwo : invertible (2 : R)] {B : bilin_form R M} (hB₁ : B ≠ 0) (hB₂ : B.is_symm) : ∃ x, ¬ B.is_ortho x x := begin lift B to quadratic_form R M using hB₂ with Q, obtain ⟨x, hx⟩ := quadratic_form.exists_quadratic_form_ne_zero hB₁, exact ⟨x, λ h, hx (Q.associated_eq_self_apply ℕ x ▸ h)⟩, end open finite_dimensional variables {V : Type u} {K : Type v} [field K] [add_comm_group V] [module K V] variable [finite_dimensional K V] /-- Given a symmetric bilinear form `B` on some vector space `V` over a field `K` in which `2` is invertible, there exists an orthogonal basis with respect to `B`. -/ lemma exists_orthogonal_basis [hK : invertible (2 : K)] {B : bilin_form K V} (hB₂ : B.is_symm) : ∃ (v : basis (fin (finrank K V)) K V), B.is_Ortho v := begin unfreezingI { induction hd : finrank K V with d ih generalizing V }, { exact ⟨basis_of_finrank_zero hd, λ _ _ _, zero_left _⟩ }, haveI := finrank_pos_iff.1 (hd.symm ▸ nat.succ_pos d : 0 < finrank K V), -- either the bilinear form is trivial or we can pick a non-null `x` obtain rfl | hB₁ := eq_or_ne B 0, { let b := finite_dimensional.fin_basis K V, rw hd at b, refine ⟨b, λ i j hij, rfl⟩, }, obtain ⟨x, hx⟩ := exists_bilin_form_self_ne_zero hB₁ hB₂, rw [← submodule.finrank_add_eq_of_is_compl (is_compl_span_singleton_orthogonal hx).symm, finrank_span_singleton (ne_zero_of_not_is_ortho_self x hx)] at hd, let B' := B.restrict (B.orthogonal $ K ∙ x), obtain ⟨v', hv₁⟩ := ih (B.restrict_symm hB₂ _ : B'.is_symm) (nat.succ.inj hd), -- concatenate `x` with the basis obtained by induction let b := basis.mk_fin_cons x v' (begin rintros c y hy hc, rw add_eq_zero_iff_neg_eq at hc, rw [← hc, submodule.neg_mem_iff] at hy, have := (is_compl_span_singleton_orthogonal hx).disjoint, rw submodule.disjoint_def at this, have := this (c • x) (submodule.smul_mem _ _ $ submodule.mem_span_singleton_self _) hy, exact (smul_eq_zero.1 this).resolve_right (λ h, hx $ h.symm ▸ zero_left _), end) (begin intro y, refine ⟨-B x y/B x x, λ z hz, _⟩, obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.1 hz, rw [is_ortho, smul_left, add_right, smul_right, div_mul_cancel _ hx, add_neg_self, mul_zero], end), refine ⟨b, _⟩, { rw basis.coe_mk_fin_cons, intros j i, refine fin.cases _ (λ i, _) i; refine fin.cases _ (λ j, _) j; intro hij; simp only [function.on_fun, fin.cons_zero, fin.cons_succ, function.comp_apply], { exact (hij rfl).elim }, { rw [is_ortho, hB₂], exact (v' j).prop _ (submodule.mem_span_singleton_self x) }, { exact (v' i).prop _ (submodule.mem_span_singleton_self x) }, { exact hv₁ (ne_of_apply_ne _ hij), }, } end end bilin_form namespace quadratic_form open finset bilin_form variables {M₁ : Type*} [semiring R] [comm_semiring R₁] [add_comm_monoid M] [add_comm_monoid M₁] variables [module R M] [module R M₁] variables {ι : Type*} [fintype ι] {v : basis ι R M} /-- Given a quadratic form `Q` and a basis, `basis_repr` is the basis representation of `Q`. -/ noncomputable def basis_repr (Q : quadratic_form R M) (v : basis ι R M) : quadratic_form R (ι → R) := Q.comp v.equiv_fun.symm @[simp] lemma basis_repr_apply (Q : quadratic_form R M) (w : ι → R) : Q.basis_repr v w = Q (∑ i : ι, w i • v i) := by { rw ← v.equiv_fun_symm_apply, refl } section variables (R₁) /-- The weighted sum of squares with respect to some weight as a quadratic form. The weights are applied using `•`; typically this definition is used either with `S = R₁` or `[algebra S R₁]`, although this is stated more generally. -/ def weighted_sum_squares [monoid S] [distrib_mul_action S R₁] [smul_comm_class S R₁ R₁] (w : ι → S) : quadratic_form R₁ (ι → R₁) := ∑ i : ι, w i • proj i i end @[simp] lemma weighted_sum_squares_apply [monoid S] [distrib_mul_action S R₁] [smul_comm_class S R₁ R₁] (w : ι → S) (v : ι → R₁) : weighted_sum_squares R₁ w v = ∑ i : ι, w i • (v i * v i) := quadratic_form.sum_apply _ _ _ /-- On an orthogonal basis, the basis representation of `Q` is just a sum of squares. -/ lemma basis_repr_eq_of_is_Ortho {R₁ M} [comm_ring R₁] [add_comm_group M] [module R₁ M] [invertible (2 : R₁)] (Q : quadratic_form R₁ M) (v : basis ι R₁ M) (hv₂ : (associated Q).is_Ortho v) : Q.basis_repr v = weighted_sum_squares _ (λ i, Q (v i)) := begin ext w, rw [basis_repr_apply, ←@associated_eq_self_apply R₁, sum_left, weighted_sum_squares_apply], refine sum_congr rfl (λ j hj, _), rw [←@associated_eq_self_apply R₁, sum_right, sum_eq_single_of_mem j hj], { rw [smul_left, smul_right, smul_eq_mul], ring }, { intros i _ hij, rw [smul_left, smul_right, show associated_hom R₁ Q (v j) (v i) = 0, from hv₂ hij.symm, mul_zero, mul_zero] }, end end quadratic_form
2eade4f3e193a50b2163b01b78c3ec4dd17c9a07
1d265c7dd8cb3d0e1d645a19fd6157a2084c3921
/src/other/odd_and_even_nat.lean
faed2c2e99e5e5b6aca687a787f7a797c1e29f69
[ "MIT" ]
permissive
hanzhi713/lean-proofs
de432372f220d302be09b5ca4227f8986567e4fd
4d8356a878645b9ba7cb036f87737f3f1e68ede5
refs/heads/master
1,585,580,245,658
1,553,646,623,000
1,553,646,623,000
151,342,188
0
1
null
null
null
null
UTF-8
Lean
false
false
5,407
lean
import data.nat.basic import data.set def odd : ℕ → Prop := λ n, ∃ m, n = 2 * m + 1 def even : ℕ → Prop := λ n, ∃ m, n = 2 * m theorem even_or_odd : ∀ n, (even n ∨ odd n) := begin assume n, apply @nat.rec_on (λ n, even n ∨ odd n), left, exact ⟨0, rfl⟩, assume k, assume h, cases h, right, apply exists.elim h, assume m, assume f, rw f, exact ⟨m, rfl⟩, left, apply exists.elim h, assume m, assume f, rw f, exact ⟨m + 1, rfl⟩, end theorem not_both_even_and_odd : ∀ n, ¬ (even n ∧ odd n) := begin assume n, apply @nat.rec_on (λ n, ¬ (even n ∧ odd n)), assume h, apply exists.elim h.2, assume _ f, cases f, assume k, assume h, assume h1, have : even k ∧ odd k, let f : ℕ → ℕ := λ n, n - 1, split, apply exists.elim h1.2, assume m, assume h2, exact ⟨m, congr_arg f h2⟩, apply exists.elim h1.1, assume m, assume h2, apply exists.intro (m - 1), have : k = 2 * m - 1 := congr_arg f h2, rw this, cases m, trivial, simp, calc 2 * nat.succ m - 1 = 2 * (m + 1) - 1 : by trivial ... = 2 * m + 2 * 1 - 1 : by rw mul_add ... = 2 * m + (2 * 1 - 1) : by rw (@nat.add_sub_assoc (2*1) 1 dec_trivial) ... = 1 + 2 * m : by simp, contradiction end theorem not_even_odd: ∀ n, ¬ even n ↔ odd n := begin assume n, split, assume not_even, have h := even_or_odd n, cases h, contradiction, assumption, assume oddn, assume evenn, have h := not_both_even_and_odd n, exact h ⟨evenn, oddn⟩ end theorem not_odd_even: ∀ n, ¬ odd n ↔ even n := begin assume n, split, assume not_odd, have h := even_or_odd n, cases h, assumption, contradiction, assume evenn, assume oddn, have h := not_both_even_and_odd n, exact h ⟨evenn, oddn⟩ end namespace hidden def tilda : ℕ → ℕ → Prop := λ m n, ((even m) ∧ (n = m + 1)) ∨ ((odd m) ∧ n = m - 1) ∨ (m = n) def equiv_tilda : ℕ → set ℕ := λ a, {b | tilda a b} example : equiv_tilda 5 = {4, 5} := begin apply set.ext, assume x, split, assume h, cases h, have : odd 5 := ⟨2, rfl⟩, have : even 5 ∧ odd 5 := ⟨h.1, this⟩, have : false := not_both_even_and_odd 5 this, contradiction, cases h, cases h, rw h_right, simp, rw ←h, simp, assume h, cases h, right, right, apply eq.symm h, cases h, right, left, split, exact ⟨2, rfl⟩, rw h, cases h, end def set_nat : set ℕ := {n | true} theorem Union.intro {U : Type} {I : Type} {A : I → set U} {x : U} (i : I) (h : x ∈ A i) : x ∈ ⋃ i, A i := by {simp, existsi i, exact h} theorem Union.elim {U : Type} {I : Type} {A : I → set U} {b : Prop} {x : U} (h₁ : x ∈ ⋃ i, A i) (h₂ : ∀ (i : I), x ∈ A i → b) : b := by {simp at h₁, cases h₁ with i h, exact h₂ i h} example : (⋃ i, equiv_tilda i) = set_nat := begin apply set.ext, assume x, split, assume h, trivial, assume h, apply @nat.rec_on (λ k, k ∈ ⋃ i, equiv_tilda i), apply Union.intro 0, right, right, trivial, assume k hk, apply Union.elim hk, assume i hi, let f : ℕ → ℕ := λ n, n + 1, cases hi, apply Union.intro (i+2), right, right, rw hi.2, cases hi, apply Union.intro (i), right, right, rw hi.2, rw ←nat.add_one, rw nat.sub_add_cancel, apply exists.elim hi.1, assume a ha, rw ha, have : 2 * a + 1 ≥ 1 := dec_trivial, assumption, apply Union.intro (i+1), right, right, rw hi, end end hidden
456b6a24dc3938661d52fbeba6f32653a3af7c69
e8d6a03af236c510516281c3b076aa984c212a1f
/lean4/ModelCount/ModelCount/Parse.lean
7fc996f5197fb5bad66d76b1b041dd0576e06111
[ "MIT" ]
permissive
minsungc/model-counting
9918a1afb2ef4cc91e6be906956b4ae2b82d10be
02f650741bddb6a94a0729889dfeb8e9b0e8521a
refs/heads/main
1,686,421,950,907
1,624,283,093,000
1,624,283,093,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,945
lean
import ModelCount.Iteg namespace String def readNum (s : Substring) : Nat × Substring := do let s₀ := s.dropWhile (fun c => ! c.isDigit) let s₁ := s₀.takeWhile Char.isDigit let s₂ : Substring := ⟨s₀.1, s₁.3, s₀.3⟩ return (s₁.toNat?.get!, s₂) end String open Iteg def parseIte (s : String) : IteElt := do let (n₀, s₀) := String.readNum s.toSubstring let (n₁, s₁) := String.readNum s₀ let (n₂, s₂) := String.readNum s₁ let (n₃, s₃) := String.readNum s₂ return IteElt.Ite n₁ n₂ n₃ partial def readItegHeader (h : IO.FS.Handle) : IO (Nat × Nat × Nat × Nat) := do let s ← h.getLine if "iteg".isPrefixOf s then let (n₀, s₀) := String.readNum s.toSubstring let (n₁, s₁) := String.readNum s₀ let (n₂, s₂) := String.readNum s₁ let (n₃, s₃) := String.readNum s₂ return (n₀, n₁, n₂, n₃) else readItegHeader h -- For now, only reads the first one partial def readOutputDeclarations (h : IO.FS.Handle) : IO Nat := do let s ← h.getLine if "c Output".isPrefixOf s then let s ← h.getLine let (n₀, s₀) := String.readNum s.toSubstring return n₀ else readOutputDeclarations h partial def findItes (h : IO.FS.Handle) : IO Unit := do let s ← h.getLine if "c ITE".isPrefixOf s then return () else findItes h def readIteg (fname : String) : IO (Nat × Nat × Nat × Array IteElt) := do let h ← IO.FS.Handle.mk fname IO.FS.Mode.read true let (maxIndex, numInputs, numOutputs, numIteElts) ← readItegHeader h let output ← readOutputDeclarations h let mut I : Array IteElt := #[] I := I.push IteElt.Fls I := I.push IteElt.Tr for i in [2:numInputs+2] do I := I.push (IteElt.Var i) findItes h for i in [:numIteElts-numInputs] do I := (dbgTraceIfShared "not shared!" I).push $ parseIte (← h.getLine) return (numInputs, output, numIteElts, I)
fad7e56521febfc33017e7b2f05f93445926fec2
020c82b947b28c4d255384a0466715fbb44e5c1e
/src/play.lean
157caec37dfc7dbf7ff82eba3ad48e386e2719e0
[]
no_license
SnobbyDragon/leanfifteen
79ceb751749fa0185c4f9e60ffa2f128e64fbc3c
4583ab44e1de89a25e693e5e611472a9ba1147b6
refs/heads/main
1,675,887,746,364
1,609,534,902,000
1,609,534,902,000
325,708,959
2
0
null
null
null
null
UTF-8
Lean
false
false
505
lean
import fifteen puzzles fifteentactics fifteeninteractive open fifteen fifteen.tile fifteen.position open puzzles fifteentactics /- Here ye play games :) -/ example : game puzzle_1 := begin unfold game, apply slide_one_step, use [bc, bd], split, split; dec_trivial, sorry -- oops end example : game puzzle_1 := begin [fifteen_tactic'] end example : game easy_cheesy := begin slide_tile dd, finish_game, end example : game easy_cheesy := begin [fifteen_tactic'] slide_tile dd, end
2ab816bae43a2adea45bc1b367c792c6be4b128d
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/logic/basic.lean
0cf578deb171d23addb3f3c83f3409f34d346f77
[]
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
19,493
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Theorems that require decidability hypotheses are in the namespace "decidable". Classical versions are in the namespace "classical". Note: in the presence of automation, this whole file may be unnecessary. On the other hand, maybe it is useful for writing automation. -/ /- miscellany TODO: move elsewhere -/ section miscellany universes u v variables {α : Type u} {β : Type v} lemma eq_iff_le_and_le {α : Type u} [weak_order α] {a b : α} : a = b ↔ (a ≤ b ∧ b ≤ a) := ⟨assume eq, eq ▸ ⟨le_refl a, le_refl a⟩, assume ⟨ab, ba⟩, le_antisymm ab ba⟩ @[simp] lemma prod.mk.inj_iff {α : Type u} {β : Type v} {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ (a₁ = a₂ ∧ b₁ = b₂) := ⟨prod.mk.inj, by cc⟩ @[simp] lemma prod.forall {α : Type u} {β : Type v} {p : α × β → Prop} : (∀x, p x) ↔ (∀a b, p (a, b)) := ⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩ @[simp] lemma prod.exists {α : Type u} {β : Type v} {p : α × β → Prop} : (∃x, p x) ↔ (∃a b, p (a, b)) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ @[simp] lemma set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} = (∀a, p a → q a) := rfl end miscellany /- propositional connectives -/ section propositional variables {a b c d : Prop} /- implies -/ theorem implies_self (h : a) : a := h theorem implies_intro (h : a) (h₂ : b) : a := h theorem implies_false_iff (a : Prop) : (a → false) ↔ ¬ a := iff.rfl /- not -/ theorem {u} not_elim {A : Sort u} (H1 : ¬a) (H2 : a) : A := absurd H2 H1 theorem not_not_of_not_implies : ¬(a → b) → ¬¬a := mt not_elim theorem not_of_not_implies : ¬(a → b) → ¬b := mt implies_intro theorem decidable.not_not_iff (a : Prop) [decidable a] : ¬¬a ↔ a := iff.intro decidable.by_contradiction not_not_intro theorem decidable.not_not_elim {a : Prop} [decidable a] : ¬¬a → a := decidable.by_contradiction theorem decidable.of_not_implies [decidable a] (h : ¬ (a → b)) : a := decidable.by_contradiction (not_not_of_not_implies h) /- and -/ theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right theorem and_implies_left (h : a → b) : a ∧ c → b ∧ c := and_implies h implies_self theorem and_implies_right (h : a → b) : c ∧ a → c ∧ b := and_implies implies_self h theorem and_of_and_of_implies_of_implies (h₁ : a ∧ b) (h₂ : a → c) (h₃ : b → d) : c ∧ d := and_implies h₂ h₃ h₁ theorem and_of_and_of_imp_left (h₁ : a ∧ c) (h : a → b) : b ∧ c := and_implies_left h h₁ theorem and_of_and_of_imp_right (h₁ : c ∧ a) (h : a → b) : c ∧ b := and_implies_right h h₁ theorem and_imp_iff (a b c : Prop) : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λ h a b, h ⟨a, b⟩) and.rec theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false := iff.intro (assume h, (h^.right) (h^.left)) (assume h, h^.elim) theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false := iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim /- or -/ theorem or_of_or_of_implies_of_implies (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := or.imp h₂ h₃ h₁ theorem or_of_or_of_implies_left (h₁ : a ∨ c) (h : a → b) : b ∨ c := or.imp_left h h₁ theorem or_of_or_of_implies_right (h₁ : c ∨ a) (h : a → b) : c ∨ b := or.imp_right h h₁ theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := or.elim h ha (assume h₂, or.elim h₂ hb hc) theorem or_resolve_right (h₁ : a ∨ b) (h₂ : ¬a) : b := or.elim h₁ (not_elim h₂) implies_self theorem or_resolve_left (h₁ : a ∨ b) (h₂ : ¬b) : a := or_resolve_right h₁^.symm h₂ theorem or_implies_distrib (a b c : Prop) : ((a ∨ b) → c) ↔ ((a → c) ∧ (b → c)) := iff.intro (λh, and.intro (implies.trans or.inl h) (implies.trans or.inr h)) (and.rec or.rec) theorem or_iff_or (h1 : a ↔ c) (h2 : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h1) (iff.mp h2)) (or.imp (iff.mpr h1) (iff.mpr h2)) theorem decidable.or_not_self_iff (a : Prop) [decidable a] : a ∨ ¬ a ↔ true := iff.intro (assume h, trivial) (assume h, decidable.em a) theorem decidable.not_or_self_iff (a : Prop) [decidable a] : ¬ a ∨ a ↔ true := iff.intro (assume h, trivial) (assume h, (decidable.em a)^.symm) lemma decidable.or_of_not_implies {a b : Prop} [decidable b] (h : ¬ b → a) : (a ∨ b) := decidable.by_cases or.inr (or.inl ∘ h) lemma not_imp_iff_not_imp {a b : Prop} [decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨assume h hb, decidable.by_contradiction $ assume na, h na hb, mt⟩ /- distributivity -/ theorem and_distrib (a b c : Prop) : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := iff.intro (and.rec (λh, or.imp (and.intro h) (and.intro h))) (or.rec (and_implies_right or.inl) (and_implies_right or.inr)) theorem and_distrib_right (a b c : Prop) : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := iff.trans (iff.trans and.comm (and_distrib c a b)) (or_iff_or and.comm and.comm) theorem or_distrib (a b c : Prop) : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := iff.intro (or.rec (λh, and.intro (or.inl h) (or.inl h)) (and_implies or.inr or.inr)) (and.rec (or.rec (implies.trans or.inl implies_intro) (implies.trans and.intro or.imp_right))) theorem or_distrib_right (a b c : Prop) : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := iff.trans (iff.trans or.comm (or_distrib c a b)) (and_congr or.comm or.comm) /- iff -/ theorem implies_iff {a : Prop} (n : Prop) (ha : a) : (a → b) ↔ b := iff.intro (λf, f ha) implies_intro theorem decidable.not_or_of_implies [decidable a] (h : a → b) : ¬ a ∨ b := if ha : a then or.inr (h ha) else or.inl ha theorem implies_of_not_or (h : ¬ a ∨ b) : a → b := assume ha, or.elim h (assume hna, absurd ha hna) (assume hb, hb) theorem decidable.implies_iff_not_or (a b : Prop) [decidable a] : (a → b) ↔ (¬ a ∨ b) := iff.intro decidable.not_or_of_implies implies_of_not_or theorem not_implies_of_and_not (h : a ∧ ¬ b) : ¬ (a → b) := assume h₁, and.right h (h₁ (and.left h)) theorem decidable.and_not_of_not_implies [decidable a] (h : ¬ (a → b)) : a ∧ ¬ b := ⟨decidable.of_not_implies h, not_of_not_implies h⟩ theorem decidable.not_implies_iff_and_not (a b : Prop) [decidable a] : ¬(a → b) ↔ a ∧ ¬b := iff.intro decidable.and_not_of_not_implies not_implies_of_and_not theorem decidable.peirce (a b : Prop) [decidable a] : ((a → b) → a) → a := if ha : a then λ h, ha else λ h, h (λ h', absurd h' ha) /- de morgan's laws -/ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) := assume ⟨ha, hb⟩, or.elim h (assume hna, hna ha) (assume hnb, hnb hb) theorem decidable.not_or_not_of_not_and [decidable a] (h : ¬ (a ∧ b)) : ¬ a ∨ ¬ b := if ha : a then or.inr (show ¬ b, from assume hb, h ⟨ha, hb⟩) else or.inl ha theorem decidable.not_or_not_of_not_and' [decidable b] (h : ¬ (a ∧ b)) : ¬ a ∨ ¬ b := if hb : b then or.inl (show ¬ a, from assume ha, h ⟨ha, hb⟩) else or.inr hb theorem decidable.not_and_iff (a b : Prop) [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := iff.intro decidable.not_or_not_of_not_and not_and_of_not_or_not theorem not_or_of_not_and_not (h : ¬ a ∧ ¬ b) : ¬ (a ∨ b) := assume h₁, or.elim h₁ (assume ha, and.left h ha) (assume hb, and.right h hb) theorem not_and_not_of_not_or (h : ¬ (a ∨ b)) : ¬ a ∧ ¬ b := and.intro (assume ha, h (or.inl ha)) (assume hb, h (or.inr hb)) theorem not_or_iff (a b : Prop) : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := iff.intro not_and_not_of_not_or not_or_of_not_and_not theorem decidable.or_iff_not_and_not (a b : Prop) [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rewrite [←not_or_iff, decidable.not_not_iff] theorem decidable.and_iff_not_or_not (a b : Prop) [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rewrite [←decidable.not_and_iff, decidable.not_not_iff] /- other identities -/ lemma or_imp_iff_and_imp {a b c : Prop} : ((a ∨ b) → c) ↔ ((a → c) ∧ (b → c)) := ⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩, assume ⟨ha, hb⟩, or.rec ha hb⟩ end propositional /- classical versions -/ namespace classical variables {a b c d : Prop} local attribute [instance] prop_decidable theorem not_not_iff (a : Prop) : ¬¬a ↔ a := decidable.not_not_iff a theorem not_not_elim {a : Prop} : ¬¬a → a := decidable.not_not_elim theorem of_not_implies (h : ¬ (a → b)) : a := decidable.of_not_implies h theorem or_not_self_iff (a : Prop) : a ∨ ¬ a ↔ true := decidable.or_not_self_iff a theorem not_or_self_iff (a : Prop) : ¬ a ∨ a ↔ true := decidable.not_or_self_iff a theorem not_or_of_implies (h : a → b) : ¬ a ∨ b := decidable.not_or_of_implies h theorem implies_iff_not_or (a b : Prop) : (a → b) ↔ (¬ a ∨ b) := decidable.implies_iff_not_or a b theorem and_not_of_not_implies (h : ¬ (a → b)) : a ∧ ¬ b := decidable.and_not_of_not_implies h theorem not_implies_iff_and_not (a b : Prop) : ¬(a → b) ↔ a ∧ ¬b := decidable.not_implies_iff_and_not a b theorem peirce (a b : Prop) : ((a → b) → a) → a := decidable.peirce a b theorem not_or_not_of_not_and (h : ¬ (a ∧ b)) : ¬ a ∨ ¬ b := decidable.not_or_not_of_not_and h theorem not_and_iff (a b : Prop) : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_iff a b theorem or_iff_not_and_not (a b : Prop) : a ∨ b ↔ ¬ (¬a ∧ ¬b) := decidable.or_iff_not_and_not a b theorem and_iff_not_or_not (a b : Prop) : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := decidable.and_iff_not_or_not a b lemma or_of_not_implies {a b : Prop} (h : ¬ b → a) : (a ∨ b) := decidable.or_of_not_implies h end classical /- quantifiers -/ section quantifiers universe variable u variables {α : Type u} {p q : α → Prop} {b : Prop} @[simp] lemma forall_const_iff_of_inhabited [h : inhabited α] {p : Prop} : (α → p) ↔ p := ⟨assume h, h (arbitrary α), assume h _, h⟩ theorem forall_of_forall (h : ∀ x, (p x → q x)) (h₁ : ∀ x, p x) : ∀ x, q x := assume x, h x (h₁ x) theorem exists_of_exists (h : ∀ x, (p x → q x)) (h₁ : ∃ x, p x) : ∃ x, q x := match h₁ with ⟨x, hpx⟩ := ⟨x, h x hpx⟩ end theorem forall_implies_of_exists_implies (h : (∃ x, p x) → b) : ∀ x, p x → b := assume x, assume hpx, h ⟨x, hpx⟩ theorem exists_implies_of_forall_implies (h : ∀ x, p x → b) : (∃ x, p x) → b := Exists.rec h theorem exists_implies_distrib (p : α → Prop) (b : Prop) : ((∃ x, p x) → b) ↔ (∀ x, p x → b) := iff.intro forall_implies_of_exists_implies exists_implies_of_forall_implies --theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x := --forall_implies_of_exists_implies h theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x := exists_implies_of_forall_implies h theorem not_exists_iff_forall_not (p : α → Prop) : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := exists_implies_distrib p false theorem decidable.exists_not_of_not_forall [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] (h : ¬ ∀ x, p x) : ∃ x, ¬ p x := decidable.by_contradiction (assume h₁, h (assume x, decidable.by_contradiction (assume hnpx, h₁ ⟨x, hnpx⟩))) theorem not_forall_of_exists_not (h : ∃ x, ¬ p x) : ¬ ∀ x, p x := assume h₁, match h with ⟨x, hnpx⟩ := hnpx (h₁ x) end theorem decidable.not_forall_iff_exists_not (p : α → Prop) [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := iff.intro decidable.exists_not_of_not_forall not_forall_of_exists_not theorem forall_true_iff : (∀ x : α, true) ↔ true := iff_true_intro (λ h, trivial) theorem forall_p_iff_p (α : Type u) [inhabited α] (p : Prop) : (∀ x : α, p) ↔ p := iff.intro (λ h, h (inhabited.default α)) (λ hp x, hp) theorem exists_p_iff_p (α : Type u) [inhabited α] (p : Prop) : (∃ x : α, p) ↔ p := iff.intro (Exists.rec (λ x (hpx : p), hpx)) (λ hp, ⟨default α, hp⟩) theorem forall_and_distrib (p q : α → Prop) : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (assume h, ⟨(assume x, (h x)^.left), (assume x, (h x)^.right)⟩) (assume h x, ⟨h^.left x, h^.right x⟩) theorem exists_or_distrib (p q : α → Prop) : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := iff.intro (assume ⟨x, hpq⟩, or.elim hpq (assume hpx, or.inl (exists.intro x hpx)) (assume hqx, or.inr (exists.intro x hqx))) (assume hepq, or.elim hepq (assume hepx, match hepx : _ → ∃ x, p x ∨ q x with ⟨x, hpx⟩ := ⟨x, or.inl hpx⟩ end) (assume ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)) @[simp] theorem exists_and_iff_and_exists {q : Prop} {p : α → Prop} : (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) := ⟨assume ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, assume ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩ /- other identities -/ lemma forall_and_comm {α : Sort u} {p q : α → Prop} : (∀a, p a ∧ q a) ↔ ((∀a, p a) ∧ (∀a, q a)) := ⟨assume h, ⟨assume a, (h a)^.left, assume a, (h a)^.right⟩, assume ⟨ha, hb⟩ a, ⟨ha a, hb a⟩⟩ lemma forall_eq_elim {α : Type u} {p : α → Prop} {a' : α} : (∀a, a = a' → p a) ↔ p a' := ⟨assume h, h a' rfl, assume h a eq, eq^.symm ▸ h⟩ end quantifiers /- classical versions -/ namespace classical universe variable u variables {α : Type u} {p : α → Prop} local attribute [instance] prop_decidable theorem exists_not_of_not_forall (h : ¬ ∀ x, p x) : ∃ x, ¬ p x := decidable.exists_not_of_not_forall h theorem not_forall_iff_exists_not (p : α → Prop) : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := decidable.not_forall_iff_exists_not p theorem forall_or_iff_or_forall {q : Prop} {p : α → Prop} : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := ⟨assume h, if hq : q then or.inl hq else or.inr $ assume x, or.resolve_left (h x) hq, assume h x, or.imp_right (assume : ∀x, p x, this x) h⟩ end classical /- bounded quantifiers -/ section bounded_quantifiers universe variable u variables {α : Type u} {r p q : α → Prop} {b : Prop} theorem bforall_congr (h : ∀ x (hrx : r x), p x ↔ q x) : (∀ x (hrx : r x), p x) ↔ (∀ x (hrx : r x), q x) := begin apply forall_congr, intro x, apply forall_congr, apply h end theorem bexists_congr (h : ∀ x (hrx : r x), p x ↔ q x) : (∃ x (hrx : r x), p x) ↔ (∃ x (hrx : r x), q x) := begin apply exists_congr, intros, apply exists_congr, apply h end theorem bforall_of_bforall (h : ∀ x (hrx : r x), (p x → q x)) (h₁ : ∀ x (hrx : r x), p x) : ∀ x (hrx : r x) , q x := assume x, assume hrx, h x hrx (h₁ x hrx) theorem bexists_of_bexists {α : Type} {p q : α → Prop} (h : ∀ x, (p x → q x)) (h₁ : ∃ x, p x) : ∃ x, q x := match h₁ with ⟨x, hpx⟩ := ⟨x, h x hpx⟩ end theorem bforall_of_forall (h : ∀ x, p x) : ∀ x (hrx : r x), p x := λ x hrx, h x theorem forall_of_bforall (h : ∀ x (ht : true), p x) : ∀ x, p x := λ x, h x trivial theorem bexists_of_exists (h : ∃ x, p x) : ∃ x (ht : true), p x := match h with ⟨x, hpx⟩ := ⟨x, trivial, hpx⟩ end theorem exists_of_bexists (h : ∃ x (hrx : r x), p x) : ∃ x, p x := match h with ⟨x, hrx, hpx⟩ := ⟨x, hpx⟩ end theorem bforall_implies_of_bexists_implies (h : (∃ x (hrx : r x), p x) → b) : ∀ x (hrx : r x), p x → b := λ x hrx hpx, h ⟨x, hrx, hpx⟩ theorem bexists_implies_of_bforall_implies (h : ∀ x (hrx : r x), p x → b) : (∃ x (hrx : r x), p x) → b := assume ⟨x, hrx, hpx⟩, h x hrx hpx theorem bexists_implies_distrib (r p : α → Prop) (b : Prop) : ((∃ x (hrx : r x), p x) → b) ↔ (∀ x (hrx : r x), p x → b) := iff.intro bforall_implies_of_bexists_implies bexists_implies_of_bforall_implies theorem bforall_not_of_not_bexists (h : ¬ ∃ x (hrx : r x), p x) : ∀ x (hrx : r x), ¬ p x := bforall_implies_of_bexists_implies h theorem not_bexists_of_bforall_not (h : ∀ x (hrx : r x), ¬ p x) : ¬ ∃ x (hrx : r x), p x := bexists_implies_of_bforall_implies h theorem not_bexists_iff_bforall_not (r p : α → Prop) : (¬ ∃ x (hrx : r x) , p x) ↔ (∀ x (h : r x), ¬ p x) := bexists_implies_distrib r p false theorem decidable.bexists_not_of_not_bforall [decidable (∃ x (hrx : r x), ¬ p x)] [∀ x, decidable (p x)] (h : ¬ ∀ x (hrx : r x), p x) : ∃ x (hr : r x), ¬ p x := decidable.by_contradiction (assume h₁, h (assume x, assume hrx, decidable.by_contradiction (assume hnpx, h₁ ⟨x, hrx, hnpx⟩))) theorem not_bforall_of_bexists_not (h : ∃ x (hrx : r x), ¬ p x) : ¬ ∀ x (hrx : r x), p x := assume h₁, match h with ⟨x, hrx, hnpx⟩ := hnpx (h₁ x hrx) end theorem decidable.not_bforall_iff_bexists_not (r p : α → Prop) [decidable (∃ x (hrx : r x), ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x (hrx : r x), p x) ↔ (∃ x (hrx : r x), ¬ p x) := iff.intro decidable.bexists_not_of_not_bforall not_bforall_of_bexists_not theorem bforall_true_iff (r : α → Prop): (∀ x (hrx : r x), true) ↔ true := iff_true_intro (λ h hrx, trivial) theorem bforall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (assume h, ⟨(assume x, (h x)^.left), (assume x, (h x)^.right)⟩) (assume h x, ⟨h^.left x, h^.right x⟩) theorem bexists_or_distrib (r p q : α → Prop) : (∃ x (hrx : r x), p x ∨ q x) ↔ (∃ x (hrx : r x), p x) ∨ (∃ x (hrx : r x), q x) := iff.intro (assume ⟨x, hrx, hpq⟩, or.elim hpq (assume hpx, or.inl (exists.intro x (exists.intro hrx hpx))) (assume hqx, or.inr (exists.intro x (exists.intro hrx hqx)))) (assume hepq, or.elim hepq (assume hepx, match hepx : _ → ∃ x (hrx : r x), p x ∨ q x with ⟨x, hrx, hpx⟩ := ⟨x, hrx, or.inl hpx⟩ end) (assume ⟨x, hrx, hqx⟩, ⟨x, hrx, or.inr hqx⟩)) end bounded_quantifiers -- TODO(Jeremy): merge with previous section section universe variable uu variables {α : Type uu} {p q : α → Prop} @[simp] theorem exists_prop_iff (p q : Prop) : (∃ h : p, q) ↔ p ∧ q := iff.intro begin intro h', cases h', split, repeat { assumption } end begin intro h', cases h', split, repeat { assumption } end theorem bexists.elim {b : Prop} (h : ∃ x : α, ∃ h : p x, q x) (h' : ∀ (a : α), p a → q a → b) : b := exists.elim h (λ a h₁, exists.elim h₁ (h' a)) theorem bexists.intro (a : α) (h₁ : p a) (h₂ : q a) : ∃ x, ∃ h : p x, q x := exists.intro a (exists.intro h₁ h₂) end namespace classical universe variable u variables {α : Type u} {r p : α → Prop} local attribute [instance] prop_decidable theorem bexists_not_of_not_bforall (h : ¬ ∀ x (hrx : r x), p x) : ∃ x (hr : r x), ¬ p x := decidable.bexists_not_of_not_bforall h theorem not_bforall_iff_bexists_not (r p : α → Prop) : (¬ ∀ x (hrx : r x), p x) ↔ (∃ x (hrx : r x), ¬ p x) := decidable.not_bforall_iff_bexists_not r p end classical
efe798c8d1ada28c1b15935046d554a96d9a7481
94637389e03c919023691dcd05bd4411b1034aa5
/src/zzz_junk/exam1_grad.lean
2625a662a062759d9829556a675f0327caa612a8
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
5,944
lean
import algebra.module.basic universes u /- A vector space combines a set of scalar values and a set of vector objects. In a Lean formalization, these sets will be represented by two types (called R and M in Lean's library). The set of scalars must be a field, which means you have all of the usual operations and properties of arithmetic for scalars; and the set of vectors must be an additive, commutative group, so you can add scalars but there is no operation for multiplying them. In a vector space you can also multiply a scalar by a vector, to "scale" it. To test your understanding and ability to apply concepts we've studied in class and on homeworks, you will show that a pair of types and operations on them do form a vector space. To this end, you will assume that K is a non-empty field, it doesn't matter what. K (R in the Lean libraries) is the scalar field for your vector space, -/ variables (K : Type u) [field K] [inhabited K] /- The vectors, on the other hand, are ordered pairs of values of type K, i.e., values of type K ⨯ K (i.e., prod K K). -/ /- Before going any further, try to convince yourself completely informally that the pair of types, K (K × K), forms a vector space with the scalars being K objects, vectors being pair-of-K objects, you add ordered pairs component-wise, multiplying a scalar by a vector (pair) scales each of its two components. Is it now true, for example, that adding two scalars (a + b) and then multiplying that by a vector, v, is the same as adding a times v and b times v? Try it using the real numbers for K. Good. -/ /- Operations: add, scale, -/ def add : K × K → K × K → K × K | (f1,s1) (f2,s2) := ⟨ f1 + f2, s1 + s2 ⟩ def scale : K → K × K → K × K | a (f,s) := ⟨ a * f, a * s ⟩ -- delete def negate : K × K → K × K | (f,s) := ⟨ -1 * f, -1 * s ⟩ def sub : K × K → K × K → K × K | l1 l2 := add K l1 (negate K l2) --endelete /- You exam task is to instantate the vector_space typeclass for the types K and K ⨯ K. Doing this will certify that you really do have a mathematical vector space (except you will stub out the proofs for now), and will provide the benefits of Lean-library-defined notations when subsequently writing code involving vector spaces. -/ /- To get you started, you will now be guided through the first few steps of the process. Follow directions as you proceed through the code below. They ask you to jump around a bit so that (1) you see things in an order that makes sense, and (2) Lean sees the in the order it needs to compile the code. -/ /- Task: produce a "vector_space K (K × K)" instance. -/ instance : vector_space K (K × K) := _ /- Move this line of code to come after all of the prerequisites, once they are built, below. We put it here at the top so that you can see the main goal up front: build an instance, vector_space K (K × K), of the vector_space typeclass. Read on. -/ -- hover on "vector_space" for info from mathlib #check vector_space K (K × K) /- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like ℝ^n, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ /- Don't gloss over the definitions. They are the keys. Go see the definition in the Lean library. Read it! It says that vector_space K (K ⨯ K) is really just abbreviation for semimodule R M. -/ /- vector_space : Π (R : Type u_1) -- ring of scalars (M : Type u_2) -- set of vectoids [_inst_1 : field R] -- implicit [_inst_2 : add_comm_group M], -- implicit Type (max u_1 u_2) := semimodule R M -- a vector space R M is a semimodule R M -/ /- Please jump directly to "semimodule" below. You will be directed to return to this point further on. -/ instance : distrib_mul_action K (K × K) := _ /- distrib_mul_action : Π (α : Type u) (β : Type v) [_inst_1 : monoid α] [_inst_2 : add_monoid β], Type (max u v) -/ _ /- Semimodule -/ #check semimodule /- What we need is a "semimodule K (K × K) instance!" To get that, we have to figure out what we need. To do this, go look at the semimodule definition. -/ /- class semimodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) -/ /- It tells us that to create a semimodule instance we'll need instances of semiring K, add_comm_monoid K×K, and distrib_mul_action K (K⨯L), and we'll need to provide new operations and/or rules. -/ /- NB on NOTATION: In addition to abstract syntax, the Lean libraries define infix notations. What this means is that instance of writing "mul", for example, you can use * to denote "multiplication as defined for a given structure." You will see notation in the statements of the properties of a semimodule + means add in the given field, and the • means "smul", an operation that needs to be provided, for multiplying (scaling) a vector by a scalar on the left. -/ instance : semimodule K (K × K) := ⟨ _, _ ⟩ /- failed to synthesize type class instance for K : Type u, _inst_1 : field K, _inst_2 : inhabited K ⊢ distrib_mul_action K (K × K) -/ /- Now go back and see the distrib_mul_action helper, analyze what's missing there, provide the missing pieces recursively until you're you're done. Reminder: You can jump into the Lean library to see exactly how anything there is defined. Just right click and select go to definition. You can also hover over missing values or select them and look in the Lean Info View to find out more about what's missing and needed at a particular point. -/
89dc5a49f564a56d71a685dfb81f5475526a71dd
485e6bb97db7c79fe8ec90624f4db4a1fccf69f6
/src/whatIsALanguage.lean
7cddb353d6a079804d342575d2f1588193f415ee
[]
no_license
soneyahossain/complogic-s21
afc67a5e6bbb4686a5351cb4f159073dcd42fb41
091f092eae5db34997d977d0fb806dcbc0cf5c40
refs/heads/master
1,677,292,402,207
1,612,378,227,000
1,612,378,227,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,088
lean
inductive Syntax : Type | I | II | III | IV | V inductive Semantics : Type | one | two | three | four | five #reduce Semantics.one open Semantics open Syntax #reduce one /- I --> one II --> two III --> three IV --> four V --> five -/ /- A little bit of Lean -/ -- Literal -- Variable -- Application #reduce 1 -- literal def x := 1 -- variable #reduce x def my_id : nat → nat := (λ n, n) -- lambda expression, literal -- type inference -- T V #reduce (my_id 1) #reduce (my_id 4) -- #reduce (my_id "Hello, Lean!") def my_id' : ℕ → ℕ -- by cases | n := n def my_id'' (n : nat) : nat := -- C style syntax n #reduce my_id #reduce my_id'' -- End of "A little bit of Lean" -- Another aside def my_add (n m : ℕ) := nat.add n m -- n + m #reduce my_add 2 3 def my_add' : ℕ → (ℕ → ℕ) := λ n, λ m, n + m def k := my_add' 5 #reduce k 6 /- Our semantics! -/ def my_eval : Syntax → Semantics | I := one | II := two | III := three | IV := four | V := five #reduce my_eval II
be56e7eb6ed45fc6464d4d368beeecc3ed83315f
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/exceptional.lean
441ba9486367dbe59eb2c9668a23427f1cf51e23
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,610
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.control.monad init.meta.format init.util /-- An exceptional is similar to `Result` in Haskell. Remark: we use a function that produces a format object as the exception information. Motivation: the formatting object may be big, and we may create it on demand.-/ meta inductive exceptional (α : Type) | success : α → exceptional | exception : (options → format) → exceptional section open exceptional variables {α : Type} variables [has_to_string α] protected meta def exceptional.to_string : exceptional α → string | (success a) := to_string a | (exception e) := "Exception: " ++ to_string (e options.mk) meta instance : has_to_string (exceptional α) := has_to_string.mk exceptional.to_string end namespace exceptional variables {α β : Type} protected meta def to_bool : exceptional α → bool | (success _) := tt | (exception _) := ff protected meta def to_option : exceptional α → option α | (success a) := some a | (exception _) := none @[inline] protected meta def bind (e₁ : exceptional α) (e₂ : α → exceptional β) : exceptional β := exceptional.cases_on e₁ (λ a, e₂ a) (λ f, exception f) @[inline] protected meta def return (a : α) : exceptional α := success a @[inline] meta def fail (f : format) : exceptional α := exception (λ u, f) end exceptional meta instance : monad exceptional := {pure := @exceptional.return, bind := @exceptional.bind}
5bf4aab6eee27fbd531dcca8e1cac78bdf6b9b24
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/PreDefinition/WF/Fix.lean
f2c2e3bcf2d695cef698e5a83e54fe227e7710f1
[ "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
7,033
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.Match.Match import Lean.Meta.Tactic.Simp.Main import Lean.Meta.Tactic.Cleanup import Lean.Elab.RecAppSyntax import Lean.Elab.PreDefinition.Basic import Lean.Elab.PreDefinition.Structural.Basic namespace Lean.Elab.WF open Meta private def toUnfold : Std.PHashSet Name := [``measure, ``id, ``Prod.lex, ``invImage, ``InvImage, ``Nat.lt_wfRel].foldl (init := {}) fun s a => s.insert a private def applyDefaultDecrTactic (mvarId : MVarId) : TermElabM Unit := do let ctx ← Simp.Context.mkDefault let ctx := { ctx with simpLemmas.toUnfold := toUnfold } if let some mvarId ← simpTarget mvarId ctx then -- TODO: invoke tactic to close the goal Term.reportUnsolvedGoals [mvarId] throwAbortTactic private def mkDecreasingProof (decreasingProp : Expr) (decrTactic? : Option Syntax) : TermElabM Expr := do let mvar ← mkFreshExprSyntheticOpaqueMVar decreasingProp let mvarId := mvar.mvarId! let mvarId ← cleanup mvarId match decrTactic? with | none => applyDefaultDecrTactic mvarId | some decrTactic => Term.runTactic mvarId decrTactic instantiateMVars mvar private partial def replaceRecApps (recFnName : Name) (decrTactic? : Option Syntax) (F : Expr) (e : Expr) : TermElabM Expr := let rec loop (F : Expr) (e : Expr) : TermElabM Expr := do match e with | Expr.lam n d b c => withLocalDecl n c.binderInfo (← loop F d) fun x => do mkLambdaFVars #[x] (← loop F (b.instantiate1 x)) | Expr.forallE n d b c => withLocalDecl n c.binderInfo (← loop F d) fun x => do mkForallFVars #[x] (← loop F (b.instantiate1 x)) | Expr.letE n type val body _ => withLetDecl n (← loop F type) (← loop F val) fun x => do mkLetFVars #[x] (← loop F (body.instantiate1 x)) (usedLetOnly := false) | Expr.mdata d b _ => if let some stx := getRecAppSyntax? e then withRef stx <| loop F b else return mkMData d (← loop F b) | Expr.proj n i e _ => return mkProj n i (← loop F e) | Expr.app _ _ _ => let processApp (e : Expr) : TermElabM Expr := e.withApp fun f args => do if f.isConstOf recFnName && args.size == 1 then let r := mkApp F args[0] let decreasingProp := (← whnf (← inferType r)).bindingDomain! return mkApp r (← mkDecreasingProof decreasingProp decrTactic?) else return mkAppN (← loop F f) (← args.mapM (loop F)) let matcherApp? ← matchMatcherApp? e match matcherApp? with | some matcherApp => if !Structural.recArgHasLooseBVarsAt recFnName 0 e then processApp e else let matcherApp ← mapError (matcherApp.addArg F) (fun msg => "failed to add functional argument to 'matcher' application" ++ indentD msg) let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let FAlt := xs[numParams - 1] mkLambdaFVars xs (← loop FAlt altBody) pure { matcherApp with alts := altsNew }.toExpr | none => processApp e | e => Structural.ensureNoRecFn recFnName e loop F e /-- Refine `F` over `Sum.casesOn` -/ private partial def processSumCasesOn (x F val : Expr) (k : (x : Expr) → (F : Expr) → (val : Expr) → TermElabM Expr) : TermElabM Expr := do if x.isFVar && val.isAppOfArity ``Sum.casesOn 6 && val.getArg! 3 == x && (val.getArg! 4).isLambda && (val.getArg! 5).isLambda then let args := val.getAppArgs let α := args[0] let β := args[1] let FDecl ← getLocalDecl F.fvarId! let (motiveNew, u) ← lambdaTelescope args[2] fun xs type => do let type ← mkArrow (FDecl.type.replaceFVar x xs[0]) type return (← mkLambdaFVars xs type, ← getLevel type) let mkMinorNew (ctorName : Name) (minor : Expr) : TermElabM Expr := lambdaTelescope minor fun xs body => do let xNew ← xs[0] let valNew ← mkLambdaFVars xs[1:] body let FTypeNew := FDecl.type.replaceFVar x (← mkAppOptM ctorName #[α, β, xNew]) withLocalDeclD FDecl.userName FTypeNew fun FNew => do mkLambdaFVars #[xNew, FNew] (← processSumCasesOn xNew FNew valNew k) let minorLeft ← mkMinorNew ``Sum.inl args[4] let minorRight ← mkMinorNew ``Sum.inr args[5] let result := mkAppN (mkConst ``Sum.casesOn [u, (← getDecLevel α), (← getDecLevel β)]) #[α, β, motiveNew, x, minorLeft, minorRight, F] return result else k x F val /-- Refine `F` over `PSigma.casesOn` -/ private partial def processPSigmaCasesOn (x F val : Expr) (k : (F : Expr) → (val : Expr) → TermElabM Expr) : TermElabM Expr := do if x.isFVar && val.isAppOfArity ``PSigma.casesOn 5 && val.getArg! 3 == x && (val.getArg! 4).isLambda && (val.getArg! 4).bindingBody!.isLambda then let args := val.getAppArgs let [_, u, v] ← val.getAppFn.constLevels! | unreachable! let α := args[0] let β := args[1] let FDecl ← getLocalDecl F.fvarId! let (motiveNew, w) ← lambdaTelescope args[2] fun xs type => do let type ← mkArrow (FDecl.type.replaceFVar x xs[0]) type return (← mkLambdaFVars xs type, ← getLevel type) let minor ← lambdaTelescope args[4] fun xs body => do let a ← xs[0] let xNew ← xs[1] let valNew ← mkLambdaFVars xs[2:] body let FTypeNew := FDecl.type.replaceFVar x (← mkAppOptM `PSigma.mk #[α, β, a, xNew]) withLocalDeclD FDecl.userName FTypeNew fun FNew => do mkLambdaFVars #[a, xNew, FNew] (← processPSigmaCasesOn xNew FNew valNew k) let result := mkAppN (mkConst ``PSigma.casesOn [w, u, v]) #[α, β, motiveNew, x, minor, F] return result else k F val def mkFix (preDef : PreDefinition) (wfRel : Expr) (decrTactic? : Option Syntax) : TermElabM PreDefinition := do let wfFix ← forallBoundedTelescope preDef.type (some 1) fun x type => do let x := x[0] let α ← inferType x let u ← getLevel α let v ← getLevel type let motive ← mkLambdaFVars #[x] type let rel := mkProj ``WellFoundedRelation 0 wfRel let wf := mkProj ``WellFoundedRelation 1 wfRel return mkApp4 (mkConst ``WellFounded.fix [u, v]) α motive rel wf forallBoundedTelescope (← whnf (← inferType wfFix)).bindingDomain! (some 2) fun xs _ => do let x := xs[0] let F := xs[1] let val := preDef.value.betaRev #[x] let val ← processSumCasesOn x F val fun x F val => processPSigmaCasesOn x F val (replaceRecApps preDef.declName decrTactic?) return { preDef with value := mkApp wfFix (← mkLambdaFVars #[x, F] val) } end Lean.Elab.WF
9aa1f9d95606d72a0c98dc4ce03d179f3ecd7167
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/data/string/basic.lean
5cbf0c47b96455c25eb5cb55e95992d3e1cc2c70
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
2,513
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.basic import init.data.char.basic private structure string_imp := (data : list char) def string := string_imp def list.as_string (s : list char) : string := ⟨s.reverse⟩ namespace string def empty : string := ⟨list.nil⟩ instance : inhabited string := ⟨empty⟩ def length : string → nat | ⟨s⟩ := s.length instance : has_sizeof string := ⟨string.length⟩ def str : string → char → string | ⟨s⟩ c := ⟨c::s⟩ def append : string → string → string | ⟨a⟩ ⟨b⟩ := ⟨b ++ a⟩ def is_empty : string → bool | ⟨[]⟩ := tt | _ := ff instance : has_append string := ⟨string.append⟩ def to_list : string → list char | ⟨s⟩ := s.reverse def pop_back : string → string | ⟨s⟩ := ⟨s.tail⟩ def popn_back : string → nat → string | ⟨s⟩ n := ⟨s.dropn n⟩ def intercalate (s : string) (ss : list string) : string := (list.intercalate s.to_list (ss.map to_list)).as_string def fold {α} (a : α) (f : α → char → α) (s : string) : α := s.to_list.foldl f a def front (s : string) : char := s.to_list.head def back : string → char | ⟨[]⟩ := default char | ⟨c::cs⟩ := c def backn : string → nat → string | ⟨s⟩ n := ⟨s.taken n⟩ def join (l : list string) : string := l.foldl (λ r s, r ++ s) "" end string open list string private def utf8_length_aux : nat → nat → list char → nat | 0 r (c::s) := let n := char.to_nat c in if n < 0x80 then utf8_length_aux 0 (r+1) s else if 0xC0 ≤ n ∧ n < 0xE0 then utf8_length_aux 1 (r+1) s else if 0xE0 ≤ n ∧ n < 0xF0 then utf8_length_aux 2 (r+1) s else if 0xF0 ≤ n ∧ n < 0xF8 then utf8_length_aux 3 (r+1) s else if 0xF8 ≤ n ∧ n < 0xFC then utf8_length_aux 4 (r+1) s else if 0xFC ≤ n ∧ n < 0xFE then utf8_length_aux 5 (r+1) s else utf8_length_aux 0 (r+1) s | (n+1) r (c::s) := utf8_length_aux n r s | n r [] := r def string.utf8_length : string → nat | s := utf8_length_aux 0 0 s.to_list export string (utf8_length) private def to_nat_core : list char → nat → nat | [] r := r | (c::cs) r := to_nat_core cs (char.to_nat c - char.to_nat '0' + r*10) def string.to_nat (s : string) : nat := to_nat_core s.to_list 0 def char.to_string (c : char) : string := str empty c
97563671560286e15c81c6d22f0769954567e4a8
b147e1312077cdcfea8e6756207b3fa538982e12
/data/real/basic.lean
be337c4154f87bf937f386ecf2979745a3bc59d6
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,386
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro The (classical) real numbers ℝ. This is a direct construction from Cauchy sequences. -/ import order.conditionally_complete_lattice data.real.cau_seq algebra.big_operators algebra.archimedean def real := @quotient (cau_seq ℚ abs) cau_seq.equiv notation `ℝ` := real namespace real open rat cau_seq def mk : cau_seq ℚ abs → ℝ := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq ℝ ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat (x : ℚ) : ℝ := mk (const abs x) instance : has_zero ℝ := ⟨of_rat 0⟩ instance : has_one ℝ := ⟨of_rat 1⟩ instance : inhabited ℝ := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add ℝ := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r] using add_lim_zero hf hg⟩ @[simp] theorem mk_add (f g : cau_seq ℚ abs) : mk f + mk g = mk (f + g) := rfl instance : has_neg ℝ := ⟨λ x, quotient.lift_on x (λ f, mk (-f)) $ λ f₁ f₂ hf, quotient.sound $ by simpa [(≈), setoid.r] using neg_lim_zero hf⟩ @[simp] theorem mk_neg (f : cau_seq ℚ abs) : -mk f = mk (-f) := rfl instance : has_mul ℝ := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, mul_add, mul_comm] using add_lim_zero (mul_lim_zero g₁ hf) (mul_lim_zero f₂ hg)⟩ @[simp] theorem mk_mul (f g : cau_seq ℚ abs) : mk f * mk g = mk (f * g) := rfl theorem of_rat_add (x y : ℚ) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : ℚ) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : ℚ) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) instance : comm_ring ℝ := by refine { neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, .. }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [show 0 = mk 0, from rfl, show 1 = mk 1, from rfl, mul_left_comm, mul_comm, mul_add] } /- Extra instances to short-circuit type class resolution -/ instance : semigroup ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : ring ℝ := by apply_instance theorem of_rat_sub (x y : ℚ) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) instance : has_lt ℝ := ⟨λ x y, quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩⟩ @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := iff.rfl @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := iff_of_eq (congr_arg pos (sub_zero f)) instance : has_le ℝ := ⟨λ x y, x < y ∨ x = y⟩ @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := or_congr iff.rfl quotient.eq theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := quotient.induction_on₃ a b c (λ f g h, iff_of_eq (congr_arg pos $ by rw add_sub_add_left_eq_sub)) instance : linear_order ℝ := { le := (≤), lt := (<), le_refl := λ a, or.inr rfl, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ f g h, by simpa using le_trans, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ f g, le_total := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa using le_total f g } instance : partial_order ℝ := by apply_instance instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := const_lt protected theorem zero_lt_one : (0 : ℝ) < 1 := of_rat_lt.2 zero_lt_one protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := quotient.induction_on₂ a b $ λ f g, by simpa using cau_seq.mul_pos instance : linear_ordered_comm_ring ℝ := { add_le_add_left := λ a b h c, (le_iff_le_iff_lt_iff_lt.2 $ real.add_lt_add_iff_left c).2 h, zero_ne_one := ne_of_lt real.zero_lt_one, mul_nonneg := λ a b a0 b0, match a0, b0 with | or.inl a0, or.inl b0 := le_of_lt (real.mul_pos a0 b0) | or.inr a0, _ := by simp [a0.symm] | _, or.inr b0 := by simp [b0.symm] end, mul_pos := @real.mul_pos, zero_lt_one := real.zero_lt_one, add_lt_add_left := λ a b h c, (real.add_lt_add_iff_left c).2 h, ..real.comm_ring, ..real.linear_order } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_ring ℝ := by apply_instance instance : ordered_ring ℝ := by apply_instance instance : ordered_comm_group ℝ := by apply_instance instance : ordered_cancel_comm_monoid ℝ := by apply_instance instance : integral_domain ℝ := by apply_instance instance : domain ℝ := by apply_instance local attribute [instance] classical.prop_decidable noncomputable instance : has_inv ℝ := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : ℝ)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (mk f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg protected theorem inv_mul_cancel {x : ℝ} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end noncomputable instance : discrete_linear_ordered_field ℝ := { inv := has_inv.inv, inv_mul_cancel := @real.inv_mul_cancel, mul_inv_cancel := λ x x0, by rw [mul_comm, real.inv_mul_cancel x0], inv_zero := inv_zero, decidable_le := by apply_instance, ..real.linear_ordered_comm_ring } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_field ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_comm_ring ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_comm_group ℝ := by apply_instance noncomputable instance : decidable_linear_order ℝ := by apply_instance noncomputable instance : discrete_field ℝ := by apply_instance noncomputable instance : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := eq_cast of_rat rfl of_rat_add of_rat_mul theorem le_mk_of_forall_le {x : ℝ} {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := quotient.induction_on x $ λ g h, le_of_not_lt $ λ ⟨K, K0, hK⟩, let ⟨i, H⟩ := exists_forall_ge_and h $ exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0) in begin apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} : (∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) → mk f ≤ x | ⟨i, H⟩ := by rw [← neg_le_neg_iff, mk_neg]; exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, quotient.induction_on x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin have, { refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } }, cases classical.axiom_of_choice this with f hf, dsimp at f hf, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff (nat.cast_pos.2 n0)).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff (nat.cast_pos.2 n0), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le (nat.cast_pos.2 n0) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable def Sup (S : set ℝ) : ℝ := if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ noncomputable def Inf (S : set ℝ) : ℝ := -Sup {x | -x ∈ S} theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ open lattice noncomputable instance lattice : lattice ℝ := by apply_instance noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := real.Sup, Inf := real.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H, ..real.linear_order, ..real.lattice} theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) ((sub_lt_self_iff _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable def lim (f : ℕ → ℝ) : ℝ := if hf : is_cau_seq abs f then classical.some (cau_seq_converges ⟨f, hf⟩) else 0 theorem equiv_lim (f : cau_seq ℝ abs) : f ≈ const abs (lim f) := by simp [lim, f.is_cau]; cases f with f hf; exact classical.some_spec (cau_seq_converges ⟨f, hf⟩) theorem sqrt_exists : ∀ {x : ℝ}, 0 ≤ x → ∃ y, 0 ≤ y ∧ y * y = x := suffices H : ∀ {x : ℝ}, 0 < x → x ≤ 1 → ∃ y, 0 < y ∧ y * y = x, begin intros x x0, cases x0, cases le_total x 1 with x1 x1, { rcases H x0 x1 with ⟨y, y0, hy⟩, exact ⟨y, le_of_lt y0, hy⟩ }, { have := (inv_le_inv x0 zero_lt_one).2 x1, rw inv_one at this, rcases H (inv_pos x0) this with ⟨y, y0, hy⟩, refine ⟨y⁻¹, le_of_lt (inv_pos y0), _⟩, rw [← mul_inv', hy, inv_inv'] }, { exact ⟨0, by simp [x0.symm]⟩ } end, λ x x0 x1, begin let S := {y | 0 < y ∧ y * y ≤ x}, have lb : x ∈ S := ⟨x0, by simpa using (mul_le_mul_right x0).2 x1⟩, have ub : ∀ y ∈ S, (y:ℝ) ≤ 1, { intros y yS, cases yS with y0 yx, refine (mul_self_le_mul_self_iff (le_of_lt y0) zero_le_one).2 _, simpa using le_trans yx x1 }, have S0 : 0 < Sup S := lt_of_lt_of_le x0 (le_Sup _ ⟨_, ub⟩ lb), refine ⟨Sup S, S0, le_antisymm (not_lt.1 $ λ h, _) (not_lt.1 $ λ h, _)⟩, { rw [← div_lt_iff S0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at h, rcases h with ⟨y, ⟨y0, yx⟩, hy⟩, rw [div_lt_iff S0, ← div_lt_iff' y0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at hy, rcases hy with ⟨z, ⟨z0, zx⟩, hz⟩, rw [div_lt_iff y0] at hz, exact not_lt_of_lt ((mul_lt_mul_right y0).1 (lt_of_le_of_lt yx hz)) ((mul_lt_mul_left z0).1 (lt_of_le_of_lt zx hz)) }, { let s := Sup S, let y := s + (x - s * s) / 3, replace h : 0 < x - s * s := sub_pos.2 h, have _30 := bit1_pos zero_le_one, have : s < y := (lt_add_iff_pos_right _).2 (div_pos h _30), refine not_le_of_lt this (le_Sup S ⟨_, ub⟩ ⟨lt_trans S0 this, _⟩), rw [add_mul_self_eq, add_assoc, ← le_sub_iff_add_le', ← add_mul, ← le_div_iff (div_pos h _30), div_div_cancel (ne_of_gt h)], apply add_le_add, { simpa using (mul_le_mul_left (@two_pos ℝ _)).2 (Sup_le_ub _ ⟨_, lb⟩ ub) }, { rw [div_le_one_iff_le _30], refine le_trans (sub_le_self _ (mul_self_nonneg _)) (le_trans x1 _), exact (le_add_iff_nonneg_left _).2 (le_of_lt two_pos) } } end def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ | 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt | (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2 theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i | 0 := by rw [sqrt_aux, mk_nat_eq, mk_eq_div]; apply div_nonneg'; exact int.cast_nonneg.2 (int.of_nat_nonneg _) | (n + 1) := le_max_left _ _ /- TODO(Mario): finish the proof theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧ mk ⟨sqrt_aux f, h⟩ = x := begin rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩, suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x, { exact this.imp (λ h e, ⟨x, x0, hx, e⟩) }, apply of_near, suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i, { rcases this with ⟨δ, δ0, hδ⟩, intros, } end -/ noncomputable def sqrt (x : ℝ) : ℝ := classical.some (sqrt_exists (le_max_left 0 x)) /-quotient.lift_on x (λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩) (λ f g e, begin rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩, rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩, refine xs.trans (eq.trans _ ys.symm), rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg], congr' 1, exact quotient.sound e end)-/ theorem sqrt_prop (x : ℝ) : 0 ≤ sqrt x ∧ sqrt x * sqrt x = max 0 x := classical.some_spec (sqrt_exists (le_max_left 0 x)) /-quotient.induction_on x $ λ f, by rcases sqrt_aux_converges f with ⟨hf, _, x0, xf, rfl⟩; exact ⟨x0, xf⟩-/ theorem sqrt_eq_zero_of_nonpos {x : ℝ} (h : x ≤ 0) : sqrt x = 0 := eq_zero_of_mul_self_eq_zero $ (sqrt_prop x).2.trans $ max_eq_left h theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := (sqrt_prop x).1 @[simp] theorem mul_self_sqrt {x : ℝ} (h : 0 ≤ x) : sqrt x * sqrt x = x := (sqrt_prop x).2.trans (max_eq_right h) @[simp] theorem sqrt_mul_self {x : ℝ} (h : 0 ≤ x) : sqrt (x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_iff_mul_self_eq {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y * y = x := ⟨λ h, by rw [← h, mul_self_sqrt hx], λ h, by rw [← h, sqrt_mul_self hy]⟩ @[simp] theorem sqr_sqrt {x : ℝ} (h : 0 ≤ x) : sqrt x ^ 2 = x := by rw [pow_two, mul_self_sqrt h] @[simp] theorem sqrt_sqr {x : ℝ} (h : 0 ≤ x) : sqrt (x ^ 2) = x := by rw [pow_two, sqrt_mul_self h] theorem sqrt_eq_iff_sqr_eq {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y ^ 2 = x := by rw [pow_two, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = abs x := (le_total 0 x).elim (λ h, (sqrt_mul_self h).trans (abs_of_nonneg h).symm) (λ h, by rw [← neg_mul_neg, sqrt_mul_self (neg_nonneg.2 h), abs_of_nonpos h]) theorem sqrt_sqr_eq_abs (x : ℝ) : sqrt (x ^ 2) = abs x := by rw [pow_two, sqrt_mul_self_eq_abs] @[simp] theorem sqrt_zero : sqrt 0 = 0 := by simpa using sqrt_mul_self (le_refl _) @[simp] theorem sqrt_one : sqrt 1 = 1 := by simpa using sqrt_mul_self zero_le_one @[simp] theorem sqrt_le {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y := by rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _), mul_self_sqrt hx, mul_self_sqrt hy] @[simp] theorem sqrt_lt {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < sqrt y ↔ x < y := le_iff_le_iff_lt_iff_lt.1 (sqrt_le hy hx) @[simp] theorem sqrt_inj {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y := by simp [le_antisymm_iff, hx, hy] @[simp] theorem sqrt_eq_zero {x : ℝ} (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 := by simpa using sqrt_inj h (le_refl _) theorem sqrt_eq_zero' {x : ℝ} : sqrt x = 0 ↔ x ≤ 0 := (le_total x 0).elim (λ h, by simp [h, sqrt_eq_zero_of_nonpos]) (λ h, by simp [h]; simp [le_antisymm_iff, h]) @[simp] theorem sqrt_pos {x : ℝ} : 0 < sqrt x ↔ 0 < x := le_iff_le_iff_lt_iff_lt.1 (iff.trans (by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero') @[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y := begin cases le_total 0 x with hx hx, { refine (mul_self_inj_of_nonneg _ (mul_nonneg _ _)).1 _; try {apply sqrt_nonneg}, rw [mul_self_sqrt (mul_nonneg hx hy), mul_assoc, mul_left_comm (sqrt y), mul_self_sqrt hy, ← mul_assoc, mul_self_sqrt hx] }, { rw [sqrt_eq_zero'.2 (mul_nonpos_of_nonpos_of_nonneg hx hy), sqrt_eq_zero'.2 hx, zero_mul] } end @[simp] theorem sqrt_mul {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y := by rw [mul_comm, sqrt_mul' _ hx, mul_comm] @[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ := (le_or_lt x 0).elim (λ h, by simp [sqrt_eq_zero'.2, inv_nonpos, h]) (λ h, by rw [ ← mul_self_inj_of_nonneg (sqrt_nonneg _) (le_of_lt $ inv_pos $ sqrt_pos.2 h), mul_self_sqrt (le_of_lt $ inv_pos h), ← mul_inv', mul_self_sqrt (le_of_lt h)]) @[simp] theorem sqrt_div {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y := by rw [division_def, sqrt_mul hx, sqrt_inv]; refl end real
98b2b147ce205227c72d23b09614ae083acc83f9
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/algebra/group_set_bigops.lean
5e233f4548ac29545e14b176cff7bf35c59940ca
[ "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
3,945
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Set-based version of group_bigops. -/ import .group_bigops data.set.finite open set classical namespace algebra namespace set variables {A B : Type} /- Prod: product indexed by a set -/ section Prod variable [cmB : comm_monoid B] include cmB noncomputable definition Prod (s : set A) (f : A → B) : B := algebra.finset.Prod (to_finset s) f -- ∏ x ∈ s, f x notation `∏` binders `∈` s, r:(scoped f, prod s f) := r theorem Prod_empty (f : A → B) : Prod ∅ f = 1 := by rewrite [↑Prod, to_finset_empty] theorem Prod_of_not_finite {s : set A} (nfins : ¬ finite s) (f : A → B) : Prod s f = 1 := by rewrite [↑Prod, to_finset_of_not_finite nfins] theorem Prod_mul (s : set A) (f g : A → B) : Prod s (λx, f x * g x) = Prod s f * Prod s g := by rewrite [↑Prod, finset.Prod_mul] theorem Prod_insert_of_mem (f : A → B) {a : A} {s : set A} (H : a ∈ s) : Prod (insert a s) f = Prod s f := by_cases (suppose finite s, assert (#finset a ∈ set.to_finset s), by rewrite mem_to_finset_eq; apply H, by rewrite [↑Prod, to_finset_insert, finset.Prod_insert_of_mem f this]) (assume nfs : ¬ finite s, assert ¬ finite (insert a s), from assume H, nfs (finite_of_finite_insert H), by rewrite [Prod_of_not_finite nfs, Prod_of_not_finite this]) theorem Prod_insert_of_not_mem (f : A → B) {a : A} {s : set A} [fins : finite s] (H : a ∉ s) : Prod (insert a s) f = f a * Prod s f := assert (#finset a ∉ set.to_finset s), by rewrite mem_to_finset_eq; apply H, by rewrite [↑Prod, to_finset_insert, finset.Prod_insert_of_not_mem f this] theorem Prod_union (f : A → B) {s₁ s₂ : set A} [fins₁ : finite s₁] [fins₂ : finite s₂] (disj : s₁ ∩ s₂ = ∅) : Prod (s₁ ∪ s₂) f = Prod s₁ f * Prod s₂ f := begin rewrite [↑Prod, to_finset_union], apply finset.Prod_union, apply finset.eq_of_to_set_eq_to_set, rewrite [finset.to_set_inter, *to_set_to_finset, finset.to_set_empty, disj] end theorem Prod_ext {s : set A} {f g : A → B} (H : ∀{x}, x ∈ s → f x = g x) : Prod s f = Prod s g := by_cases (suppose finite s, by esimp [Prod]; apply finset.Prod_ext; intro x; rewrite [mem_to_finset_eq]; apply H) (assume nfs : ¬ finite s, by rewrite [*Prod_of_not_finite nfs]) theorem Prod_one (s : set A) : Prod s (λ x, 1) = (1:B) := by rewrite [↑Prod, finset.Prod_one] end Prod /- Sum -/ section Sum variable [acmB : add_comm_monoid B] include acmB local attribute add_comm_monoid.to_comm_monoid [trans-instance] noncomputable definition Sum (s : set A) (f : A → B) : B := Prod s f -- ∑ x ∈ s, f x notation `∑` binders `∈` s, r:(scoped f, Sum s f) := r theorem Sum_empty (f : A → B) : Sum ∅ f = 0 := Prod_empty f theorem Sum_of_not_finite {s : set A} (nfins : ¬ finite s) (f : A → B) : Sum s f = 0 := Prod_of_not_finite nfins f theorem Sum_add (s : set A) (f g : A → B) : Sum s (λx, f x + g x) = Sum s f + Sum s g := Prod_mul s f g theorem Sum_insert_of_mem (f : A → B) {a : A} {s : set A} (H : a ∈ s) : Sum (insert a s) f = Sum s f := Prod_insert_of_mem f H theorem Sum_insert_of_not_mem (f : A → B) {a : A} {s : set A} [fins : finite s] (H : a ∉ s) : Sum (insert a s) f = f a + Sum s f := Prod_insert_of_not_mem f H theorem Sum_union (f : A → B) {s₁ s₂ : set A} [fins₁ : finite s₁] [fins₂ : finite s₂] (disj : s₁ ∩ s₂ = ∅) : Sum (s₁ ∪ s₂) f = Sum s₁ f + Sum s₂ f := Prod_union f disj theorem Sum_ext {s : set A} {f g : A → B} (H : ∀x, x ∈ s → f x = g x) : Sum s f = Sum s g := Prod_ext H theorem Sum_zero (s : set A) : Sum s (λ x, 0) = (0:B) := Prod_one s end Sum end set end algebra
3b0d4972d38fc5fb927be22d7deadd993b42130d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/matrix/kronecker.lean
761a437a6995904492776a3b8593c271425fbc62
[ "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
23,399
lean
/- Copyright (c) 2021 Filippo A. E. Nuccio. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Filippo A. E. Nuccio, Eric Wieser -/ import data.matrix.basic import data.matrix.block import linear_algebra.matrix.determinant import linear_algebra.matrix.nonsingular_inverse import linear_algebra.tensor_product import ring_theory.tensor_product /-! # Kronecker product of matrices > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This defines the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product). ## Main definitions * `matrix.kronecker_map`: A generalization of the Kronecker product: given a map `f : α → β → γ` and matrices `A` and `B` with coefficients in `α` and `β`, respectively, it is defined as the matrix with coefficients in `γ` such that `kronecker_map f A B (i₁, i₂) (j₁, j₂) = f (A i₁ j₁) (B i₁ j₂)`. * `matrix.kronecker_map_bilinear`: when `f` is bilinear, so is `kronecker_map f`. ## Specializations * `matrix.kronecker`: An alias of `kronecker_map (*)`. Prefer using the notation. * `matrix.kronecker_bilinear`: `matrix.kronecker` is bilinear * `matrix.kronecker_tmul`: An alias of `kronecker_map (⊗ₜ)`. Prefer using the notation. * `matrix.kronecker_tmul_bilinear`: `matrix.tmul_kronecker` is bilinear ## Notations These require `open_locale kronecker`: * `A ⊗ₖ B` for `kronecker_map (*) A B`. Lemmas about this notation use the token `kronecker`. * `A ⊗ₖₜ B` and `A ⊗ₖₜ[R] B` for `kronecker_map (⊗ₜ) A B`. Lemmas about this notation use the token `kronecker_tmul`. -/ namespace matrix open_locale matrix variables {R α α' β β' γ γ' : Type*} variables {l m n p : Type*} {q r : Type*} {l' m' n' p' : Type*} section kronecker_map /-- Produce a matrix with `f` applied to every pair of elements from `A` and `B`. -/ def kronecker_map (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) : matrix (l × n) (m × p) γ := of $ λ (i : l × n) (j : m × p), f (A i.1 j.1) (B i.2 j.2) -- TODO: set as an equation lemma for `kronecker_map`, see mathlib4#3024 @[simp] lemma kronecker_map_apply (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) (i j) : kronecker_map f A B i j = f (A i.1 j.1) (B i.2 j.2) := rfl lemma kronecker_map_transpose (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) : kronecker_map f Aᵀ Bᵀ = (kronecker_map f A B)ᵀ := ext $ λ i j, rfl lemma kronecker_map_map_left (f : α' → β → γ) (g : α → α') (A : matrix l m α) (B : matrix n p β) : kronecker_map f (A.map g) B = kronecker_map (λ a b, f (g a) b) A B := ext $ λ i j, rfl lemma kronecker_map_map_right (f : α → β' → γ) (g : β → β') (A : matrix l m α) (B : matrix n p β) : kronecker_map f A (B.map g) = kronecker_map (λ a b, f a (g b)) A B := ext $ λ i j, rfl lemma kronecker_map_map (f : α → β → γ) (g : γ → γ') (A : matrix l m α) (B : matrix n p β) : (kronecker_map f A B).map g = kronecker_map (λ a b, g (f a b)) A B := ext $ λ i j, rfl @[simp] lemma kronecker_map_zero_left [has_zero α] [has_zero γ] (f : α → β → γ) (hf : ∀ b, f 0 b = 0) (B : matrix n p β) : kronecker_map f (0 : matrix l m α) B = 0:= ext $ λ i j,hf _ @[simp] lemma kronecker_map_zero_right [has_zero β] [has_zero γ] (f : α → β → γ) (hf : ∀ a, f a 0 = 0) (A : matrix l m α) : kronecker_map f A (0 : matrix n p β) = 0 := ext $ λ i j, hf _ lemma kronecker_map_add_left [has_add α] [has_add γ] (f : α → β → γ) (hf : ∀ a₁ a₂ b, f (a₁ + a₂) b = f a₁ b + f a₂ b) (A₁ A₂ : matrix l m α) (B : matrix n p β) : kronecker_map f (A₁ + A₂) B = kronecker_map f A₁ B + kronecker_map f A₂ B := ext $ λ i j, hf _ _ _ lemma kronecker_map_add_right [has_add β] [has_add γ] (f : α → β → γ) (hf : ∀ a b₁ b₂, f a (b₁ + b₂) = f a b₁ + f a b₂) (A : matrix l m α) (B₁ B₂ : matrix n p β) : kronecker_map f A (B₁ + B₂) = kronecker_map f A B₁ + kronecker_map f A B₂ := ext $ λ i j, hf _ _ _ lemma kronecker_map_smul_left [has_smul R α] [has_smul R γ] (f : α → β → γ) (r : R) (hf : ∀ a b, f (r • a) b = r • f a b) (A : matrix l m α) (B : matrix n p β) : kronecker_map f (r • A) B = r • kronecker_map f A B := ext $ λ i j, hf _ _ lemma kronecker_map_smul_right [has_smul R β] [has_smul R γ] (f : α → β → γ) (r : R) (hf : ∀ a b, f a (r • b) = r • f a b) (A : matrix l m α) (B : matrix n p β) : kronecker_map f A (r • B) = r • kronecker_map f A B := ext $ λ i j, hf _ _ lemma kronecker_map_diagonal_diagonal [has_zero α] [has_zero β] [has_zero γ] [decidable_eq m] [decidable_eq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (a : m → α) (b : n → β): kronecker_map f (diagonal a) (diagonal b) = diagonal (λ mn, f (a mn.1) (b mn.2)) := begin ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩, simp [diagonal, apply_ite f, ite_and, ite_apply, apply_ite (f (a i₁)), hf₁, hf₂], end lemma kronecker_map_diagonal_right [has_zero β] [has_zero γ] [decidable_eq n] (f : α → β → γ) (hf : ∀ a, f a 0 = 0) (A : matrix l m α) (b : n → β): kronecker_map f A (diagonal b) = block_diagonal (λ i, A.map (λ a, f a (b i))) := begin ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩, simp [diagonal, block_diagonal, apply_ite (f (A i₁ j₁)), hf], end lemma kronecker_map_diagonal_left [has_zero α] [has_zero γ] [decidable_eq l] (f : α → β → γ) (hf : ∀ b, f 0 b = 0) (a : l → α) (B : matrix m n β) : kronecker_map f (diagonal a) B = matrix.reindex (equiv.prod_comm _ _) (equiv.prod_comm _ _) (block_diagonal (λ i, B.map (λ b, f (a i) b))) := begin ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩, simp [diagonal, block_diagonal, apply_ite f, ite_apply, hf], end @[simp] lemma kronecker_map_one_one [has_zero α] [has_zero β] [has_zero γ] [has_one α] [has_one β] [has_one γ] [decidable_eq m] [decidable_eq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (hf₃ : f 1 1 = 1) : kronecker_map f (1 : matrix m m α) (1 : matrix n n β) = 1 := (kronecker_map_diagonal_diagonal _ hf₁ hf₂ _ _).trans $ by simp only [hf₃, diagonal_one] lemma kronecker_map_reindex (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (en : n ≃ n') (ep : p ≃ p') (M : matrix l m α) (N : matrix n p β) : kronecker_map f (reindex el em M) (reindex en ep N) = reindex (el.prod_congr en) (em.prod_congr ep) (kronecker_map f M N) := by { ext ⟨i, i'⟩ ⟨j, j'⟩, refl } lemma kronecker_map_reindex_left (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (M : matrix l m α) (N : matrix n n' β) : kronecker_map f (matrix.reindex el em M) N = reindex (el.prod_congr (equiv.refl _)) (em.prod_congr (equiv.refl _)) (kronecker_map f M N) := kronecker_map_reindex _ _ _ (equiv.refl _) (equiv.refl _) _ _ lemma kronecker_map_reindex_right (f : α → β → γ) (em : m ≃ m') (en : n ≃ n') (M : matrix l l' α) (N : matrix m n β) : kronecker_map f M (reindex em en N) = reindex ((equiv.refl _).prod_congr em) ((equiv.refl _).prod_congr en) (kronecker_map f M N) := kronecker_map_reindex _ (equiv.refl _) (equiv.refl _) _ _ _ _ lemma kronecker_map_assoc {δ ξ ω ω' : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω') (g' : β → δ → ξ) (A : matrix l m α) (B : matrix n p β) (D : matrix q r δ) (φ : ω ≃ ω') (hφ : ∀ a b d, φ (g (f a b) d) = f' a (g' b d)) : (reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r)).trans (equiv.map_matrix φ) (kronecker_map g (kronecker_map f A B) D) = kronecker_map f' A (kronecker_map g' B D) := ext $ λ i j, hφ _ _ _ lemma kronecker_map_assoc₁ {δ ξ ω : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω) (g' : β → δ → ξ) (A : matrix l m α) (B : matrix n p β) (D : matrix q r δ) (h : ∀ a b d, (g (f a b) d) = f' a (g' b d)) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) (kronecker_map g (kronecker_map f A B) D) = kronecker_map f' A (kronecker_map g' B D) := ext $ λ i j, h _ _ _ /-- When `f` is bilinear then `matrix.kronecker_map f` is also bilinear. -/ @[simps] def kronecker_map_bilinear [comm_semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) : matrix l m α →ₗ[R] matrix n p β →ₗ[R] matrix (l × n) (m × p) γ := linear_map.mk₂ R (kronecker_map (λ r s, f r s)) (kronecker_map_add_left _ $ f.map_add₂) (λ r, kronecker_map_smul_left _ _ $ f.map_smul₂ _) (kronecker_map_add_right _ $ λ a, (f a).map_add) (λ r, kronecker_map_smul_right _ _ $ λ a, (f a).map_smul r) /-- `matrix.kronecker_map_bilinear` commutes with `⬝` if `f` commutes with `*`. This is primarily used with `R = ℕ` to prove `matrix.mul_kronecker_mul`. -/ lemma kronecker_map_bilinear_mul_mul [comm_semiring R] [fintype m] [fintype m'] [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] [non_unital_non_assoc_semiring γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) (h_comm : ∀ a b a' b', f (a * b) (a' * b') = f a a' * f b b') (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' β) (B' : matrix m' n' β) : kronecker_map_bilinear f (A ⬝ B) (A' ⬝ B') = (kronecker_map_bilinear f A A') ⬝ (kronecker_map_bilinear f B B') := begin ext ⟨i, i'⟩ ⟨j, j'⟩, simp only [kronecker_map_bilinear_apply_apply, mul_apply, ← finset.univ_product_univ, finset.sum_product, kronecker_map_apply], simp_rw [f.map_sum, linear_map.sum_apply, linear_map.map_sum, h_comm], end /-- `trace` distributes over `matrix.kronecker_map_bilinear`. This is primarily used with `R = ℕ` to prove `matrix.trace_kronecker`. -/ lemma trace_kronecker_map_bilinear [comm_semiring R] [fintype m] [fintype n] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) (A : matrix m m α) (B : matrix n n β) : trace (kronecker_map_bilinear f A B) = f (trace A) (trace B) := by simp_rw [matrix.trace, matrix.diag, kronecker_map_bilinear_apply_apply, linear_map.map_sum₂, map_sum, ←finset.univ_product_univ, finset.sum_product, kronecker_map_apply] /-- `determinant` of `matrix.kronecker_map_bilinear`. This is primarily used with `R = ℕ` to prove `matrix.det_kronecker`. -/ lemma det_kronecker_map_bilinear [comm_semiring R] [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] [comm_ring α] [comm_ring β] [comm_ring γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) (h_comm : ∀ a b a' b', f (a * b) (a' * b') = f a a' * f b b') (A : matrix m m α) (B : matrix n n β) : det (kronecker_map_bilinear f A B) = det (A.map (λ a, f a 1)) ^ fintype.card n * det (B.map (λ b, f 1 b)) ^ fintype.card m := calc det (kronecker_map_bilinear f A B) = det (kronecker_map_bilinear f A 1 ⬝ kronecker_map_bilinear f 1 B) : by rw [←kronecker_map_bilinear_mul_mul f h_comm, matrix.mul_one, matrix.one_mul] ... = det (block_diagonal (λ _, A.map (λ a, f a 1))) * det (block_diagonal (λ _, B.map (λ b, f 1 b))) : begin rw [det_mul, ←diagonal_one, ←diagonal_one, kronecker_map_bilinear_apply_apply, kronecker_map_diagonal_right _ (λ _, _), kronecker_map_bilinear_apply_apply, kronecker_map_diagonal_left _ (λ _, _), det_reindex_self], { exact linear_map.map_zero₂ _ _ }, { exact map_zero _ }, end ... = _ : by simp_rw [det_block_diagonal, finset.prod_const, finset.card_univ] end kronecker_map /-! ### Specialization to `matrix.kronecker_map (*)` -/ section kronecker open_locale matrix /-- The Kronecker product. This is just a shorthand for `kronecker_map (*)`. Prefer the notation `⊗ₖ` rather than this definition. -/ @[simp] def kronecker [has_mul α] : matrix l m α → matrix n p α → matrix (l × n) (m × p) α := kronecker_map (*) localized "infix (name := matrix.kronecker_map.mul) ` ⊗ₖ `:100 := matrix.kronecker_map (*)" in kronecker @[simp] lemma kronecker_apply [has_mul α] (A : matrix l m α) (B : matrix n p α) (i₁ i₂ j₁ j₂) : (A ⊗ₖ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ * B i₂ j₂ := rfl /-- `matrix.kronecker` as a bilinear map. -/ def kronecker_bilinear [comm_semiring R] [semiring α] [algebra R α] : matrix l m α →ₗ[R] matrix n p α →ₗ[R] matrix (l × n) (m × p) α := kronecker_map_bilinear (algebra.lmul R α) /-! What follows is a copy, in order, of every `matrix.kronecker_map` lemma above that has hypotheses which can be filled by properties of `*`. -/ @[simp] lemma zero_kronecker [mul_zero_class α] (B : matrix n p α) : (0 : matrix l m α) ⊗ₖ B = 0 := kronecker_map_zero_left _ zero_mul B @[simp] lemma kronecker_zero [mul_zero_class α] (A : matrix l m α) : A ⊗ₖ (0 : matrix n p α) = 0 := kronecker_map_zero_right _ mul_zero A lemma add_kronecker [distrib α] (A₁ A₂ : matrix l m α) (B : matrix n p α) : (A₁ + A₂) ⊗ₖ B = A₁ ⊗ₖ B + A₂ ⊗ₖ B := kronecker_map_add_left _ add_mul _ _ _ lemma kronecker_add [distrib α] (A : matrix l m α) (B₁ B₂ : matrix n p α) : A ⊗ₖ (B₁ + B₂) = A ⊗ₖ B₁ + A ⊗ₖ B₂ := kronecker_map_add_right _ mul_add _ _ _ lemma smul_kronecker [monoid R] [monoid α] [mul_action R α] [is_scalar_tower R α α] (r : R) (A : matrix l m α) (B : matrix n p α) : (r • A) ⊗ₖ B = r • (A ⊗ₖ B) := kronecker_map_smul_left _ _ (λ _ _, smul_mul_assoc _ _ _) _ _ lemma kronecker_smul [monoid R] [monoid α] [mul_action R α] [smul_comm_class R α α] (r : R) (A : matrix l m α) (B : matrix n p α) : A ⊗ₖ (r • B) = r • (A ⊗ₖ B) := kronecker_map_smul_right _ _ (λ _ _, mul_smul_comm _ _ _) _ _ lemma diagonal_kronecker_diagonal [mul_zero_class α] [decidable_eq m] [decidable_eq n] (a : m → α) (b : n → α): (diagonal a) ⊗ₖ (diagonal b) = diagonal (λ mn, (a mn.1) * (b mn.2)) := kronecker_map_diagonal_diagonal _ zero_mul mul_zero _ _ lemma kronecker_diagonal [mul_zero_class α] [decidable_eq n] (A : matrix l m α) (b : n → α): A ⊗ₖ diagonal b = block_diagonal (λ i, mul_opposite.op (b i) • A) := kronecker_map_diagonal_right _ mul_zero _ _ lemma diagonal_kronecker [mul_zero_class α] [decidable_eq l](a : l → α) (B : matrix m n α) : diagonal a ⊗ₖ B = matrix.reindex (equiv.prod_comm _ _) (equiv.prod_comm _ _) (block_diagonal (λ i, a i • B)) := kronecker_map_diagonal_left _ zero_mul _ _ @[simp] lemma one_kronecker_one [mul_zero_one_class α] [decidable_eq m] [decidable_eq n] : (1 : matrix m m α) ⊗ₖ (1 : matrix n n α) = 1 := kronecker_map_one_one _ zero_mul mul_zero (one_mul _) lemma kronecker_one [mul_zero_one_class α] [decidable_eq n] (A : matrix l m α) : A ⊗ₖ (1 : matrix n n α) = block_diagonal (λ i, A) := (kronecker_diagonal _ _).trans $ congr_arg _ $ funext $ λ _, matrix.ext $ λ _ _, mul_one _ lemma one_kronecker [mul_zero_one_class α] [decidable_eq l] (B : matrix m n α) : (1 : matrix l l α) ⊗ₖ B = matrix.reindex (equiv.prod_comm _ _) (equiv.prod_comm _ _) (block_diagonal (λ i, B)) := (diagonal_kronecker _ _).trans $ congr_arg _ $ congr_arg _ $ funext $ λ _, matrix.ext $ λ _ _, one_mul _ lemma mul_kronecker_mul [fintype m] [fintype m'] [comm_semiring α] (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' α) (B' : matrix m' n' α) : (A ⬝ B) ⊗ₖ (A' ⬝ B') = (A ⊗ₖ A') ⬝ (B ⊗ₖ B') := kronecker_map_bilinear_mul_mul (algebra.lmul ℕ α).to_linear_map mul_mul_mul_comm A B A' B' @[simp] lemma kronecker_assoc [semigroup α] (A : matrix l m α) (B : matrix n p α) (C : matrix q r α) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) ((A ⊗ₖ B) ⊗ₖ C) = A ⊗ₖ (B ⊗ₖ C) := kronecker_map_assoc₁ _ _ _ _ A B C mul_assoc lemma trace_kronecker [fintype m] [fintype n] [semiring α] (A : matrix m m α) (B : matrix n n α) : trace (A ⊗ₖ B) = trace A * trace B := trace_kronecker_map_bilinear (algebra.lmul ℕ α).to_linear_map _ _ lemma det_kronecker [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] [comm_ring R] (A : matrix m m R) (B : matrix n n R) : det (A ⊗ₖ B) = det A ^ fintype.card n * det B ^ fintype.card m := begin refine (det_kronecker_map_bilinear (algebra.lmul ℕ R).to_linear_map mul_mul_mul_comm _ _).trans _, congr' 3, { ext i j, exact mul_one _}, { ext i j, exact one_mul _}, end lemma inv_kronecker [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] [comm_ring R] (A : matrix m m R) (B : matrix n n R) : (A ⊗ₖ B)⁻¹ = A⁻¹ ⊗ₖ B⁻¹ := begin -- handle the special cases where either matrix is not invertible by_cases hA : is_unit A.det, swap, { casesI is_empty_or_nonempty n, { exact subsingleton.elim _ _ }, have hAB : ¬is_unit (A ⊗ₖ B).det, { refine mt (λ hAB, _) hA, rw det_kronecker at hAB, exact (is_unit_pow_iff fintype.card_ne_zero).mp (is_unit_of_mul_is_unit_left hAB) }, rw [nonsing_inv_apply_not_is_unit _ hA, zero_kronecker, nonsing_inv_apply_not_is_unit _ hAB] }, by_cases hB : is_unit B.det, swap, { casesI is_empty_or_nonempty m, { exact subsingleton.elim _ _ }, have hAB : ¬is_unit (A ⊗ₖ B).det, { refine mt (λ hAB, _) hB, rw det_kronecker at hAB, exact (is_unit_pow_iff fintype.card_ne_zero).mp (is_unit_of_mul_is_unit_right hAB) }, rw [nonsing_inv_apply_not_is_unit _ hB, kronecker_zero, nonsing_inv_apply_not_is_unit _ hAB] }, -- otherwise follows trivially from `mul_kronecker_mul` { apply inv_eq_right_inv, rw [←mul_kronecker_mul, ←one_kronecker_one, mul_nonsing_inv _ hA, mul_nonsing_inv _ hB] }, end end kronecker /-! ### Specialization to `matrix.kronecker_map (⊗ₜ)` -/ section kronecker_tmul variables (R) open tensor_product open_locale matrix tensor_product section module variables [comm_semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] variables [module R α] [module R β] [module R γ] /-- The Kronecker tensor product. This is just a shorthand for `kronecker_map (⊗ₜ)`. Prefer the notation `⊗ₖₜ` rather than this definition. -/ @[simp] def kronecker_tmul : matrix l m α → matrix n p β → matrix (l × n) (m × p) (α ⊗[R] β) := kronecker_map (⊗ₜ) localized "infix (name := matrix.kronecker_map.tmul) ` ⊗ₖₜ `:100 := matrix.kronecker_map (⊗ₜ)" in kronecker localized "notation (name := matrix.kronecker_map.tmul') x ` ⊗ₖₜ[`:100 R `] `:0 y:100 := matrix.kronecker_map (tensor_product.tmul R) x y" in kronecker @[simp] lemma kronecker_tmul_apply (A : matrix l m α) (B : matrix n p β) (i₁ i₂ j₁ j₂) : (A ⊗ₖₜ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ ⊗ₜ[R] B i₂ j₂ := rfl /-- `matrix.kronecker` as a bilinear map. -/ def kronecker_tmul_bilinear : matrix l m α →ₗ[R] matrix n p β →ₗ[R] matrix (l × n) (m × p) (α ⊗[R] β) := kronecker_map_bilinear (tensor_product.mk R α β) /-! What follows is a copy, in order, of every `matrix.kronecker_map` lemma above that has hypotheses which can be filled by properties of `⊗ₜ`. -/ @[simp] lemma zero_kronecker_tmul (B : matrix n p β) : (0 : matrix l m α) ⊗ₖₜ[R] B = 0 := kronecker_map_zero_left _ (zero_tmul α) B @[simp] lemma kronecker_tmul_zero (A : matrix l m α) : A ⊗ₖₜ[R] (0 : matrix n p β) = 0 := kronecker_map_zero_right _ (tmul_zero β) A lemma add_kronecker_tmul (A₁ A₂ : matrix l m α) (B : matrix n p α) : (A₁ + A₂) ⊗ₖₜ[R] B = A₁ ⊗ₖₜ B + A₂ ⊗ₖₜ B := kronecker_map_add_left _ add_tmul _ _ _ lemma kronecker_tmul_add (A : matrix l m α) (B₁ B₂ : matrix n p α) : A ⊗ₖₜ[R] (B₁ + B₂) = A ⊗ₖₜ B₁ + A ⊗ₖₜ B₂ := kronecker_map_add_right _ tmul_add _ _ _ lemma smul_kronecker_tmul (r : R) (A : matrix l m α) (B : matrix n p α) : (r • A) ⊗ₖₜ[R] B = r • (A ⊗ₖₜ B) := kronecker_map_smul_left _ _ (λ _ _, smul_tmul' _ _ _) _ _ lemma kronecker_tmul_smul (r : R) (A : matrix l m α) (B : matrix n p α) : A ⊗ₖₜ[R] (r • B) = r • (A ⊗ₖₜ B) := kronecker_map_smul_right _ _ (λ _ _, tmul_smul _ _ _) _ _ lemma diagonal_kronecker_tmul_diagonal [decidable_eq m] [decidable_eq n] (a : m → α) (b : n → α): (diagonal a) ⊗ₖₜ[R] (diagonal b) = diagonal (λ mn, a mn.1 ⊗ₜ b mn.2) := kronecker_map_diagonal_diagonal _ (zero_tmul _) (tmul_zero _) _ _ lemma kronecker_tmul_diagonal [decidable_eq n] (A : matrix l m α) (b : n → α): A ⊗ₖₜ[R] (diagonal b) = block_diagonal (λ i, A.map (λ a, a ⊗ₜ[R] b i)) := kronecker_map_diagonal_right _ (tmul_zero _) _ _ lemma diagonal_kronecker_tmul [decidable_eq l](a : l → α) (B : matrix m n α) : diagonal a ⊗ₖₜ[R] B = matrix.reindex (equiv.prod_comm _ _) (equiv.prod_comm _ _) (block_diagonal (λ i, B.map (λ b, a i ⊗ₜ[R] b))) := kronecker_map_diagonal_left _ (zero_tmul _) _ _ @[simp] lemma kronecker_tmul_assoc (A : matrix l m α) (B : matrix n p β) (C : matrix q r γ) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) (((A ⊗ₖₜ[R] B) ⊗ₖₜ[R] C).map (tensor_product.assoc _ _ _ _)) = A ⊗ₖₜ[R] (B ⊗ₖₜ[R] C) := ext $ λ i j, assoc_tmul _ _ _ lemma trace_kronecker_tmul [fintype m] [fintype n] (A : matrix m m α) (B : matrix n n β) : trace (A ⊗ₖₜ[R] B) = trace A ⊗ₜ[R] trace B := trace_kronecker_map_bilinear (tensor_product.mk R α β) _ _ end module section algebra open_locale kronecker open algebra.tensor_product section semiring variables [comm_semiring R] [semiring α] [semiring β] [algebra R α] [algebra R β] @[simp] lemma one_kronecker_tmul_one [decidable_eq m] [decidable_eq n] : (1 : matrix m m α) ⊗ₖₜ[R] (1 : matrix n n α) = 1 := kronecker_map_one_one _ (zero_tmul _) (tmul_zero _) rfl lemma mul_kronecker_tmul_mul [fintype m] [fintype m'] (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' β) (B' : matrix m' n' β) : (A ⬝ B) ⊗ₖₜ[R] (A' ⬝ B') = (A ⊗ₖₜ A') ⬝ (B ⊗ₖₜ B') := kronecker_map_bilinear_mul_mul (tensor_product.mk R α β) tmul_mul_tmul A B A' B' end semiring section comm_ring variables [comm_ring R] [comm_ring α] [comm_ring β] [algebra R α] [algebra R β] lemma det_kronecker_tmul [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] (A : matrix m m α) (B : matrix n n β) : det (A ⊗ₖₜ[R] B) = (det A ^ fintype.card n) ⊗ₜ[R] (det B ^ fintype.card m) := begin refine (det_kronecker_map_bilinear (tensor_product.mk R α β) tmul_mul_tmul _ _).trans _, simp only [mk_apply, ←include_left_apply, ←include_right_apply] {eta := ff}, simp only [←alg_hom.map_matrix_apply, ←alg_hom.map_det], simp only [include_left_apply, include_right_apply, tmul_pow, tmul_mul_tmul, one_pow, _root_.mul_one, _root_.one_mul], end end comm_ring end algebra -- insert lemmas specific to `kronecker_tmul` below this line end kronecker_tmul end matrix
4f9b5f333ce975ccb97f2a4232593b25ed824441
367134ba5a65885e863bdc4507601606690974c1
/src/field_theory/galois.lean
db5f7fde7ea0516b48ba7d34f24312986d01138a
[ "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
18,750
lean
/- Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning and Patrick Lutz -/ import field_theory.normal import field_theory.primitive_element import field_theory.fixed import ring_theory.power_basis /-! # Galois Extensions In this file we define Galois extensions as extensions which are both separable and normal. ## Main definitions - `is_galois F E` where `E` is an extension of `F` - `fixed_field H` where `H : subgroup (E ≃ₐ[F] E)` - `fixing_subgroup K` where `K : intermediate_field F E` - `galois_correspondence` where `E/F` is finite dimensional and Galois ## Main results - `fixing_subgroup_of_fixed_field` : If `E/F` is finite dimensional (but not necessarily Galois) then `fixing_subgroup (fixed_field H) = H` - `fixed_field_of_fixing_subgroup`: If `E/F` is finite dimensional and Galois then `fixed_field (fixing_subgroup K) = K` Together, these two result prove the Galois correspondence - `is_galois.tfae` : Equivalent characterizations of a Galois extension of finite degree -/ noncomputable theory open_locale classical open finite_dimensional alg_equiv section variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] /-- A field extension E/F is galois if it is both separable and normal -/ class is_galois : Prop := (separable' : is_separable F E) (normal' : normal F E) variables {F E} theorem is_galois_iff : is_galois F E ↔ is_separable F E ∧ normal F E := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ protected theorem is_galois.is_separable (h : is_galois F E) : is_separable F E := h.1 protected theorem is_galois.normal (h : is_galois F E) : normal F E := h.2 @[priority 100] -- see Note [lower instance priority] instance is_galois.normal'' [h : is_galois F E] : normal F E := h.2 variables (F E) namespace is_galois instance self : is_galois F F := ⟨is_separable_self F, normal_self F⟩ @[priority 100] -- see Note [lower instance priority] instance to_is_separable [h : is_galois F E] : is_separable F E := h.1 @[priority 100] -- see Note [lower instance priority] instance to_normal [h : is_galois F E] : normal F E := h.2 variables (F) {E} lemma integral [is_galois F E] (x : E) : is_integral F x := normal.is_integral' x lemma separable [h : is_galois F E] (x : E) : (minpoly F x).separable := h.is_separable.separable x lemma splits [is_galois F E] (x : E) : (minpoly F x).splits (algebra_map F E) := normal.splits' x variables (F E) instance of_fixed_field (G : Type*) [group G] [fintype G] [mul_semiring_action G E] : is_galois (mul_action.fixed_points G E) E := ⟨fixed_points.separable G E, fixed_points.normal G E⟩ lemma intermediate_field.adjoin_simple.card_aut_eq_findim [finite_dimensional F E] {α : E} (hα : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F F⟮α⟯)) : fintype.card (F⟮α⟯ ≃ₐ[F] F⟮α⟯) = findim F F⟮α⟯ := begin letI : fintype (F⟮α⟯ →ₐ[F] F⟮α⟯) := intermediate_field.fintype_of_alg_hom_adjoin_integral F hα, rw intermediate_field.adjoin.findim hα, rw ← intermediate_field.card_alg_hom_adjoin_integral F hα h_sep h_splits, exact fintype.card_congr (alg_equiv_equiv_alg_hom F F⟮α⟯) end lemma card_aut_eq_findim [finite_dimensional F E] [h : is_galois F E] : fintype.card (E ≃ₐ[F] E) = findim F E := begin cases field.exists_primitive_element h.1 with α hα, let iso : F⟮α⟯ ≃ₐ[F] E := { to_fun := λ e, e.val, inv_fun := λ e, ⟨e, by { rw hα, exact intermediate_field.mem_top }⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, rfl, map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, commutes' := λ _, rfl }, have H : is_integral F α := is_galois.integral F α, have h_sep : (minpoly F α).separable := is_galois.separable F α, have h_splits : (minpoly F α).splits (algebra_map F E) := is_galois.splits F α, replace h_splits : polynomial.splits (algebra_map F F⟮α⟯) (minpoly F α), { convert polynomial.splits_comp_of_splits (algebra_map F E) iso.symm.to_alg_hom.to_ring_hom h_splits }, rw ← linear_equiv.findim_eq iso.to_linear_equiv, rw ← intermediate_field.adjoin_simple.card_aut_eq_findim F E H h_sep h_splits, apply fintype.card_congr, apply equiv.mk (λ ϕ, iso.trans (trans ϕ iso.symm)) (λ ϕ, iso.symm.trans (trans ϕ iso)), { intro ϕ, ext1, simp only [trans_apply, apply_symm_apply] }, { intro ϕ, ext1, simp only [trans_apply, symm_apply_apply] }, end end is_galois end section is_galois_tower variables (F K E : Type*) [field F] [field K] [field E] {E' : Type*} [field E'] [algebra F E'] variables [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_galois.tower_top_of_is_galois [is_galois F E] : is_galois K E := ⟨is_separable_tower_top_of_is_separable F K E, normal.tower_top_of_normal F K E⟩ variables {F E} @[priority 100] -- see Note [lower instance priority] instance is_galois.tower_top_intermediate_field (K : intermediate_field F E) [h : is_galois F E] : is_galois K E := is_galois.tower_top_of_is_galois F K E lemma is_galois_iff_is_galois_bot : is_galois (⊥ : intermediate_field F E) E ↔ is_galois F E := begin split, { introI h, exact is_galois.tower_top_of_is_galois (⊥ : intermediate_field F E) F E }, { introI h, apply_instance }, end lemma is_galois.of_alg_equiv [h : is_galois F E] (f : E ≃ₐ[F] E') : is_galois F E' := ⟨is_separable.of_alg_hom F E f.symm, normal.of_alg_equiv f⟩ lemma alg_equiv.transfer_galois (f : E ≃ₐ[F] E') : is_galois F E ↔ is_galois F E' := ⟨λ h, by exactI is_galois.of_alg_equiv f, λ h, by exactI is_galois.of_alg_equiv f.symm⟩ lemma is_galois_iff_is_galois_top : is_galois F (⊤ : intermediate_field F E) ↔ is_galois F E := (intermediate_field.top_equiv).transfer_galois instance is_galois_bot : is_galois F (⊥ : intermediate_field F E) := intermediate_field.bot_equiv.transfer_galois.mpr (is_galois.self F) end is_galois_tower section galois_correspondence variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] variables (H : subgroup (E ≃ₐ[F] E)) (K : intermediate_field F E) namespace intermediate_field instance subgroup_action : faithful_mul_semiring_action H E := { smul := λ h x, h x, smul_zero := λ _, map_zero _, smul_add := λ _, map_add _, one_smul := λ _, rfl, smul_one := λ _, map_one _, mul_smul := λ _ _ _, rfl, smul_mul := λ _, map_mul _, eq_of_smul_eq_smul' := λ x y z, subtype.ext (alg_equiv.ext z) } /-- The intermediate_field fixed by a subgroup -/ def fixed_field : intermediate_field F E := { carrier := mul_action.fixed_points H E, zero_mem' := λ g, smul_zero g, add_mem' := λ a b hx hy g, by rw [smul_add g a b, hx, hy], neg_mem' := λ a hx g, by rw [smul_neg g a, hx], one_mem' := λ g, smul_one g, mul_mem' := λ a b hx hy g, by rw [smul_mul' g a b, hx, hy], inv_mem' := λ a hx g, by rw [smul_inv _ g a, hx], algebra_map_mem' := λ a g, commutes g a } lemma findim_fixed_field_eq_card [finite_dimensional F E] : findim (fixed_field H) E = fintype.card H := fixed_points.findim_eq_card H E /-- The subgroup fixing an intermediate_field -/ def fixing_subgroup : subgroup (E ≃ₐ[F] E) := { carrier := λ ϕ, ∀ x : K, ϕ x = x, one_mem' := λ _, rfl, mul_mem' := λ _ _ hx hy _, (congr_arg _ (hy _)).trans (hx _), inv_mem' := λ _ hx _, (equiv.symm_apply_eq (to_equiv _)).mpr (hx _).symm } lemma le_iff_le : K ≤ fixed_field H ↔ H ≤ fixing_subgroup K := ⟨λ h g hg x, h (subtype.mem x) ⟨g, hg⟩, λ h x hx g, h (subtype.mem g) ⟨x, hx⟩⟩ /-- The fixing_subgroup of `K : intermediate_field F E` is isomorphic to `E ≃ₐ[K] E` -/ def fixing_subgroup_equiv : fixing_subgroup K ≃* (E ≃ₐ[K] E) := { to_fun := λ ϕ, of_bijective (alg_hom.mk ϕ (map_one ϕ) (map_mul ϕ) (map_zero ϕ) (map_add ϕ) (ϕ.mem)) (bijective ϕ), inv_fun := λ ϕ, ⟨of_bijective (alg_hom.mk ϕ (ϕ.map_one) (ϕ.map_mul) (ϕ.map_zero) (ϕ.map_add) (λ r, ϕ.commutes (algebra_map F K r))) (ϕ.bijective), ϕ.commutes⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl }, map_mul' := λ _ _, by { ext, refl } } theorem fixing_subgroup_fixed_field [finite_dimensional F E] : fixing_subgroup (fixed_field H) = H := begin have H_le : H ≤ (fixing_subgroup (fixed_field H)) := (le_iff_le _ _).mp (le_refl _), suffices : fintype.card H = fintype.card (fixing_subgroup (fixed_field H)), { exact subgroup.ext' (set.eq_of_inclusion_surjective ((fintype.bijective_iff_injective_and_card (set.inclusion H_le)).mpr ⟨set.inclusion_injective H_le, this⟩).2).symm }, apply fintype.card_congr, refine (fixed_points.to_alg_hom_equiv H E).trans _, refine (alg_equiv_equiv_alg_hom (fixed_field H) E).symm.trans _, exact (fixing_subgroup_equiv (fixed_field H)).to_equiv.symm end instance fixed_field.algebra : algebra K (fixed_field (fixing_subgroup K)) := { smul := λ x y, ⟨x*y, λ ϕ, by rw [smul_mul', (show ϕ • ↑x = ↑x, by exact subtype.mem ϕ x), (show ϕ • ↑y = ↑y, by exact subtype.mem y ϕ)]⟩, to_fun := λ x, ⟨x, λ ϕ, subtype.mem ϕ x⟩, map_zero' := rfl, map_add' := λ _ _, rfl, map_one' := rfl, map_mul' := λ _ _, rfl, commutes' := λ _ _, mul_comm _ _, smul_def' := λ _ _, rfl } instance fixed_field.is_scalar_tower : is_scalar_tower K (fixed_field (fixing_subgroup K)) E := ⟨λ _ _ _, mul_assoc _ _ _⟩ end intermediate_field namespace is_galois theorem fixed_field_fixing_subgroup [finite_dimensional F E] [h : is_galois F E] : intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) = K := begin have K_le : K ≤ intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) := (intermediate_field.le_iff_le _ _).mpr (le_refl _), suffices : findim K E = findim (intermediate_field.fixed_field (intermediate_field.fixing_subgroup K)) E, { exact (intermediate_field.eq_of_le_of_findim_eq' K_le this).symm }, rw [intermediate_field.findim_fixed_field_eq_card, fintype.card_congr (intermediate_field.fixing_subgroup_equiv K).to_equiv], exact (card_aut_eq_findim K E).symm, end lemma card_fixing_subgroup_eq_findim [finite_dimensional F E] [is_galois F E] : fintype.card (intermediate_field.fixing_subgroup K) = findim K E := by conv { to_rhs, rw [←fixed_field_fixing_subgroup K, intermediate_field.findim_fixed_field_eq_card] } /-- The Galois correspondence from intermediate fields to subgroups -/ def intermediate_field_equiv_subgroup [finite_dimensional F E] [is_galois F E] : intermediate_field F E ≃o order_dual (subgroup (E ≃ₐ[F] E)) := { to_fun := intermediate_field.fixing_subgroup, inv_fun := intermediate_field.fixed_field, left_inv := λ K, fixed_field_fixing_subgroup K, right_inv := λ H, intermediate_field.fixing_subgroup_fixed_field H, map_rel_iff' := λ K L, by { rw [←fixed_field_fixing_subgroup L, intermediate_field.le_iff_le, fixed_field_fixing_subgroup L, ←order_dual.dual_le], refl } } /-- The Galois correspondence as a galois_insertion -/ def galois_insertion_intermediate_field_subgroup [finite_dimensional F E] : galois_insertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ K _, intermediate_field.fixing_subgroup K, gc := λ K H, (intermediate_field.le_iff_le H K).symm, le_l_u := λ H, le_of_eq (intermediate_field.fixing_subgroup_fixed_field H).symm, choice_eq := λ K _, rfl } /-- The Galois correspondence as a galois_coinsertion -/ def galois_coinsertion_intermediate_field_subgroup [finite_dimensional F E] [is_galois F E] : galois_coinsertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ H _, intermediate_field.fixed_field H, gc := λ K H, (intermediate_field.le_iff_le H K).symm, u_l_le := λ K, le_of_eq (fixed_field_fixing_subgroup K), choice_eq := λ H _, rfl } end is_galois end galois_correspondence section galois_equivalent_definitions variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] namespace is_galois lemma is_separable_splitting_field [finite_dimensional F E] [h : is_galois F E] : ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E := begin cases field.exists_primitive_element h.1 with α h1, use [minpoly F α, separable F α, is_galois.splits F α], rw [eq_top_iff, ←intermediate_field.top_to_subalgebra, ←h1], rw intermediate_field.adjoin_simple_to_subalgebra_of_integral F α (integral F α), apply algebra.adjoin_mono, rw [set.singleton_subset_iff, finset.mem_coe, multiset.mem_to_finset, polynomial.mem_roots], { dsimp only [polynomial.is_root], rw [polynomial.eval_map, ←polynomial.aeval_def], exact minpoly.aeval _ _ }, { exact polynomial.map_ne_zero (minpoly.ne_zero (integral F α)) } end lemma of_fixed_field_eq_bot [finite_dimensional F E] (h : intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥) : is_galois F E := begin rw [←is_galois_iff_is_galois_bot, ←h], exact is_galois.of_fixed_field E (⊤ : subgroup (E ≃ₐ[F] E)), end lemma of_card_aut_eq_findim [finite_dimensional F E] (h : fintype.card (E ≃ₐ[F] E) = findim F E) : is_galois F E := begin apply of_fixed_field_eq_bot, have p : 0 < findim (intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E))) E := findim_pos, rw [←intermediate_field.findim_eq_one_iff, ←mul_left_inj' (ne_of_lt p).symm, findim_mul_findim, ←h, one_mul, intermediate_field.findim_fixed_field_eq_card], apply fintype.card_congr, exact { to_fun := λ g, ⟨g, subgroup.mem_top g⟩, inv_fun := coe, left_inv := λ g, rfl, right_inv := λ _, by { ext, refl } }, end variables {F} {E} {p : polynomial F} lemma of_separable_splitting_field_aux [hFE : finite_dimensional F E] [sp : p.is_splitting_field F E] (hp : p.separable) (K : intermediate_field F E) {x : E} (hx : x ∈ (p.map (algebra_map F E)).roots) : fintype.card ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) = fintype.card (K →ₐ[F] E) * findim K K⟮x⟯ := begin have h : is_integral K x := is_integral_of_is_scalar_tower x (is_integral_of_noetherian hFE x), have h1 : p ≠ 0 := λ hp, by rwa [hp, polynomial.map_zero, polynomial.roots_zero] at hx, have h2 : (minpoly K x) ∣ p.map (algebra_map F K), { apply minpoly.dvd, rw [polynomial.aeval_def, polynomial.eval₂_map, ←polynomial.eval_map], exact (polynomial.mem_roots (polynomial.map_ne_zero h1)).mp hx }, let key_equiv : ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) ≃ Σ (f : K →ₐ[F] E), @alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f) := equiv.trans (alg_equiv.arrow_congr (intermediate_field.lift2_alg_equiv K⟮x⟯) (alg_equiv.refl)) alg_hom_equiv_sigma, haveI : Π (f : K →ₐ[F] E), fintype (@alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f)) := λ f, by { apply fintype.of_injective (sigma.mk f) (λ _ _ H, eq_of_heq ((sigma.mk.inj H).2)), exact fintype.of_equiv _ key_equiv }, rw [fintype.card_congr key_equiv, fintype.card_sigma, intermediate_field.adjoin.findim h], apply finset.sum_const_nat, intros f hf, rw ← @intermediate_field.card_alg_hom_adjoin_integral K _ E _ _ x E _ (ring_hom.to_algebra f) h, { apply fintype.card_congr, refl }, { exact polynomial.separable.of_dvd ((polynomial.separable_map (algebra_map F K)).mpr hp) h2 }, { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero h1) _ h2, rw [polynomial.splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact sp.splits }, end lemma of_separable_splitting_field [sp : p.is_splitting_field F E] (hp : p.separable) : is_galois F E := begin haveI hFE : finite_dimensional F E := polynomial.is_splitting_field.finite_dimensional E p, let s := (p.map (algebra_map F E)).roots.to_finset, have adjoin_root := intermediate_field.ext (subalgebra.ext_iff.mp (eq.trans (top_le_iff.mp (eq.trans_le sp.adjoin_roots.symm (intermediate_field.algebra_adjoin_le_adjoin F ↑s))) intermediate_field.top_to_subalgebra.symm)), let P : intermediate_field F E → Prop := λ K, fintype.card (K →ₐ[F] E) = findim F K, suffices : P (intermediate_field.adjoin F ↑s), { rw adjoin_root at this, apply of_card_aut_eq_findim, rw ← eq.trans this (linear_equiv.findim_eq intermediate_field.top_equiv.to_linear_equiv), exact fintype.card_congr (equiv.trans (alg_equiv_equiv_alg_hom F E) (alg_equiv.arrow_congr intermediate_field.top_equiv.symm alg_equiv.refl)) }, apply intermediate_field.induction_on_adjoin_finset s P, { have key := intermediate_field.card_alg_hom_adjoin_integral F (show is_integral F (0 : E), by exact is_integral_zero), rw [minpoly.zero, polynomial.nat_degree_X] at key, specialize key polynomial.separable_X (polynomial.splits_X (algebra_map F E)), rw [←@subalgebra.findim_bot F E _ _ _, ←intermediate_field.bot_to_subalgebra] at key, refine eq.trans _ key, apply fintype.card_congr, rw intermediate_field.adjoin_zero }, intros K x hx hK, simp only [P] at *, rw [of_separable_splitting_field_aux hp K (multiset.mem_to_finset.mp hx), hK, findim_mul_findim], exact (linear_equiv.findim_eq (intermediate_field.lift2_alg_equiv K⟮x⟯).to_linear_equiv).symm, end /--Equivalent characterizations of a Galois extension of finite degree-/ theorem tfae [finite_dimensional F E] : tfae [is_galois F E, intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥, fintype.card (E ≃ₐ[F] E) = findim F E, ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E] := begin tfae_have : 1 → 2, { exact λ h, order_iso.map_bot (@intermediate_field_equiv_subgroup F _ E _ _ _ h).symm }, tfae_have : 1 → 3, { introI _, exact card_aut_eq_findim F E }, tfae_have : 1 → 4, { introI _, exact is_separable_splitting_field F E }, tfae_have : 2 → 1, { exact of_fixed_field_eq_bot F E }, tfae_have : 3 → 1, { exact of_card_aut_eq_findim F E }, tfae_have : 4 → 1, { rintros ⟨h, hp1, _⟩, exactI of_separable_splitting_field hp1 }, tfae_finish, end end is_galois end galois_equivalent_definitions
c5f0fa70ea145992cba28cb0c0fb09213ff806e1
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/expr.lean
3ba22210e2a1aed482583804a3be9ce39be817fe
[ "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
24,163
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.level init.control.monad init.meta.rb_map universes u v open native /-- Column and line position in a Lean source file. -/ structure pos := (line : nat) (column : nat) instance : decidable_eq pos | ⟨l₁, c₁⟩ ⟨l₂, c₂⟩ := if h₁ : l₁ = l₂ then if h₂ : c₁ = c₂ then is_true (eq.rec_on h₁ (eq.rec_on h₂ rfl)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₂ h₂)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₁ h₁)) meta instance : has_to_format pos := ⟨λ ⟨l, c⟩, "⟨" ++ l ++ ", " ++ c ++ "⟩"⟩ /-- Auxiliary annotation for binders (Lambda and Pi). This information is only used for elaboration. The difference between `{}` and `⦃⦄` is how implicit arguments are treated that are *not* followed by explicit arguments. `{}` arguments are applied eagerly, while `⦃⦄` arguments are left partially applied: ```lean def foo {x : ℕ} : ℕ := x def bar ⦃x : ℕ⦄ : ℕ := x #check foo -- foo : ℕ #check bar -- bar : Π ⦃x : ℕ⦄, ℕ ``` -/ inductive binder_info /- `(x : α)` -/ | default /- `{x : α}` -/ | implicit /- `⦃x:α⦄` -/ | strict_implicit /- `[x : α]`. Should be inferred with typeclass resolution. -/ | inst_implicit /- Auxiliary internal attribute used to mark local constants representing recursive functions in recursive equations and `match` statements. -/ | aux_decl instance : has_repr binder_info := ⟨λ bi, match bi with | binder_info.default := "default" | binder_info.implicit := "implicit" | binder_info.strict_implicit := "strict_implicit" | binder_info.inst_implicit := "inst_implicit" | binder_info.aux_decl := "aux_decl" end⟩ /-- Macros are basically "promises" to build an expr by some C++ code, you can't build them in Lean. You can unfold a macro and force it to evaluate. They are used for - `sorry`. - Term placeholders (`_`) in `pexpr`s. - Expression annotations. See `expr.is_annotation`. - Meta-recursive calls. Eg: ``` meta def Y : (α → α) → α | f := f (Y f) ``` The `Y` that appears in `f (Y f)` is a macro. - Builtin projections: ``` structure foo := (mynat : ℕ) #print foo.mynat -- @[reducible] -- def foo.mynat : foo → ℕ := -- λ (c : foo), [foo.mynat c] ``` The thing in square brackets is a macro. - Ephemeral structures inside certain specialised C++ implemented tactics. -/ meta constant macro_def : Type /-- An expression. eg ```(4+5)```. The `elab` flag is indicates whether the `expr` has been elaborated and doesn't contain any placeholder macros. For example the equality `x = x` is represented in `expr ff` as ``app (app (const `eq _) x) x`` while in `expr tt` it is represented as ``app (app (app (const `eq _) t) x) x`` (one more argument). The VM replaces instances of this datatype with the C++ implementation. -/ meta inductive expr (elaborated : bool := tt) /- A bound variable with a de-Bruijn index. -/ | var (i : nat) : expr /- A type universe: `Sort u` -/ | sort (l : level) : expr /- A global constant. These include definitions, constants and inductive type stuff present in the environment as well as hard-coded definitions. -/ | const (name : name) (ls : list level) : expr /- [WARNING] Do not trust the types for `mvar` and `local_const`, they are sometimes dummy values. Use `tactic.infer_type` instead. -/ /- An `mvar` is a 'hole' yet to be filled in by the elaborator or tactic state. -/ | mvar (unique : name) (pretty : name) (type : expr) : expr /- A local constant. For example, if our tactic state was `h : P ⊢ Q`, `h` would be a local constant. -/ | local_const (unique : name) (pretty : name) (bi : binder_info) (type : expr) : expr /- Function application. -/ | app (f : expr) (x : expr) : expr /- Lambda abstraction. eg ```(λ a : α, x)`` -/ | lam (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr /- Pi type constructor. eg ```(Π a : α, x)`` and ```(α → β)`` -/ | pi (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr /- An explicit let binding. -/ | elet (var_name : name) (type : expr) (assignment : expr) (body : expr) : expr /- A macro, see the docstring for `macro_def`. The list of expressions are local constants and metavariables that the macro depends on. -/ | macro (m : macro_def) (args : list expr) : expr variable {elab : bool} meta instance : inhabited (expr elab) := ⟨expr.sort level.zero⟩ /-- Get the name of the macro definition. -/ meta constant expr.macro_def_name (d : macro_def) : name meta def expr.mk_var (n : nat) : expr := expr.var n /-- Expressions can be annotated using an annotation macro during compilation. For example, a `have x:X, from p, q` expression will be compiled to `(λ x:X,q)(p)`, but nested in an annotation macro with the name `"have"`. These annotations have no real semantic meaning, but are useful for helping Lean's pretty printer. -/ meta constant expr.is_annotation : expr elab → option (name × expr elab) meta constant expr.is_string_macro : expr elab → option (expr elab) /-- Remove all macro annotations from the given `expr`. -/ meta def expr.erase_annotations : expr elab → expr elab | e := match e.is_annotation with | some (_, a) := expr.erase_annotations a | none := e end /-- Compares expressions, including binder names. -/ meta constant expr.has_decidable_eq : decidable_eq expr attribute [instance] expr.has_decidable_eq /-- Compares expressions while ignoring binder names. -/ meta constant expr.alpha_eqv : expr → expr → bool notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt protected meta constant expr.to_string : expr elab → string meta instance : has_to_string (expr elab) := ⟨expr.to_string⟩ meta instance : has_to_format (expr elab) := ⟨λ e, e.to_string⟩ /-- Coercion for letting users write (f a) instead of (expr.app f a) -/ meta instance : has_coe_to_fun (expr elab) (λ e, expr elab → expr elab) := ⟨λ e, expr.app e⟩ /-- Each expression created by Lean carries a hash. This is calculated upon creation of the expression. Two structurally equal expressions will have the same hash. -/ meta constant expr.hash : expr → nat /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta constant expr.lt : expr → expr → bool /-- Compares expressions, ignoring binder names. -/ meta constant expr.lex_lt : expr → expr → bool /-- `expr.fold e a f`: Traverses each subexpression of `e`. The `nat` passed to the folder `f` is the binder depth. -/ meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α /-- `expr.replace e f` Traverse over an expr `e` with a function `f` which can decide to replace subexpressions or not. For each subexpression `s` in the expression tree, `f s n` is called where `n` is how many binders are present above the given subexpression `s`. If `f s n` returns `none`, the children of `s` will be traversed. Otherwise if `some s'` is returned, `s'` will replace `s` and this subexpression will not be traversed further. -/ meta constant expr.replace : expr → (expr → nat → option expr) → expr /-- `abstract_local e n` replaces each instance of the local constant with unique (not pretty) name `n` in `e` with a de-Bruijn variable. -/ meta constant expr.abstract_local : expr → name → expr /-- Multi version of `abstract_local`. Note that the given expression will only be traversed once, so this is not the same as `list.foldl expr.abstract_local`.-/ meta constant expr.abstract_locals : expr → list name → expr /-- `abstract e x` Abstracts the expression `e` over the local constant `x`. -/ meta def expr.abstract : expr → expr → expr | e (expr.local_const n m bi t) := e.abstract_local n | e _ := e /-- Expressions depend on `level`s, and these may depend on universe parameters which have names. `instantiate_univ_params e [(n₁,l₁), ...]` will traverse `e` and replace any universe parameters with name `nᵢ` with the corresponding level `lᵢ`. -/ meta constant expr.instantiate_univ_params : expr → list (name × level) → expr /-- `instantiate_nth_var n a b` takes the `n`th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/ meta constant expr.instantiate_nth_var : nat → expr → expr → expr /-- `instantiate_var a b` takes the 0th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/ meta constant expr.instantiate_var : expr → expr → expr /-- ``instantiate_vars `(#0 #1 #2) [x,y,z] = `(%%x %%y %%z)`` -/ meta constant expr.instantiate_vars : expr → list expr → expr /-- Same as `instantiate_vars` except lifts and shifts the vars by the given amount. ``instantiate_vars_core `(#0 #1 #2 #3) 0 [x,y] = `(x y #0 #1)`` ``instantiate_vars_core `(#0 #1 #2 #3) 1 [x,y] = `(#0 x y #1)`` ``instantiate_vars_core `(#0 #1 #2 #3) 2 [x,y] = `(#0 #1 x y)`` -/ meta constant expr.instantiate_vars_core : expr → nat → list expr → expr /-- Perform beta-reduction if the left expression is a lambda, or construct an application otherwise. That is: ``expr.subst `(λ x, %%Y) Z = Y[x/Z]``, and ``expr.subst X Z = X.app Z`` otherwise -/ protected meta constant expr.subst : expr elab → expr elab → expr elab /-- `get_free_var_range e` returns one plus the maximum de-Bruijn value in `e`. Eg `get_free_var_range `(#1 #0)` yields `2` -/ meta constant expr.get_free_var_range : expr → nat /-- `has_var e` returns true iff e has free variables. -/ meta constant expr.has_var : expr → bool /-- `has_var_idx e n` returns true iff `e` has a free variable with de-Bruijn index `n`. -/ meta constant expr.has_var_idx : expr → nat → bool /-- `has_local e` returns true if `e` contains a local constant. -/ meta constant expr.has_local : expr → bool /-- `has_meta_var e` returns true iff `e` contains a metavariable. -/ meta constant expr.has_meta_var : expr → bool /-- `lower_vars e s d` lowers the free variables >= s in `e` by `d`. Note that this can cause variable clashes. examples: - ``lower_vars `(#2 #1 #0) 1 1 = `(#1 #0 #0)`` - ``lower_vars `(λ x, #2 #1 #0) 1 1 = `(λ x, #1 #1 #0 )`` -/ meta constant expr.lower_vars : expr → nat → nat → expr /-- Lifts free variables. `lift_vars e s d` will lift all free variables with index `≥ s` in `e` by `d`. -/ meta constant expr.lift_vars : expr → nat → nat → expr /-- Get the position of the given expression in the Lean source file, if anywhere. -/ protected meta constant expr.pos : expr elab → option pos /-- `copy_pos_info src tgt` copies position information from `src` to `tgt`. -/ meta constant expr.copy_pos_info : expr → expr → expr /-- Returns `some n` when the given expression is a constant with the name `..._cnstr.n` ``` is_internal_cnstr : expr → option unsigned |(const (mk_numeral n (mk_string "_cnstr" _)) _) := some n |_ := none ``` [NOTE] This is not used anywhere in core Lean. -/ meta constant expr.is_internal_cnstr : expr → option unsigned /-- There is a macro called a "nat_value_macro" holding a natural number which are used during compilation. This function extracts that to a natural number. [NOTE] This is not used anywhere in Lean. -/ meta constant expr.get_nat_value : expr → option nat /-- Get a list of all of the universe parameters that the given expression depends on. -/ meta constant expr.collect_univ_params : expr → list name /-- `occurs e t` returns `tt` iff `e` occurs in `t` up to α-equivalence. Purely structural: no unification or definitional equality. -/ meta constant expr.occurs : expr → expr → bool /-- Returns true if any of the names in the given `name_set` are present in the given `expr`. -/ meta constant expr.has_local_in : expr → name_set → bool /-- Computes the number of sub-expressions (constant time). -/ meta constant expr.get_weight : expr → ℕ /-- Computes the maximum depth of the expression (constant time). -/ meta constant expr.get_depth : expr → ℕ /-- `mk_delayed_abstraction m ls` creates a delayed abstraction on the metavariable `m` with the unique names of the local constants `ls`. If `m` is not a metavariable then this is equivalent to `abstract_locals`. -/ meta constant expr.mk_delayed_abstraction : expr → list name → expr /-- If the given expression is a delayed abstraction macro, return `some ls` where `ls` is a list of unique names of locals that will be abstracted. -/ meta constant expr.get_delayed_abstraction_locals : expr → option (list name) /-- (reflected a) is a special opaque container for a closed `expr` representing `a`. It can only be obtained via type class inference, which will use the representation of `a` in the calling context. Local constants in the representation are replaced by nested inference of `reflected` instances. The quotation expression `` `(a) `` (outside of patterns) is equivalent to `reflect a` and thus can be used as an explicit way of inferring an instance of `reflected a`. Note that the `α` argument is explicit to prevent it being treated as reducible by typeclass inference, as this breaks `reflected` instances on type synonyms. -/ @[class] meta def reflected (α : Sort u) : α → Type := λ _, expr @[inline] meta def reflected.to_expr {α : Sort u} {a : α} : reflected _ a → expr := id /-- This is a more strongly-typed version of `expr.subst` that keeps track of the value being reflected. To obtain a term of type `reflected _`, use `` (`(λ x y, foo x y).subst ex).subst ey`` instead of using `` `(foo %%ex %%ey) `` (which returns an `expr`). -/ @[inline] meta def reflected.subst {α : Sort v} {β : α → Sort u} {f : Π a : α, β a} {a : α} : reflected _ f → reflected _ a → reflected _ (f a) := expr.subst attribute [irreducible] reflected reflected.subst reflected.to_expr @[instance] protected meta constant expr.reflect (e : expr elab) : reflected _ e @[instance] protected meta constant string.reflect (s : string) : reflected _ s @[inline] meta instance {α : Sort u} (a : α) : has_coe (reflected _ a) expr := ⟨reflected.to_expr⟩ protected meta def reflect {α : Sort u} (a : α) [h : reflected _ a] : reflected _ a := h meta instance {α} (a : α) : has_to_format (reflected _ a) := ⟨λ h, to_fmt h.to_expr⟩ namespace expr open decidable meta def lt_prop (a b : expr) : Prop := expr.lt a b = tt meta instance : decidable_rel expr.lt_prop := λ a b, bool.decidable_eq _ _ /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta instance : has_lt expr := ⟨ expr.lt_prop ⟩ meta def mk_true : expr := const `true [] meta def mk_false : expr := const `false [] /-- Returns the sorry macro with the given type. -/ meta constant mk_sorry (type : expr) : expr /-- Checks whether e is sorry, and returns its type. -/ meta constant is_sorry (e : expr) : option expr /-- Replace each instance of the local constant with name `n` by the expression `s` in `e`. -/ meta def instantiate_local (n : name) (s : expr) (e : expr) : expr := instantiate_var (abstract_local e n) s meta def instantiate_locals (s : list (name × expr)) (e : expr) : expr := instantiate_vars (abstract_locals e (list.reverse (list.map prod.fst s))) (list.map prod.snd s) meta def is_var : expr → bool | (var _) := tt | _ := ff meta def app_of_list : expr → list expr → expr | f [] := f | f (p::ps) := app_of_list (f p) ps meta def is_app : expr → bool | (app f a) := tt | e := ff meta def app_fn : expr → expr | (app f a) := f | a := a meta def app_arg : expr → expr | (app f a) := a | a := a meta def get_app_fn : expr elab → expr elab | (app f a) := get_app_fn f | a := a meta def get_app_num_args : expr → nat | (app f a) := get_app_num_args f + 1 | e := 0 meta def get_app_args_aux : list expr → expr → list expr | r (app f a) := get_app_args_aux (a::r) f | r e := r meta def get_app_args : expr → list expr := get_app_args_aux [] meta def mk_app : expr → list expr → expr | e [] := e | e (x::xs) := mk_app (e x) xs meta def mk_binding (ctor : name → binder_info → expr → expr → expr) (e : expr) : Π (l : expr), expr | (local_const n pp_n bi ty) := ctor pp_n bi ty (e.abstract_local n) | _ := e /-- (bind_pi e l) abstracts and pi-binds the local `l` in `e` -/ meta def bind_pi := mk_binding pi /-- (bind_lambda e l) abstracts and lambda-binds the local `l` in `e` -/ meta def bind_lambda := mk_binding lam meta def ith_arg_aux : expr → nat → expr | (app f a) 0 := a | (app f a) (n+1) := ith_arg_aux f n | e _ := e meta def ith_arg (e : expr) (i : nat) : expr := ith_arg_aux e (get_app_num_args e - i - 1) meta def const_name : expr elab → name | (const n ls) := n | e := name.anonymous meta def is_constant : expr elab → bool | (const n ls) := tt | e := ff meta def is_local_constant : expr → bool | (local_const n m bi t) := tt | e := ff meta def local_uniq_name : expr → name | (local_const n m bi t) := n | e := name.anonymous meta def local_pp_name : expr elab → name | (local_const x n bi t) := n | e := name.anonymous meta def local_type : expr elab → expr elab | (local_const _ _ _ t) := t | e := e meta def is_aux_decl : expr → bool | (local_const _ _ binder_info.aux_decl _) := tt | _ := ff meta def is_constant_of : expr elab → name → bool | (const n₁ ls) n₂ := n₁ = n₂ | e n := ff meta def is_app_of (e : expr) (n : name) : bool := is_constant_of (get_app_fn e) n /-- The same as `is_app_of` but must also have exactly `n` arguments. -/ meta def is_napp_of (e : expr) (c : name) (n : nat) : bool := is_app_of e c ∧ get_app_num_args e = n meta def is_false : expr → bool | `(false) := tt | _ := ff meta def is_not : expr → option expr | `(not %%a) := some a | `(%%a → false) := some a | e := none meta def is_and : expr → option (expr × expr) | `(and %%α %%β) := some (α, β) | _ := none meta def is_or : expr → option (expr × expr) | `(or %%α %%β) := some (α, β) | _ := none meta def is_iff : expr → option (expr × expr) | `((%%a : Prop) ↔ %%b) := some (a, b) | _ := none meta def is_eq : expr → option (expr × expr) | `((%%a : %%_) = %%b) := some (a, b) | _ := none meta def is_ne : expr → option (expr × expr) | `((%%a : %%_) ≠ %%b) := some (a, b) | _ := none meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) := if is_napp_of e op 4 then some (app_arg (app_fn e), app_arg e) else none meta def is_lt (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_lt.lt meta def is_gt (e : expr) : option (expr × expr) := is_bin_arith_app e ``gt meta def is_le (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_le.le meta def is_ge (e : expr) : option (expr × expr) := is_bin_arith_app e ``ge meta def is_heq : expr → option (expr × expr × expr × expr) | `(@heq %%α %%a %%β %%b) := some (α, a, β, b) | _ := none meta def is_lambda : expr → bool | (lam _ _ _ _) := tt | e := ff meta def is_pi : expr → bool | (pi _ _ _ _) := tt | e := ff meta def is_arrow : expr → bool | (pi _ _ _ b) := bnot (has_var b) | e := ff meta def is_let : expr → bool | (elet _ _ _ _) := tt | e := ff /-- The name of the bound variable in a pi, lambda or let expression. -/ meta def binding_name : expr → name | (pi n _ _ _) := n | (lam n _ _ _) := n | (elet n _ _ _) := n | e := name.anonymous /-- The binder info of a pi or lambda expression. -/ meta def binding_info : expr → binder_info | (pi _ bi _ _) := bi | (lam _ bi _ _) := bi | e := binder_info.default /-- The domain (type of bound variable) of a pi, lambda or let expression. -/ meta def binding_domain : expr → expr | (pi _ _ d _) := d | (lam _ _ d _) := d | (elet _ d _ _) := d | e := e /-- The body of a pi, lambda or let expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions] in mathlib. -/ meta def binding_body : expr → expr | (pi _ _ _ b) := b | (lam _ _ _ b) := b | (elet _ _ _ b) := b | e := e /-- `nth_binding_body n e` iterates `binding_body` `n` times to an iterated pi expression `e`. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions] in mathlib. -/ meta def nth_binding_body : ℕ → expr → expr | (n + 1) (pi _ _ _ b) := nth_binding_body n b | _ e := e meta def is_macro : expr → bool | (macro d a) := tt | e := ff meta def is_numeral : expr → bool | `(@has_zero.zero %%α %%s) := tt | `(@has_one.one %%α %%s) := tt | `(@bit0 %%α %%s %%v) := is_numeral v | `(@bit1 %%α %%s₁ %%s₂ %%v) := is_numeral v | _ := ff meta def pi_arity : expr → ℕ | (pi _ _ _ b) := pi_arity b + 1 | _ := 0 meta def lam_arity : expr → ℕ | (lam _ _ _ b) := lam_arity b + 1 | _ := 0 meta def imp (a b : expr) : expr := pi `_ binder_info.default a b /-- `lambdas cs e` lambda binds `e` with each of the local constants in `cs`. -/ meta def lambdas : list expr → expr → expr | (local_const uniq pp info t :: es) f := lam pp info t (abstract_local (lambdas es f) uniq) | _ f := f /-- Same as `expr.lambdas` but with `pi`. -/ meta def pis : list expr → expr → expr | (local_const uniq pp info t :: es) f := pi pp info t (abstract_local (pis es f) uniq) | _ f := f meta def extract_opt_auto_param : expr → expr | `(@opt_param %%t _) := extract_opt_auto_param t | `(@auto_param %%t _) := extract_opt_auto_param t | e := e open format private meta def p : list format → format | [] := "" | [x] := x.paren | (x::y::xs) := p ((x ++ format.line ++ y).group :: xs) meta def to_raw_fmt : expr elab → format | (var n) := p ["var", to_fmt n] | (sort l) := p ["sort", to_fmt l] | (const n ls) := p ["const", to_fmt n, to_fmt ls] | (mvar n m t) := p ["mvar", to_fmt n, to_fmt m, to_raw_fmt t] | (local_const n m bi t) := p ["local_const", to_fmt n, to_fmt m, to_raw_fmt t] | (app e f) := p ["app", to_raw_fmt e, to_raw_fmt f] | (lam n bi e t) := p ["lam", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t] | (pi n bi e t) := p ["pi", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t] | (elet n g e f) := p ["elet", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f] | (macro d args) := sbracket (format.join (list.intersperse " " ("macro" :: to_fmt (macro_def_name d) :: args.map to_raw_fmt))) /-- Fold an accumulator `a` over each subexpression in the expression `e`. The `nat` passed to `fn` is the number of binders above the subexpression. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : expr) (a : α) (fn : expr → nat → α → m α) : m α := fold e (return a) (λ e n a, a >>= fn e n) end expr /-- An dictionary from `data` to expressions. -/ @[reducible] meta def expr_map (data : Type) := rb_map expr data namespace expr_map export native.rb_map (mk_core size empty insert erase contains find min max fold keys values to_list mfold of_list set_of_list map for filter) meta def mk (data : Type) : expr_map data := rb_map.mk expr data end expr_map meta def mk_expr_map {data : Type} : expr_map data := expr_map.mk data @[reducible] meta def expr_set := rb_set expr meta def mk_expr_set : expr_set := mk_rb_set
c68e337ff7f8f2b5384d967c56fbba3705cae872
91b8df3b248df89472cc0b753fbe2bac750aefea
/experiments/lean/src/ddl/binary/formation.lean
21a829f5a087b3327b2301cc5f69b2b7368fb350
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yeslogic/fathom
eabe5c4112d3b4d5ec9096a57bb502254ddbdf15
3960a9466150d392c2cb103c5cb5fcffa0200814
refs/heads/main
1,685,349,769,736
1,675,998,621,000
1,675,998,621,000
28,993,871
214
11
Apache-2.0
1,694,044,276,000
1,420,764,938,000
Rust
UTF-8
Lean
false
false
1,794
lean
import ddl.host.typing import ddl.binary.basic namespace ddl.binary open ddl open ddl.binary namespace type variables {ℓ α : Type} [decidable_eq ℓ] inductive struct : type ℓ α → Prop | nil {} : struct struct_nil | cons {l t₁ t₂} : struct (struct_cons l t₁ t₂) inductive union : type ℓ α → Prop | nil {} : union union_nil | cons {l t₁ t₂} : union (union_cons l t₁ t₂) inductive well_formed : type ℓ α → Prop | bvar {} (i) : well_formed (bvar i) | fvar (x) : well_formed (fvar x) | bit {} : well_formed bit | union_nil {} : well_formed union_nil | union_cons {l t₁ t₂} : well_formed t₁ → well_formed t₂ → union t₂ → well_formed (union_cons l t₁ t₂) | struct_nil {} : well_formed struct_nil | struct_cons {l t₁ t₂} : well_formed t₁ → well_formed t₂ → struct t₂ → well_formed (struct_cons l t₁ t₂) | array {t e} : well_formed t → well_formed (array t e) | assert {t e} : well_formed t → well_formed (assert t e) | interp {t e th} : well_formed t → well_formed (interp t e th) | lam {t k} : well_formed t → well_formed (lam k t) | app {t₁ t₂} : well_formed t₁ → well_formed t₂ → well_formed (app t₁ t₂) lemma well_formed_lookup : Π {l : ℓ} {tr tf : type ℓ α}, well_formed tr → lookup l tr = some tf → well_formed tf := begin admit end end type end ddl.binary
c400604a9fc4ac7d4ed149871295dd4934a76b84
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/measure_theory/outer_measure.lean
514beb81f8236b223f8df3a1b5111dd933a9177b
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
41,789
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 analysis.specific_limits import measure_theory.measurable_space import topology.algebra.infinite_sum /-! # Outer Measures An outer measure is a function `μ : set α → ℝ≥0∞`, from the powerset of a type to the extended nonnegative real numbers that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is monotone; 3. `μ` is countably subadditive. This means that the outer measure of a countable union is at most the sum of the outer measure on the individual sets. Note that we do not need `α` to be measurable to define an outer measure. The outer measures on a type `α` form a complete lattice. Given an arbitrary function `m : set α → ℝ≥0∞` that sends `∅` to `0` we can define an outer measure on `α` that on `s` is defined to be the infimum of `∑ᵢ, m (sᵢ)` for all collections of sets `sᵢ` that cover `s`. This is the unique maximal outer measure that is at most the given function. We also define this for functions `m` defined on a subset of `set α`, by treating the function as having value `∞` outside its domain. Given an outer measure `m`, the Carathéodory-measurable sets are the sets `s` such that for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. This forms a measurable space. ## Main definitions and statements * `outer_measure.bounded_by` is the greatest outer measure that is at most the given function. If you know that the given functions sends `∅` to `0`, then `outer_measure.of_function` is a special case. * `caratheodory` is the Carathéodory-measurable space of an outer measure. * `Inf_eq_of_function_Inf_gen` is a characterization of the infimum of outer measures. * `induced_outer_measure` is the measure induced by a function on a subset of `set α` ## References * <https://en.wikipedia.org/wiki/Outer_measure> * <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_criterion> ## Tags outer measure, Carathéodory-measurable, Carathéodory's criterion -/ noncomputable theory open set finset function filter encodable open_locale classical big_operators nnreal topological_space ennreal namespace measure_theory /-- An outer measure is a countably subadditive monotone function that sends `∅` to `0`. -/ structure outer_measure (α : Type*) := (measure_of : set α → ℝ≥0∞) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ ∑'i, measure_of (s i)) namespace outer_measure section basic variables {α : Type*} {β : Type*} {ms : set (outer_measure α)} {m : outer_measure α} instance : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ @[simp] lemma measure_of_eq_coe (m : outer_measure α) : m.measure_of = m := rfl @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ ∑'i, m (s i) := rel_supr_tsum m m.empty (≤) m.Union_nat s lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma Union_finset (m : outer_measure α) (s : β → set α) (t : finset β) : m (⋃i ∈ t, s i) ≤ ∑ i in t, m (s i) := rel_supr_sum m m.empty (≤) m.Union_nat s t protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := rel_sup_add m m.empty (≤) m.Union_nat s₁ s₂ lemma le_inter_add_diff {m : outer_measure α} {t : set α} (s : set α) : m t ≤ m (t ∩ s) + m (t \ s) := by { convert m.union _ _, rw inter_union_diff t s } lemma diff_null (m : outer_measure α) (s : set α) {t : set α} (ht : m t = 0) : m (s \ t) = m s := begin refine le_antisymm (m.mono $ diff_subset _ _) _, calc m s ≤ m (s ∩ t) + m (s \ t) : le_inter_add_diff _ ... ≤ m t + m (s \ t) : add_le_add_right (m.mono $ inter_subset_right _ _) _ ... = m (s \ t) : by rw [ht, zero_add] end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ lemma injective_coe_fn : injective (λ (μ : outer_measure α) (s : set α), μ s) := λ μ₁ μ₂ h, by { cases μ₁, cases μ₂, congr, exact h } @[ext] lemma ext {μ₁ μ₂ : outer_measure α} (h : ∀ s, μ₁ s = μ₂ s) : μ₁ = μ₂ := injective_coe_fn $ funext h instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem coe_zero : ⇑(0 : outer_measure α) = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem coe_add (m₁ m₂ : outer_measure α) : ⇑(m₁ + m₂) = m₁ + m₂ := rfl theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), .. injective.add_comm_monoid (show outer_measure α → set α → ℝ≥0∞, from coe_fn) injective_coe_fn rfl (λ _ _, rfl) } instance : has_scalar ℝ≥0∞ (outer_measure α) := ⟨λ c m, { measure_of := λ s, c * m s, empty := by simp, mono := λ s t h, ennreal.mul_left_mono $ m.mono h, Union_nat := λ s, by { rw [ennreal.tsum_mul_left], exact ennreal.mul_left_mono (m.Union _) } }⟩ @[simp] lemma coe_smul (c : ℝ≥0∞) (m : outer_measure α) : ⇑(c • m) = c • m := rfl lemma smul_apply (c : ℝ≥0∞) (m : outer_measure α) (s : set α) : (c • m) s = c * m s := rfl instance : semimodule ℝ≥0∞ (outer_measure α) := { smul := (•), .. injective.semimodule ℝ≥0∞ ⟨show outer_measure α → set α → ℝ≥0∞, from coe_fn, coe_zero, coe_add⟩ injective_coe_fn coe_smul } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆ m ∈ ms, (m : outer_measure α) s, empty := nonpos_iff_eq_zero.1 $ bsupr_le $ λ m h, le_of_eq m.empty, mono := assume s₁ s₂ hs, bsupr_le_bsupr $ assume m hm, m.mono hs, Union_nat := assume f, bsupr_le $ assume m hm, calc m (⋃i, f i) ≤ ∑' (i : ℕ), m (f i) : m.Union_nat _ ... ≤ ∑'i, (⨆ m ∈ ms, (m : outer_measure α) (f i)) : ennreal.tsum_le_tsum $ assume i, le_bsupr m hm }⟩ instance : complete_lattice (outer_measure α) := { .. outer_measure.order_bot, .. complete_lattice_of_Sup (outer_measure α) (λ ms, ⟨λ m hm s, le_bsupr m hm, λ m hm s, bsupr_le (λ m' hm', hm hm' s)⟩) } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m ∈ ms, (m : outer_measure α) s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := by rw [supr, Sup_apply, supr_range, supr] @[norm_cast] theorem coe_supr {ι} (f : ι → outer_measure α) : ⇑(⨆ i, f i) = ⨆ i, f i := funext $ λ s, by rw [supr_apply, _root_.supr_apply] @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum /-- The pushforward of `m` along `f`. The outer measure on `s` is defined to be `m (f ⁻¹' s)`. -/ def map {β} (f : α → β) : outer_measure α →ₗ[ℝ≥0∞] outer_measure β := { to_fun := λ m, { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) }, map_add' := λ m₁ m₂, injective_coe_fn rfl, map_smul' := λ c m, injective_coe_fn rfl } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl instance : functor outer_measure := {map := λ α β f, map f} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, indicator s (λ _, 1) a, empty := by simp, mono := λ s t h, indicator_le_indicator_of_subset h (λ _, zero_le _) a, Union_nat := λ s, if hs : a ∈ ⋃ n, s n then let ⟨i, hi⟩ := mem_Union.1 hs in calc indicator (⋃ n, s n) (λ _, (1 : ℝ≥0∞)) a = 1 : indicator_of_mem hs _ ... = indicator (s i) (λ _, 1) a : (indicator_of_mem hi _).symm ... ≤ ∑' n, indicator (s n) (λ _, 1) a : ennreal.le_tsum _ else by simp only [indicator_of_not_mem hs, zero_le]} @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = indicator s (λ _, 1) a := rfl /-- The sum of an (arbitrary) collection of outer measures. -/ def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl theorem smul_dirac_apply (a : ℝ≥0∞) (b : α) (s : set α) : (a • dirac b) s = indicator s (λ _, a) b := by simp /-- Pullback of an `outer_measure`: `comap f μ s = μ (f '' s)`. -/ def comap {β} (f : α → β) : outer_measure β →ₗ[ℝ≥0∞] outer_measure α := { to_fun := λ m, { measure_of := λ s, m (f '' s), empty := by simp, mono := λ s t h, m.mono $ image_subset f h, Union_nat := λ s, by { rw [image_Union], apply m.Union_nat } }, map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } @[simp] lemma comap_apply {β} (f : α → β) (m : outer_measure β) (s : set α) : comap f m s = m (f '' s) := rfl /-- Restrict an `outer_measure` to a set. -/ def restrict (s : set α) : outer_measure α →ₗ[ℝ≥0∞] outer_measure α := (map coe).comp (comap (coe : s → α)) @[simp] lemma restrict_apply (s t : set α) (m : outer_measure α) : restrict s m t = m (t ∩ s) := by simp [restrict] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ∞ := let ⟨a, as⟩ := h in top_unique $ le_trans (by simp [smul_dirac_apply, as]) (le_bsupr (∞ • dirac a) trivial) end basic section of_function set_option eqn_compiler.zeta true variables {α : Type*} (m : set α → ℝ≥0∞) (m_empty : m ∅ = 0) include m_empty /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_pos_le_add $ begin assume ε hε (hb : ∑'i, μ (s i) < ∞), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left (le_of_lt hl) _), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ ∑'i, m (f i) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← equiv.nat_prod_nat_equiv_nat.symm.tsum_eq], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } lemma of_function_apply (s : set α) : outer_measure.of_function m m_empty s = (⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, m (t n)) := rfl variables {m m_empty} theorem of_function_le (s : set α) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc ∑'i, m (f i) = ∑ i in {0}, m (f i) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem of_function_eq (s : set α) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ ∑'i, m (s i)) : outer_measure.of_function m m_empty s = m s := le_antisymm (of_function_le s) $ le_infi $ λ f, le_infi $ λ hf, le_trans (m_mono hf) (m_subadd f) theorem le_of_function {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H s) (of_function_le s), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ end of_function section bounded_by variables {α : Type*} (m : set α → ℝ≥0∞) /-- Given any function `m` assigning measures to sets, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. This is the same as `outer_measure.of_function`, except that it doesn't require `m ∅ = 0`. -/ def bounded_by : outer_measure α := outer_measure.of_function (λ s, ⨆ (h : s.nonempty), m s) (by simp [empty_not_nonempty]) variables {m} theorem bounded_by_le (s : set α) : bounded_by m s ≤ m s := (of_function_le _).trans supr_const_le theorem bounded_by_eq_of_function (m_empty : m ∅ = 0) (s : set α) : bounded_by m s = outer_measure.of_function m m_empty s := begin have : (λ s : set α, ⨆ (h : s.nonempty), m s) = m, { ext1 t, cases t.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty, m_empty] }, simp [bounded_by, this] end theorem bounded_by_apply (s : set α) : bounded_by m s = ⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, ⨆ (h : (t n).nonempty), m (t n) := by simp [bounded_by, of_function_apply] theorem bounded_by_eq (s : set α) (m_empty : m ∅ = 0) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ ∑'i, m (s i)) : bounded_by m s = m s := by rw [bounded_by_eq_of_function m_empty, of_function_eq s m_mono m_subadd] theorem le_bounded_by {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s, μ s ≤ m s := begin rw [bounded_by, le_of_function, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty] end theorem le_bounded_by' {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s : set α, s.nonempty → μ s ≤ m s := by { rw [le_bounded_by, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h] } end bounded_by section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} /-- A set `s` is Carathéodory-measurable for an outer measure `m` if for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. -/ def is_caratheodory (s : set α) : Prop := ∀t, m t = m (t ∩ s) + m (t \ s) lemma is_caratheodory_iff_le' {s : set α} : is_caratheodory s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ le_inter_add_diff _ @[simp] lemma is_caratheodory_empty : is_caratheodory ∅ := by simp [is_caratheodory, m.empty, diff_empty] lemma is_caratheodory_compl : is_caratheodory s₁ → is_caratheodory s₁ᶜ := by simp [is_caratheodory, diff_eq, add_comm] @[simp] lemma is_caratheodory_compl_iff : is_caratheodory sᶜ ↔ is_caratheodory s := ⟨λ h, by simpa using is_caratheodory_compl m h, is_caratheodory_compl⟩ lemma is_caratheodory_union (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : is_caratheodory s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] lemma is_caratheodory_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, is_caratheodory (s i)) → is_caratheodory (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact is_caratheodory_union m (h n (le_refl (n + 1))) (is_caratheodory_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) lemma is_caratheodory_inter (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∩ s₂) := by { rw [← is_caratheodory_compl_iff, compl_inter], exact is_caratheodory_union _ (is_caratheodory_compl _ h₁) (is_caratheodory_compl _ h₂) } lemma is_caratheodory_sum {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, ∑ i in finset.range n, m (t ∩ s i) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), is_caratheodory_sum], intro a, simpa [range_succ] using λ (h₁ : a ∈ s n) i (hi : i < n) h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end lemma is_caratheodory_Union_nat {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : is_caratheodory (⋃i, s i) := is_caratheodory_iff_le'.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, is_caratheodory_sum m h hd] } }, refine le_trans (add_le_add_right hp _) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left _ _) (ge_of_eq (is_caratheodory_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end lemma f_Union {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @is_caratheodory_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end /-- The Carathéodory-measurable sets for an outer measure `m` form a Dynkin system. -/ def caratheodory_dynkin : measurable_space.dynkin_system α := { has := is_caratheodory, has_empty := is_caratheodory_empty, has_compl := assume s, is_caratheodory_compl, has_Union_nat := assume f hf hn, is_caratheodory_Union_nat hn hf } /-- Given an outer measure `μ`, the Carathéodory-measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, is_caratheodory_inter lemma is_caratheodory_iff {s : set α} : caratheodory.measurable_set' s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_iff_le {s : set α} : caratheodory.measurable_set' s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := is_caratheodory_iff_le' protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.measurable_set' (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma of_function_caratheodory {m : set α → ℝ≥0∞} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.measurable_set' s := begin apply (is_caratheodory_iff_le _).mpr, refine λ t, le_infi (λ f, le_infi $ λ hf, _), refine le_trans (add_le_add (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end lemma bounded_by_caratheodory {m : set α → ℝ≥0∞} {s : set α} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (bounded_by m).caratheodory.measurable_set' s := begin apply of_function_caratheodory, intro t, cases t.eq_empty_or_nonempty with h h, { simp [h, empty_not_nonempty] }, { convert le_trans _ (hs t), { simp [h] }, exact add_le_add supr_const_le supr_const_le } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_iff_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.measurable_set_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ℝ≥0∞) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases ht : a ∈ t, swap, by simp [ht], by_cases hs : a ∈ s; simp* end section Inf_gen /-- Given a set of outer measures, we define a new function that on a set `s` is defined to be the infimum of `μ(s)` for the outer measures `μ` in the collection. We ensure that this function is defined to be `0` on `∅`, even if the collection of outer measures is empty. The outer measure generated by this function is the infimum of the given outer measures. -/ def Inf_gen (m : set (outer_measure α)) (s : set α) : ℝ≥0∞ := ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s lemma Inf_gen_def (m : set (outer_measure α)) (t : set α) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := rfl lemma Inf_eq_bounded_by_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.bounded_by (Inf_gen m) := begin refine le_antisymm _ _, { refine (le_bounded_by.2 $ λ s, _), refine le_binfi _, intros μ hμ, refine (show Inf m ≤ μ, from Inf_le hμ) s }, { refine le_Inf _, intros μ hμ t, refine le_trans (bounded_by_le t) (binfi_le μ hμ) } end lemma supr_Inf_gen_nonempty {m : set (outer_measure α)} (h : m.nonempty) (t : set α) : (⨆ (h : t.nonempty), Inf_gen m t) = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin rcases t.eq_empty_or_nonempty with rfl|ht, { rcases h with ⟨μ, hμ⟩, rw [eq_false_intro empty_not_nonempty, supr_false, eq_comm], simp_rw [empty'], apply bot_unique, refine infi_le_of_le μ (infi_le _ hμ) }, { simp [ht, Inf_gen_def] } end /-- The value of the Infimum of a nonempty set of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply {m : set (outer_measure α)} {s : set α} (h : m.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := by simp_rw [Inf_eq_bounded_by_Inf_gen, bounded_by_apply, supr_Inf_gen_nonempty h] /-- This proves that Inf and restrict commute for outer measures, so long as the set of outer measures is nonempty. -/ lemma restrict_Inf_eq_Inf_restrict (m : set (outer_measure α)) {s : set α} (hm : m.nonempty) : restrict s (Inf m) = Inf ((restrict s) '' m) := begin have hm2 : ((measure_theory.outer_measure.restrict s) '' m).nonempty := set.nonempty_image_iff.mpr hm, ext1 u, rw [restrict_apply, Inf_apply hm, Inf_apply hm2], apply le_antisymm; simp only [set.mem_image, infi_exists, le_infi_iff]; intros t hu, { refine infi_le_of_le (λ n, (t n) ∩ s) _, refine infi_le_of_le _ _, { rw [← Union_inter], exact inter_subset_inter hu subset.rfl }, apply ennreal.tsum_le_tsum (λ n, _) , simp only [and_imp, set.mem_image, infi_exists, le_infi_iff], rintro _ ⟨μ, h_μ_in_s, rfl⟩, refine infi_le_of_le μ _, refine infi_le_of_le h_μ_in_s _, simp_rw [restrict_apply, le_refl] }, { refine infi_le_of_le (λ n, (t n) ∪ sᶜ) _, refine infi_le_of_le _ _, { rwa [inter_subset, set.union_comm, Union_union] at hu }, apply ennreal.tsum_le_tsum (λ n, _), refine le_binfi (λ μ hμ, _), refine infi_le_of_le (restrict s μ) _, refine infi_le_of_le ⟨_, hμ, rfl⟩ _, rw [restrict_apply, union_inter_distrib_right, compl_inter_self, set.union_empty], exact μ.mono (inter_subset_left _ _) }, end end Inf_gen end outer_measure open outer_measure /-! ### Induced Outer Measure We can extend a function defined on a subset of `set α` to an outer measure. The underlying function is called `extend`, and the measure it induces is called `induced_outer_measure`. Some lemmas below are proven twice, once in the general case, and one where the function `m` is only defined on measurable sets (i.e. when `P = measurable_set`). In the latter cases, we can remove some hypotheses in the statement. The general version has the same name, but with a prime at the end. -/ section extend variables {α : Type*} {P : α → Prop} variables (m : Π (s : α), P s → ℝ≥0∞) /-- We can trivially extend a function defined on a subclass of objects (with codomain `ℝ≥0∞`) to all objects by defining it to be `∞` on the objects not in the class. -/ def extend (s : α) : ℝ≥0∞ := ⨅ h : P s, m s h lemma extend_eq {s : α} (h : P s) : extend m s = m s h := by simp [extend, h] lemma le_extend {s : α} (h : P s) : m s h ≤ extend m s := by { simp only [extend, le_infi_iff], intro, refl' } end extend section extend_set variables {α : Type*} {P : set α → Prop} variables {m : Π (s : set α), P s → ℝ≥0∞} variables (P0 : P ∅) (m0 : m ∅ P0 = 0) variables (PU : ∀{{f : ℕ → set α}} (hm : ∀i, P (f i)), P (⋃i, f i)) variables (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), pairwise (disjoint on f) → m (⋃i, f i) (PU hm) = ∑'i, m (f i) (hm i)) variables (msU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), m (⋃i, f i) (PU hm) ≤ ∑'i, m (f i) (hm i)) variables (m_mono : ∀⦃s₁ s₂ : set α⦄ (hs₁ : P s₁) (hs₂ : P s₂), s₁ ⊆ s₂ → m s₁ hs₁ ≤ m s₂ hs₂) lemma extend_empty : extend m ∅ = 0 := (extend_eq _ P0).trans m0 lemma extend_Union_nat {f : ℕ → set α} (hm : ∀i, P (f i)) (mU : m (⋃i, f i) (PU hm) = ∑'i, m (f i) (hm i)) : extend m (⋃i, f i) = ∑'i, extend m (f i) := (extend_eq _ _).trans $ mU.trans $ by { congr' with i, rw extend_eq } section subadditive include PU msU lemma extend_Union_le_tsum_nat' (s : ℕ → set α) : extend m (⋃i, s i) ≤ ∑'i, extend m (s i) := begin by_cases h : ∀i, P (s i), { rw [extend_eq _ (PU h), congr_arg tsum _], { apply msU h }, funext i, apply extend_eq _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } end end subadditive section mono include m_mono lemma extend_mono' ⦃s₁ s₂ : set α⦄ (h₁ : P s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := by { refine le_infi _, intro h₂, rw [extend_eq m h₁], exact m_mono h₁ h₂ hs } end mono section unions include P0 m0 PU mU lemma extend_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (hm : ∀i, P (f i)) : extend m (⋃i, f i) = ∑'i, extend m (f i) := begin rw [← encodable.Union_decode2, ← tsum_Union_decode2], { exact extend_Union_nat PU (λ n, encodable.Union_decode2_cases P0 hm) (mU _ (encodable.Union_decode2_disjoint_on hd)) }, { exact extend_empty P0 m0 } end lemma extend_union {s₁ s₂ : set α} (hd : disjoint s₁ s₂) (h₁ : P s₁) (h₂ : P s₂) : extend m (s₁ ∪ s₂) = extend m s₁ + extend m s₂ := begin rw [union_eq_Union, extend_Union P0 m0 PU mU (pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩), tsum_fintype], simp end end unions variable (m) /-- Given an arbitrary function on a subset of sets, we can define the outer measure corresponding to it (this is the unique maximal outer measure that is at most `m` on the domain of `m`). -/ def induced_outer_measure : outer_measure α := outer_measure.of_function (extend m) (extend_empty P0 m0) variables {m P0 m0} include msU m_mono lemma induced_outer_measure_eq_extend' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = extend m s := of_function_eq s (λ t, extend_mono' m_mono hs) (extend_Union_le_tsum_nat' PU msU) lemma induced_outer_measure_eq' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = m s hs := (induced_outer_measure_eq_extend' PU msU m_mono hs).trans $ extend_eq _ _ lemma induced_outer_measure_eq_infi (s : set α) : induced_outer_measure m P0 m0 s = ⨅ (t : set α) (ht : P t) (h : s ⊆ t), m t ht := begin apply le_antisymm, { simp only [le_infi_iff], intros t ht, simp only [le_infi_iff], intro hs, refine le_trans (mono' _ hs) _, exact le_of_eq (induced_outer_measure_eq' _ msU m_mono _) }, { refine le_infi _, intro f, refine le_infi _, intro hf, refine le_trans _ (extend_Union_le_tsum_nat' _ msU _), refine le_infi _, intro h2f, refine infi_le_of_le _ (infi_le_of_le h2f $ infi_le _ hf) } end lemma induced_outer_measure_preimage (f : α ≃ α) (Pm : ∀ (s : set α), P (f ⁻¹' s) ↔ P s) (mm : ∀ (s : set α) (hs : P s), m (f ⁻¹' s) ((Pm _).mpr hs) = m s hs) {A : set α} : induced_outer_measure m P0 m0 (f ⁻¹' A) = induced_outer_measure m P0 m0 A := begin simp only [induced_outer_measure_eq_infi _ msU m_mono], symmetry, refine infi_congr (preimage f) f.injective.preimage_surjective _, intro s, refine infi_congr_Prop (Pm s) _, intro hs, refine infi_congr_Prop f.surjective.preimage_subset_preimage_iff _, intro h2s, exact mm s hs end lemma induced_outer_measure_exists_set {s : set α} (hs : induced_outer_measure m P0 m0 s < ∞) {ε : ℝ≥0} (hε : 0 < ε) : ∃ (t : set α) (ht : P t), s ⊆ t ∧ induced_outer_measure m P0 m0 t ≤ induced_outer_measure m P0 m0 s + ε := begin have := ennreal.lt_add_right hs (ennreal.zero_lt_coe_iff.2 hε), conv at this {to_lhs, rw induced_outer_measure_eq_infi _ msU m_mono }, simp only [infi_lt_iff] at this, rcases this with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h1t, h2t, le_trans (le_of_eq $ induced_outer_measure_eq' _ msU m_mono h1t) (le_of_lt h3t)⟩ end /-- To test whether `s` is Carathéodory-measurable we only need to check the sets `t` for which `P t` holds. See `of_function_caratheodory` for another way to show the Carathéodory-measurability of `s`. -/ lemma induced_outer_measure_caratheodory (s : set α) : (induced_outer_measure m P0 m0).caratheodory.measurable_set' s ↔ ∀ (t : set α), P t → induced_outer_measure m P0 m0 (t ∩ s) + induced_outer_measure m P0 m0 (t \ s) ≤ induced_outer_measure m P0 m0 t := begin rw is_caratheodory_iff_le, split, { intros h t ht, exact h t }, { intros h u, conv_rhs { rw induced_outer_measure_eq_infi _ msU m_mono }, refine le_infi _, intro t, refine le_infi _, intro ht, refine le_infi _, intro h2t, refine le_trans _ (le_trans (h t ht) $ le_of_eq $ induced_outer_measure_eq' _ msU m_mono ht), refine add_le_add (mono' _ $ set.inter_subset_inter_left _ h2t) (mono' _ $ diff_subset_diff_left h2t) } end end extend_set /-! If `P` is `measurable_set` for some measurable space, then we can remove some hypotheses of the above lemmas. -/ section measurable_space variables {α : Type*} [measurable_space α] variables {m : Π (s : set α), measurable_set s → ℝ≥0∞} variables (m0 : m ∅ measurable_set.empty = 0) variable (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃i, f i) (measurable_set.Union hm) = ∑'i, m (f i) (hm i)) include m0 mU lemma extend_mono {s₁ s₂ : set α} (h₁ : measurable_set s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := begin refine le_infi _, intro h₂, have := extend_union measurable_set.empty m0 measurable_set.Union mU disjoint_diff h₁ (h₂.diff h₁), rw union_diff_cancel hs at this, rw ← extend_eq m, exact le_iff_exists_add.2 ⟨_, this⟩, end lemma extend_Union_le_tsum_nat : ∀ (s : ℕ → set α), extend m (⋃i, s i) ≤ ∑'i, extend m (s i) := begin refine extend_Union_le_tsum_nat' measurable_set.Union _, intros f h, simp [Union_disjointed.symm] {single_pass := tt}, rw [mU (measurable_set.disjointed h) disjoint_disjointed], refine ennreal.tsum_le_tsum (λ i, _), rw [← extend_eq m, ← extend_eq m], exact extend_mono m0 mU (measurable_set.disjointed h _) (inter_subset_left _ _) end lemma induced_outer_measure_eq_extend {s : set α} (hs : measurable_set s) : induced_outer_measure m measurable_set.empty m0 s = extend m s := of_function_eq s (λ t, extend_mono m0 mU hs) (extend_Union_le_tsum_nat m0 mU) lemma induced_outer_measure_eq {s : set α} (hs : measurable_set s) : induced_outer_measure m measurable_set.empty m0 s = m s hs := (induced_outer_measure_eq_extend m0 mU hs).trans $ extend_eq _ _ end measurable_space namespace outer_measure variables {α : Type*} [measurable_space α] (m : outer_measure α) /-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider `m.trim`, the unique maximal outer measure less than that function. -/ def trim : outer_measure α := induced_outer_measure (λ s _, m s) measurable_set.empty m.empty theorem le_trim : m ≤ m.trim := le_of_function.mpr $ λ s, le_infi $ λ _, le_refl _ theorem trim_eq {s : set α} (hs : measurable_set s) : m.trim s = m s := induced_outer_measure_eq' measurable_set.Union (λ f hf, m.Union_nat f) (λ _ _ _ _ h, m.mono h) hs theorem trim_congr {m₁ m₂ : outer_measure α} (H : ∀ {s : set α}, measurable_set s → m₁ s = m₂ s) : m₁.trim = m₂.trim := by { unfold trim, congr, funext s hs, exact H hs } theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim := λ s, binfi_le_binfi $ λ f hs, ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _ theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔ ∀ s, measurable_set s → m₁ s ≤ m₂ s := le_of_function.trans $ forall_congr $ λ s, le_infi_iff theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : measurable_set t), m t := by { simp only [infi_comm] {single_pass := tt}, exact induced_outer_measure_eq_infi measurable_set.Union (λ f _, m.Union_nat f) (λ _ _ _ _ h, m.mono h) s } theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ measurable_set t}, m t := by simp [infi_subtype, infi_and, trim_eq_infi] theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim := le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (le_trim _) @[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 := ext $ λ s, le_antisymm (le_trans ((trim 0).mono (subset_univ s)) $ le_of_eq $ trim_eq _ measurable_set.univ) (zero_le _) theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim := begin ext1 s, simp only [trim_eq_infi', add_apply], rw ennreal.infi_add_infi, rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩, exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩, add_le_add (m₁.mono' (inter_subset_left _ _)) (m₂.mono' (inter_subset_right _ _))⟩, end theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim := λ s, by simp [trim_eq_infi]; exact λ t st ht, ennreal.tsum_le_tsum (λ i, infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht) lemma exists_measurable_superset_eq_trim (m : outer_measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ m t = m.trim s := begin simp only [trim_eq_infi], set ms := ⨅ (t : set α) (st : s ⊆ t) (ht : measurable_set t), m t, by_cases hs : ms = ∞, { simp only [hs], simp only [infi_eq_top] at hs, exact ⟨univ, subset_univ s, measurable_set.univ, hs _ (subset_univ s) measurable_set.univ⟩ }, { have : ∀ r > ms, ∃ t, s ⊆ t ∧ measurable_set t ∧ m t < r, { intros r hs, simpa [infi_lt_iff] using hs }, have : ∀ n : ℕ, ∃ t, s ⊆ t ∧ measurable_set t ∧ m t < ms + n⁻¹, { assume n, refine this _ (ennreal.lt_add_right (lt_top_iff_ne_top.2 hs) _), exact (ennreal.inv_pos.2 $ ennreal.nat_ne_top _) }, choose t hsub hm hm', refine ⟨⋂ n, t n, subset_Inter hsub, measurable_set.Inter hm, _⟩, have : tendsto (λ n : ℕ, ms + n⁻¹) at_top (𝓝 (ms + 0)), from tendsto_const_nhds.add ennreal.tendsto_inv_nat_nhds_zero, rw add_zero at this, refine le_antisymm (ge_of_tendsto' this $ λ n, _) _, { exact le_trans (m.mono' $ Inter_subset t n) (hm' n).le }, { refine infi_le_of_le (⋂ n, t n) _, refine infi_le_of_le (subset_Inter hsub) _, refine infi_le _ (measurable_set.Inter hm) } } end lemma exists_measurable_superset_of_trim_eq_zero {m : outer_measure α} {s : set α} (h : m.trim s = 0) : ∃t, s ⊆ t ∧ measurable_set t ∧ m t = 0 := begin rcases exists_measurable_superset_eq_trim m s with ⟨t, hst, ht, hm⟩, exact ⟨t, hst, ht, h ▸ hm⟩ end theorem trim_smul (c : ℝ≥0∞) (m : outer_measure α) : (c • m).trim = c • m.trim := begin ext1 s, simp only [trim_eq_infi', smul_apply], haveI : nonempty {t // s ⊆ t ∧ measurable_set t} := ⟨⟨univ, subset_univ _, measurable_set.univ⟩⟩, refine ennreal.infi_mul_left (assume hc hs, _), rw ← trim_eq_infi' at hs, simpa [and_assoc] using exists_measurable_superset_of_trim_eq_zero hs end /-- The trimmed property of a measure μ states that `μ.to_outer_measure.trim = μ.to_outer_measure`. This theorem shows that a restricted trimmed outer measure is a trimmed outer measure. -/ lemma restrict_trim {μ : outer_measure α} {s : set α} (hs : measurable_set s) : (restrict s μ).trim = restrict s μ.trim := begin apply measure_theory.outer_measure.ext, intro t, simp_rw [restrict_apply, trim_eq_infi, restrict_apply], apply le_antisymm, { simp only [le_infi_iff], intros v h_subset hv, refine infi_le_of_le (v ∪ sᶜ) _, refine infi_le_of_le _ _, { rwa [set.union_comm, ← inter_subset] }, refine infi_le_of_le (hv.union hs.compl) _, rw [union_inter_distrib_right, compl_inter_self, set.union_empty], exact μ.mono (inter_subset_left _ _) }, { simp only [le_infi_iff], intros u h_subset hu, refine infi_le_of_le (u ∩ s) _, refine infi_le_of_le (set.inter_subset_inter_left _ h_subset) _, refine infi_le_of_le (hu.inter hs) le_rfl }, end end outer_measure end measure_theory
150f5baa24d5b3291f86071a7ebccaf6a16ba586
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/fintype.lean
4961be5c4d44add3083198a3e496f9d384d5169b
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
28,308
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas data.vector2 data.equiv.encodable universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ e, match F, G, e with ⟨⟨s, nd⟩, h⟩, ⟨⟨s', nd'⟩, h'⟩, e' := begin change multiset.card s = multiset.card s' at e', revert nd nd' h h' e', refine quotient.induction_on₂ s s' (λ l₁ l₂ (nd₁ : l₁.nodup) (nd₂ : l₂.nodup) (h₁ : ∀ x, x ∈ l₁) (h₂ : ∀ x, x ∈ l₂) (e' : l₁.length = l₂.length), _), haveI := classical.dec_eq α, refine ⟨equiv.of_bijective ⟨_, _⟩⟩, { refine λ a, l₂.nth_le (l₁.index_of a) _, rw ← e', exact list.index_of_lt_length.2 (h₁ a) }, { intros a b h, simpa [h₁] using congr_arg l₁.nth (list.nodup_iff_nth_le_inj.1 nd₂ _ _ _ _ h) }, { have := classical.dec_eq β, refine λ b, ⟨l₁.nth_le (l₂.index_of b) _, _⟩, { rw e', exact list.index_of_lt_length.2 (h₂ b) }, { simp [nd₁] } } end end, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem fintype.univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem fintype.card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype instance (n : ℕ) : fintype (fin n) := ⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1), list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩, λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := by rw [fin.fintype]; simp [fintype.card, card, univ] instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.bijective.1 (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.bijective.2 (this.1 (injective_comp e.symm.bijective.1 hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.bijective.1 (this.2 (surjective_comp e.symm.bijective.2 hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive finset.sum_attach_univ] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.bijective.1 h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.bijective.1 h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.bijective.1 h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.bijective.1 $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse end fintype
968ce4956831f397541ef63aca35314e1040d83e
e21db629d2e37a833531fdcb0b37ce4d71825408
/src/use_cases/assign_mcl/proof2.lean
6b4546dca42995e1b23dc0766cb62067e8d3d9dd
[]
no_license
fischerman/GPU-transformation-verifier
614a28cb4606a05a0eb27e8d4eab999f4f5ea60c
75a5016f05382738ff93ce5859c4cfa47ccb63c1
refs/heads/master
1,586,985,789,300
1,579,290,514,000
1,579,290,514,000
165,031,073
1
0
null
null
null
null
UTF-8
Lean
false
false
7,530
lean
import mcl.defs import mcl.rhl import mcl.compute_list import mcl.ts_updates import syncablep import mcl.syncablep import mcl.lemmas import .defs open mcl open mcl.mclk open mcl.rhl open parlang open parlang.state open parlang.thread_state namespace assign_mcl namespace proof2 notation m ` & ` n ` ::= ` v := memory.update m n v notation s ` § ` f ` ⇂ ` ac := map_active_threads ac f s lemma assign_rel' : mclp_rel eq p₁ p₂ eq := begin apply rel_mclk_to_mclp, apply skip_right.mpr, apply rhl.seq, swap, apply skip_left_after.mpr, apply skip_right.mpr, apply rhl.seq, swap, -- break it down into individual proofs apply add_skip_left.mpr, apply rhl.seq, swap, { apply shared_assign_right, },{ apply shared_assign_right, }, { apply shared_assign_left, }, apply shared_assign_left', intros _ _ _ _ _ _ h hs, cases h with m₁ h, cases h with m₂ h, simp only [map_map_active_threads], have : n₁ = n₂ := begin sorry end, subst this, have hseq : s₁ = s₂ := begin sorry end, -- the proof obligation in the form of a map thread on syncable is the simple version because we never consider threads to change active state (here all threads are always active) -- the two updates store indepedently because "a" ≠ "b" -- the two updates read indepedently because they both depend on the same state (AFAIK they could still be swaped because the state is fixed) apply exists.intro _, apply exists.intro _, -- split up the proof for the individual memories split, { have : thread_state.update_shared_vars_for_expr read_tid = id := by refl, rw this, have : thread_state.update_shared_vars_for_exprs v[read_tid] = id := by refl, rw this, have : thread_state.update_shared_vars_for_expr (read_tid + (expression.literal_int 1 (show type_of (sig.val "b") = type_of (sig.val "b"), by refl))) = id := by refl, rw this, simp, -- resolve get and update (the result should only be mcl_init, literals and memory (in case of loads)) rw ← syncable_syncable', rw function.comp.assoc, rw ← ts_updates_nil (thread_state.tlocal_to_shared _ _ _ _ ∘ _), rw [ts_updates_store, ts_updates_compute, ts_updates_store], rw [← function.comp.right_id (compute _)], rw [ts_updates_compute], rw [function.comp.right_id], apply syncable'_store (show ((sig.val "a").type).dim = 1, by refl), { simp, }, { simp, }, { intros tid₁ tid₂ hneq, simp [vector.map_cons], repeat { rw vector.map_nil }, rw initial_kernel_assertion_left_thread_state h, rw initial_kernel_assertion_left_thread_state h, simp, rw ← vector.eq_one', intro a, cases tid₁, cases tid₂, have : tid₁_val = tid₂_val := begin apply a, end, subst this, contradiction, }, rw ts_updates_merge_computes_list, apply syncable'_store (show ((sig.val "b").type).dim = 1, by refl), { intro idx, have : "b" ≠ "a" := by intro; cases a, simp [this], }, { intro idx, have : "b" ≠ "a" := by intro; cases a, simp [this], }, { intros tid₁ tid₂ hneq, simp [vector.map_cons], repeat { rw vector.map_nil }, rw initial_kernel_assertion_left_thread_state h, rw initial_kernel_assertion_left_thread_state h, simp, rw ← vector.eq_one', intro a, cases tid₁, cases tid₂, have : tid₁_val = tid₂_val := begin apply a, end, subst this, contradiction, }, simp [append, list.append], apply syncable'_compute_list_syncable, exact h.left, sorry, --trivial from h sorry, --trivial from h }, split, { have : thread_state.update_shared_vars_for_expr read_tid = id := by refl, rw this, have : thread_state.update_shared_vars_for_exprs v[read_tid] = id := by refl, rw this, have : thread_state.update_shared_vars_for_expr (read_tid + (expression.literal_int 1 (show type_of (sig.val "b") = type_of (sig.val "b"), by refl))) = id := by refl, rw this, simp, -- resolve get and update (the result should only be mcl_init, literals and memory (in case of loads)) rw ← syncable_syncable', rw function.comp.assoc, rw ← ts_updates_nil (thread_state.tlocal_to_shared _ _ _ _ ∘ _), rw [ts_updates_store, ts_updates_compute, ts_updates_store], rw [← function.comp.right_id (compute _)], rw [ts_updates_compute], rw [function.comp.right_id], apply syncable'_store (show ((sig.val "b").type).dim = 1, by refl), { simp, }, { simp, }, { intros tid₁ tid₂ hneq, simp [vector.map_cons], repeat { rw vector.map_nil }, rw h.right_thread_state, rw h.right_thread_state, simp, rw ← vector.eq_one', intro a, cases tid₁, cases tid₂, have : tid₁_val = tid₂_val := begin apply a, end, subst this, contradiction, }, rw ts_updates_merge_computes_list, apply syncable'_store (show ((sig.val "a").type).dim = 1, by refl), { intro idx, have : "a" ≠ "b" := by intro; cases a, simp [this], }, { intro idx, have : "a" ≠ "b" := by intro; cases a, simp [this], }, { intros tid₁ tid₂ hneq, simp [vector.map_cons], repeat { rw vector.map_nil }, rw h.right_thread_state, rw h.right_thread_state, simp, rw ← vector.eq_one', intro a, cases tid₁, cases tid₂, have : tid₁_val = tid₂_val := begin apply a, end, subst this, contradiction, }, simp [append, list.append], apply syncable'_compute_list_syncable, exact h.right.left, sorry, --trivial from h sorry, --trivial from h }, { -- show post-condition simp [append, list.append], rw ts_update_compute_list, rw from_tlocal_comm, have := h.precondition, subst this, have := h.initial_state_eq, subst this, apply from_tlocal_eq, { intro tid, rw map_active_threads_nth_ac, rw map_active_threads_nth_ac, refl, sorry, -- trivial sorry, -- trivial }, apply from_tlocal_eq, { intro tid, rw map_active_threads_nth_ac, rw map_active_threads_nth_ac, refl, sorry, -- trivial sorry, -- trivial }, refl, }, { sorry, --trivial } end end proof2 end assign_mcl
978639234e675e6bc4a38f29fdf3cb1c6bd5a71d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/metric_space/basic.lean
3cc95442a90c6a5f4eecae6f74f9c3f2abd4f56d
[ "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
110,326
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 data.int.interval import topology.algebra.ordered.compact import topology.metric_space.emetric_space /-! # 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 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]. /-- This is an internal lemma used inside the default of `pseudo_metric_space.edist`. -/ private theorem pseudo_metric_space.dist_nonneg' {α} {x y : α} (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): 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 /-- This tactic is used to populate `pseudo_metric_space.edist_dist` when the default `edist` is used. -/ protected meta def pseudo_metric_space.edist_dist_tac : tactic unit := tactic.intros >> `[exact (ennreal.of_real_eq_coe_nnreal _).symm <|> control_laws_tac] /-- 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, @coe (ℝ≥0) _ _ ⟨dist x y, pseudo_metric_space.dist_nonneg' _ ‹_› ‹_› ‹_›⟩) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . pseudo_metric_space.edist_dist_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, refine forall₂_congr (λ x x_in, _), erw (has_basis_binfi_principal _ nonempty_Ioi).mem_iff, { refine exists₂_congr (λ ε ε_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, 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_rfl ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico 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)) := nat.Ico_zero_eq_range ▸ 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.mem_Ico.1 hk).1 (finset.mem_Ico.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 := nat.Ico_zero_eq_range ▸ 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 : α) : |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 := pseudo_metric_space.dist_nonneg' dist dist_self dist_comm dist_triangle @[simp] theorem abs_dist {a b : α} : |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_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ := (edist_dist x y).symm ▸ ennreal.of_real_lt_top /--In a pseudometric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne /--`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 sphere_eq_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) : sphere x ε = ∅ := begin refine set.eq_empty_iff_forall_not_mem.mpr (λ y hy, _), rw [mem_sphere, ←subsingleton.elim x y, dist_self x] at hy, exact hε.symm hy, end theorem sphere_is_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) : is_empty (sphere x ε) := by simp only [sphere_eq_empty_of_subsingleton hε, set.has_emptyc.emptyc.is_empty α] 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 lemma closed_ball_disjoint_ball (x y : α) (rx ry : ℝ) (h : rx + ry ≤ dist x y) : disjoint (closed_ball x rx) (ball y ry) := begin rw disjoint_left, intros a ax ay, apply lt_irrefl (dist x y), calc dist x y ≤ dist a x + dist a y : dist_triangle_left _ _ _ ... < rx + ry : add_lt_add_of_le_of_lt (mem_closed_ball.1 ax) (mem_ball.1 ay) ... ≤ dist x y : h end lemma ball_disjoint_ball (x y : α) (rx ry : ℝ) (h : rx + ry ≤ dist x y) : disjoint (ball x rx) (ball y ry) := (closed_ball_disjoint_ball x y rx ry h).mono_left ball_subset_closed_ball lemma closed_ball_disjoint_closed_ball {x y : α} {rx ry : ℝ} (h : rx + ry < dist x y) : disjoint (closed_ball x rx) (closed_ball y ry) := begin rw disjoint_left, intros a ax ay, apply lt_irrefl (dist x y), calc dist x y ≤ dist a x + dist a y : dist_triangle_left _ _ _ ... ≤ rx + ry : add_le_add ax ay ... < dist x y : h end 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 lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... < ε₁ + dist x y : add_lt_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... ≤ ε₁ + dist x y : add_le_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_ball (h : ε₁ < ε₂) : closed_ball x ε₁ ⊆ ball x ε₂ := λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball (h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y ≤ ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2 lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2 lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := begin rw inter_comm at h, rw [add_comm, dist_comm], exact dist_lt_add_of_nonempty_closed_ball_inter_ball h end lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := dist_lt_add_of_nonempty_closed_ball_inter_ball $ h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl) @[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) lemma Union_inter_closed_ball_nat (s : set α) (x : α) : (⋃ (n : ℕ), s ∩ closed_ball x n) = s := by rw [← inter_Union, Union_closed_ball_nat, inter_univ] 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⟩ /-- If a property holds for all points in closed balls of arbitrarily large radii, then it holds for all points. -/ lemma forall_of_forall_mem_closed_ball (p : α → Prop) (x : α) (H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ closed_ball x R, p y) (y : α) : p y := begin obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x ≤ R), ∀ (z : α), z ∈ closed_ball x R → p z := frequently_iff.1 H (Ici_mem_at_top (dist y x)), exact h _ hR end /-- If a property holds for all points in balls of arbitrarily large radii, then it holds for all points. -/ lemma forall_of_forall_mem_ball (p : α → Prop) (x : α) (H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ ball x R, p y) (y : α) : p y := begin obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x < R), ∀ (z : α), z ∈ ball x R → p z := frequently_iff.1 H (Ioi_mem_at_top (dist y x)), exact h _ hR end 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, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩ /-- A pseudometric 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_ball.mem_nhds (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 closed_ball_mem_nhds_of_mem {x c : α} {ε : ℝ} (h : x ∈ ball c ε) : closed_ball c ε ∈ 𝓝 x := mem_of_superset (is_open_ball.mem_nhds h) 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 $ forall₂_congr $ λ ε hε, exists₂_congr $ λ δ hδ, forall_congr $ λ x, by simp; itauto 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_max_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 : pseudo_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. -/ noncomputable instance real.pseudo_metric_space : pseudo_metric_space ℝ := { dist := λx y, |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 = |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 = |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_Ioo (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_Icc {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] 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] theorem real.Icc_eq_closed_ball (x y : ℝ) : Icc x y = closed_ball ((x + y) / 2) ((y - x) / 2) := by rw [real.closed_ball_eq_Icc, ← 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] section metric_ordered variables [preorder α] [compact_Icc_space α] 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 /-- If `u` is a neighborhood of `x`, then for small enough `r`, the closed ball `closed_ball x r` is contained in `u`. -/ lemma eventually_closed_ball_subset {x : α} {u : set α} (hu : u ∈ 𝓝 x) : ∀ᶠ r in 𝓝 (0 : ℝ), closed_ball x r ⊆ u := begin obtain ⟨ε, εpos, hε⟩ : ∃ ε (hε : 0 < ε), closed_ball x ε ⊆ u := nhds_basis_closed_ball.mem_iff.1 hu, have : Iic ε ∈ 𝓝 (0 : ℝ) := Iic_mem_nhds εpos, filter_upwards [this] with _ hr using subset.trans (closed_ball_subset_closed_ball hr) hε, end 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 hm n hn, calc dist (s m) (s n) ≤ b N : h m n N hm hn ... ≤ |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_rfl, le_rfl⟩, 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 noncomputable instance : pseudo_metric_space ℝ≥0 := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(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 [tsub_eq_zero_iff_le.2 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 @[simp] lemma nnreal.nndist_zero_eq_val (z : ℝ≥0) : nndist 0 z = z := by simp only [nnreal.nndist_eq, max_eq_right, tsub_zero, zero_tsub, zero_le'] @[simp] lemma nnreal.nndist_zero_eq_val' (z : ℝ≥0) : nndist z 0 = z := by { rw nndist_comm, exact nnreal.nndist_zero_eq_val z, } lemma nnreal.le_add_nndist (a b : ℝ≥0) : a ≤ b + nndist a b := begin suffices : (a : ℝ) ≤ (b : ℝ) + (dist a b), { exact nnreal.coe_le_coe.mp this, }, linarith [le_of_abs_le (by refl : abs (a-b : ℝ) ≤ (dist a b))], end end nnreal section prod noncomputable 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 ×ˢ 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 ×ˢ 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. -/ noncomputable 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 nndist_pi_le_iff {f g : Πb, π b} {r : ℝ≥0} : nndist f g ≤ r ↔ ∀b, nndist (f b) (g b) ≤ r := by simp [nndist_pi_def] 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, exact nndist_pi_le_iff 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] @[simp] lemma fin.nndist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*} [Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) : nndist (i.insert_nth x f) (i.insert_nth y g) = max (nndist x y) (nndist f g) := eq_of_forall_ge_iff $ λ c, by simp [nndist_pi_le_iff, i.forall_iff_succ_above] @[simp] lemma fin.dist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*} [Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) : dist (i.insert_nth x f) (i.insert_nth y g) = max (dist x y) (dist f g) := by simp only [dist_nndist, fin.nndist_insert_nth_insert_nth, nnreal.coe_max] lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ dist x' y' := begin refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_interval _ _).trans (dist_le_pi_dist _ _ b)); refine Icc_subset_interval _, exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩] end 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 := (is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r)) export proper_space (is_compact_closed_ball) /-- 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 (is_compact_closed_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, is_compact_closed_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, is_compact_closed_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_rfl).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, is_compact_closed_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 yt x xt).le), rcases (compact_iff_totally_bounded_complete.1 (is_compact_closed_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).is_compact_closed_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 (is_compact_closed_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 (exists_lt 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, Union₂_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.mono (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x hx y hy, hC x (incl hx) y (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y hy z 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.mono ball_subset_closed_ball /-- Spheres are bounded -/ lemma bounded_sphere : bounded (sphere x r) := bounded_closed_ball.mono sphere_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 hy x hx) _⟩ } }, { exact bounded_closed_ball.mono 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.subset_ball_lt (h : bounded s) (a : ℝ) (c : α) : ∃ r, a < r ∧ s ⊆ closed_ball c r := begin rcases h.subset_ball c with ⟨r, hr⟩, refine ⟨max r (a+1), lt_of_lt_of_le (by linarith) (le_max_right _ _), _⟩, exact subset.trans hr (closed_ball_subset_closed_ball (le_max_left _ _)) end lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) := let ⟨C, h⟩ := h in ⟨C, λ a ha b hb, (is_closed_le' C).closure_subset $ map_mem_closure2 continuous_dist ha hb $ ball_mem_comm.mp h⟩ alias bounded_closure_of_bounded ← metric.bounded.closure @[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s := ⟨λ h, h.mono subset_closure, λ h, h.closure⟩ /-- The union of two bounded sets is bounded. -/ lemma bounded.union (hs : bounded s) (ht : bounded t) : bounded (s ∪ t) := begin 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 /-- The union of two sets is bounded iff each of the sets is bounded. -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λ h, ⟨h.mono (by simp), h.mono (by simp)⟩, λ h, h.1.union h.2⟩ /-- 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.mono 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⟩ lemma bounded_range_of_tendsto_cofinite_uniformity {f : β → α} (hf : tendsto (prod.map f f) (cofinite ×ᶠ cofinite) (𝓤 α)) : bounded (range f) := begin rcases (has_basis_cofinite.prod_self.tendsto_iff uniformity_basis_dist).1 hf 1 zero_lt_one with ⟨s, hsf, hs1⟩, rw [← image_univ, ← union_compl_self s, image_union, bounded_union], use [(hsf.image f).bounded, 1], rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, exact le_of_lt (hs1 (x, y) ⟨hx, hy⟩) end lemma bounded_range_of_cauchy_map_cofinite {f : β → α} (hf : cauchy (map f cofinite)) : bounded (range f) := bounded_range_of_tendsto_cofinite_uniformity $ (cauchy_map_iff.1 hf).2 lemma _root_.cauchy_seq.bounded_range {f : ℕ → α} (hf : cauchy_seq f) : bounded (range f) := bounded_range_of_cauchy_map_cofinite $ by rwa nat.cofinite_eq_at_top lemma bounded_range_of_tendsto_cofinite {f : β → α} {a : α} (hf : tendsto f cofinite (𝓝 a)) : bounded (range f) := bounded_range_of_tendsto_cofinite_uniformity $ (hf.prod_map hf).mono_right $ nhds_prod_eq.symm.trans_le (nhds_le_uniformity a) /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := compact_univ.bounded.mono (subset_univ _) lemma bounded_range_of_tendsto {α : Type*} [pseudo_metric_space α] (u : ℕ → α) {x : α} (hu : tendsto u at_top (𝓝 x)) : bounded (range u) := hu.cauchy_seq.bounded_range /-- The **Heine–Borel theorem**: In a proper space, a closed bounded set is compact. -/ lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) : is_compact s := begin unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) }, { exact is_compact_empty }, { rcases hb.subset_ball x with ⟨r, hr⟩, exact compact_of_is_closed_subset (is_compact_closed_ball x r) hc hr } end /-- The **Heine–Borel theorem**: In a proper space, the closure of a bounded set is compact. -/ lemma bounded.is_compact_closure [proper_space α] (h : bounded s) : is_compact (closure s) := is_compact_of_is_closed_bounded is_closed_closure h.closure /-- The **Heine–Borel theorem**: In a proper Hausdorff 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⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩ lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) := ⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩ section conditionally_complete_linear_order variables [preorder α] [compact_Icc_space α] 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.mono (λ 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 -/ noncomputable 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 hC) (λ h, ⟨diam s, λ x hx y 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 lemma ediam_univ_eq_top_iff_noncompact [proper_space α] : emetric.diam (univ : set α) = ∞ ↔ noncompact_space α := by rw [← not_compact_space_iff, compact_space_iff_bounded_univ, bounded_iff_ediam_ne_top, not_not] @[simp] lemma ediam_univ_of_noncompact [proper_space α] [noncompact_space α] : emetric.diam (univ : set α) = ∞ := ediam_univ_eq_top_iff_noncompact.mpr ‹_› @[simp] lemma diam_univ_of_noncompact [proper_space α] [noncompact_space α] : diam (univ : set α) = 0 := by simp [diam] /-- 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.mono 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.mono (subset_union_left _ _), have ht : bounded t, from H.mono (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 lemma diam_le_of_subset_closed_ball {r : ℝ} (hr : 0 ≤ r) (h : s ⊆ closed_ball x r) : diam s ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg zero_le_two hr) $ λa ha b hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add (h ha) (h hb) ... = 2 * r : by simp [mul_two, mul_comm] /-- 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_subset_closed_ball h subset.rfl /-- 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 := diam_le_of_subset_closed_ball h ball_subset_closed_ball 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, set.finite_Ioo], 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 @[simp] lemma sphere_zero : sphere x 0 = {x} := set.ext $ λ y, dist_eq_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, } lemma is_closed_of_pairwise_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε) (hs : s.pairwise (λ x y, ε ≤ dist x y)) : is_closed s := is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α] {ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : closed_embedding f := closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf /-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then `f` is a uniform embedding with respect to the discrete uniformity on `β`. -/ lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f := uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf 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. -/ noncomputable 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 noncomputable instance : metric_space ℝ≥0 := subtype.metric_space end nnreal section prod noncomputable 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. -/ noncomputable 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 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
fd92b78de7811f16665d6895c63c42e4e7187ee5
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/number_theory/class_number/admissible_abs.lean
bbd667ec248eb1a9b161616349d98d74c4e5aefb
[ "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
2,561
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import number_theory.class_number.admissible_absolute_value /-! # Admissible absolute value on the integers This file defines an admissible absolute value `absolute_value.abs_is_admissible` which we use to show the class number of the ring of integers of a number field is finite. ## Main results * `absolute_value.abs_is_admissible` shows the "standard" absolute value on `ℤ`, mapping negative `x` to `-x`, is admissible. -/ namespace absolute_value open int /-- We can partition a finite family into `partition_card ε` sets, such that the remainders in each set are close together. -/ lemma exists_partition_int (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : ℤ} (hb : b ≠ 0) (A : fin n → ℤ) : ∃ (t : fin n → fin ⌈1 / ε⌉₊), ∀ i₀ i₁, t i₀ = t i₁ → ↑(abs (A i₁ % b - A i₀ % b)) < abs b • ε := begin have hb' : (0 : ℝ) < ↑(abs b) := int.cast_pos.mpr (abs_pos.mpr hb), have hbε : 0 < abs b • ε, { rw algebra.smul_def, exact mul_pos hb' hε }, have hfloor : ∀ i, 0 ≤ floor ((A i % b : ℤ) / (abs b • ε) : ℝ), { intro i, exact floor_nonneg.mpr (div_nonneg (cast_nonneg.mpr (mod_nonneg _ hb)) hbε.le) }, refine ⟨λ i, ⟨nat_abs (floor ((A i % b : ℤ) / (abs b • ε) : ℝ)), _⟩, _⟩, { rw [← coe_nat_lt, nat_abs_of_nonneg (hfloor i), floor_lt], apply lt_of_lt_of_le _ (nat.le_ceil _), rw [algebra.smul_def, ring_hom.eq_int_cast, ← div_div_eq_div_mul, div_lt_div_right hε, div_lt_iff hb', one_mul, cast_lt], exact int.mod_lt _ hb }, intros i₀ i₁ hi, have hi : (⌊↑(A i₀ % b) / abs b • ε⌋.nat_abs : ℤ) = ⌊↑(A i₁ % b) / abs b • ε⌋.nat_abs := congr_arg (coe : ℕ → ℤ) (subtype.mk_eq_mk.mp hi), rw [nat_abs_of_nonneg (hfloor i₀), nat_abs_of_nonneg (hfloor i₁)] at hi, have hi := abs_sub_lt_one_of_floor_eq_floor hi, rw [abs_sub_comm, ← sub_div, abs_div, abs_of_nonneg hbε.le, div_lt_iff hbε, one_mul] at hi, rwa [int.cast_abs, int.cast_sub] end /-- `abs : ℤ → ℤ` is an admissible absolute value -/ noncomputable def abs_is_admissible : is_admissible absolute_value.abs := { card := λ ε, ⌈1 / ε⌉₊, exists_partition' := λ n ε hε b hb, exists_partition_int n hε hb, .. absolute_value.abs_is_euclidean } noncomputable instance : inhabited (is_admissible absolute_value.abs) := ⟨abs_is_admissible⟩ end absolute_value
b95aaf7c72fe0edeb407986192735a86bce25f8d
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/Script.lean
9d94e3a63ef0483532920d121f393919fd349a72
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
232
lean
import Papyrus.Script.Label import Papyrus.Script.Module import Papyrus.Script.Function import Papyrus.Script.Instructions import Papyrus.Script.Type import Papyrus.Script.Dump import Papyrus.Script.Verify import Papyrus.Script.Jit
def5cd7ccf627e4150c1220370ffea9f0156382b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/opposites.lean
5d65f5512b9d5603b1918b91a7133a9df8ee762c
[ "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,164
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.opposite import algebra.field /-! # Algebraic operations on `αᵒᵖ` -/ namespace opposite universes u variables (α : Type u) instance [has_add α] : has_add (opposite α) := { add := λ x y, op (unop x + unop y) } instance [add_semigroup α] : add_semigroup (opposite α) := { add_assoc := λ x y z, unop_injective $ add_assoc (unop x) (unop y) (unop z), .. opposite.has_add α } instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup (opposite α) := { add_left_cancel := λ x y z H, unop_injective $ add_left_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup (opposite α) := { add_right_cancel := λ x y z H, unop_injective $ add_right_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_comm_semigroup α] : add_comm_semigroup (opposite α) := { add_comm := λ x y, unop_injective $ add_comm (unop x) (unop y), .. opposite.add_semigroup α } instance [has_zero α] : has_zero (opposite α) := { zero := op 0 } instance [nontrivial α] : nontrivial (opposite α) := let ⟨x, y, h⟩ := exists_pair_ne α in nontrivial_of_ne (op x) (op y) (op_injective.ne h) section local attribute [reducible] opposite @[simp] lemma unop_eq_zero_iff [has_zero α] (a : αᵒᵖ) : a.unop = (0 : α) ↔ a = (0 : αᵒᵖ) := iff.refl _ @[simp] lemma op_eq_zero_iff [has_zero α] (a : α) : op a = (0 : αᵒᵖ) ↔ a = (0 : α) := iff.refl _ end instance [add_monoid α] : add_monoid (opposite α) := { zero_add := λ x, unop_injective $ zero_add $ unop x, add_zero := λ x, unop_injective $ add_zero $ unop x, .. opposite.add_semigroup α, .. opposite.has_zero α } instance [add_comm_monoid α] : add_comm_monoid (opposite α) := { .. opposite.add_monoid α, .. opposite.add_comm_semigroup α } instance [has_neg α] : has_neg (opposite α) := { neg := λ x, op $ -(unop x) } instance [add_group α] : add_group (opposite α) := { add_left_neg := λ x, unop_injective $ add_left_neg $ unop x, .. opposite.add_monoid α, .. opposite.has_neg α } instance [add_comm_group α] : add_comm_group (opposite α) := { .. opposite.add_group α, .. opposite.add_comm_monoid α } instance [has_mul α] : has_mul (opposite α) := { mul := λ x y, op (unop y * unop x) } instance [semigroup α] : semigroup (opposite α) := { mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. opposite.has_mul α } instance [right_cancel_semigroup α] : left_cancel_semigroup (opposite α) := { mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H, .. opposite.semigroup α } instance [left_cancel_semigroup α] : right_cancel_semigroup (opposite α) := { mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H, .. opposite.semigroup α } instance [comm_semigroup α] : comm_semigroup (opposite α) := { mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x), .. opposite.semigroup α } instance [has_one α] : has_one (opposite α) := { one := op 1 } section local attribute [reducible] opposite @[simp] lemma unop_eq_one_iff [has_one α] (a : αᵒᵖ) : a.unop = 1 ↔ a = 1 := iff.refl _ @[simp] lemma op_eq_one_iff [has_one α] (a : α) : op a = 1 ↔ a = 1 := iff.refl _ end instance [monoid α] : monoid (opposite α) := { one_mul := λ x, unop_injective $ mul_one $ unop x, mul_one := λ x, unop_injective $ one_mul $ unop x, .. opposite.semigroup α, .. opposite.has_one α } instance [comm_monoid α] : comm_monoid (opposite α) := { .. opposite.monoid α, .. opposite.comm_semigroup α } instance [has_inv α] : has_inv (opposite α) := { inv := λ x, op $ (unop x)⁻¹ } instance [group α] : group (opposite α) := { mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x, .. opposite.monoid α, .. opposite.has_inv α } instance [comm_group α] : comm_group (opposite α) := { .. opposite.group α, .. opposite.comm_monoid α } instance [distrib α] : distrib (opposite α) := { left_distrib := λ x y z, unop_injective $ add_mul (unop y) (unop z) (unop x), right_distrib := λ x y z, unop_injective $ mul_add (unop z) (unop x) (unop y), .. opposite.has_add α, .. opposite.has_mul α } instance [semiring α] : semiring (opposite α) := { zero_mul := λ x, unop_injective $ mul_zero $ unop x, mul_zero := λ x, unop_injective $ zero_mul $ unop x, .. opposite.add_comm_monoid α, .. opposite.monoid α, .. opposite.distrib α } instance [ring α] : ring (opposite α) := { .. opposite.add_comm_group α, .. opposite.monoid α, .. opposite.semiring α } instance [comm_ring α] : comm_ring (opposite α) := { .. opposite.ring α, .. opposite.comm_semigroup α } instance [integral_domain α] : integral_domain (opposite α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)), or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_injective H) (λ hy, or.inr $ unop_injective $ hy) (λ hx, or.inl $ unop_injective $ hx), .. opposite.comm_ring α, .. opposite.nontrivial α } instance [field α] : field (opposite α) := { mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ λ hx', hx $ unop_injective hx', inv_zero := unop_injective inv_zero, .. opposite.comm_ring α, .. opposite.has_inv α, .. opposite.nontrivial α } @[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl @[simp] lemma unop_zero [has_zero α] : unop (0 : αᵒᵖ) = 0 := rfl @[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl @[simp] lemma unop_one [has_one α] : unop (1 : αᵒᵖ) = 1 := rfl variable {α} @[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl @[simp] lemma unop_add [has_add α] (x y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl @[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl @[simp] lemma unop_neg [has_neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl @[simp] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl @[simp] lemma unop_mul [has_mul α] (x y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl @[simp] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl @[simp] lemma unop_inv [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl @[simp] lemma op_sub [add_group α] (x y : α) : op (x - y) = op x - op y := rfl @[simp] lemma unop_sub [add_group α] (x y : αᵒᵖ) : unop (x - y) = unop x - unop y := rfl /-- The function `op` is a homomorphism of additive commutative monoids. -/ def op_add_hom [add_comm_monoid α] : α →+ αᵒᵖ := ⟨op, op_zero α, op_add⟩ /-- The function `unop` is a homomorphism of additive commutative monoids. -/ def unop_add_hom [add_comm_monoid α] : αᵒᵖ →+ α := ⟨unop, unop_zero α, unop_add⟩ @[simp] lemma coe_op_add_hom [add_comm_monoid α] : (op_add_hom : α → αᵒᵖ) = op := rfl @[simp] lemma coe_unop_add_hom [add_comm_monoid α] : (unop_add_hom : αᵒᵖ → α) = unop := rfl end opposite
80c1531b6a9e80e5de383f9e72d5e55c0634b513
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Std/Data/DList.lean
970f668ab9ee12980c2ee4114dd69824f4b0556b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,726
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace Std universe u /-- A difference List is a Function that, given a List, returns the original contents of the difference List prepended to the given List. This structure supports `O(1)` `append` and `concat` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ structure DList (α : Type u) where apply : List α → List α invariant : ∀ l, apply l = apply [] ++ l namespace DList variable {α : Type u} open List def ofList (l : List α) : DList α := ⟨(l ++ ·), fun t => by simp⟩ def empty : DList α := ⟨id, fun t => rfl⟩ instance : EmptyCollection (DList α) := ⟨DList.empty⟩ def toList : DList α → List α | ⟨f, h⟩ => f [] def singleton (a : α) : DList α := { apply := fun t => a :: t, invariant := fun t => rfl } def cons : α → DList α → DList α | a, ⟨f, h⟩ => { apply := fun t => a :: f t, invariant := by intro t; simp; rw [h] } def append : DList α → DList α → DList α | ⟨f, h₁⟩, ⟨g, h₂⟩ => { apply := f ∘ g, invariant := by intro t show f (g t) = (f (g [])) ++ t rw [h₁ (g t), h₂ t, ← append_assoc (f []) (g []) t, ← h₁ (g [])] } def push : DList α → α → DList α | ⟨f, h⟩, a => { apply := fun t => f (a :: t), invariant := by intro t show f (a :: t) = f (a :: nil) ++ t rw [h [a], h (a::t), append_assoc (f []) [a] t] rfl } instance : Append (DList α) := ⟨DList.append⟩ end DList end Std
6edae3c2b244040b47f90a607c1404fa231ac00a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/big_operators/finsupp.lean
4160d833969b68e8f01972995b58899136b69b56
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
22,236
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 data.finsupp.defs import algebra.big_operators.pi import algebra.big_operators.ring import algebra.big_operators.order /-! # Big operators for finsupps This file contains theorems relevant to big operators in finitely supported functions. -/ noncomputable theory open finset function open_locale classical big_operators variables {α ι γ A B C : Type*} [add_comm_monoid A] [add_comm_monoid B] [add_comm_monoid C] variables {t : ι → A → C} (h0 : ∀ i, t i 0 = 0) (h1 : ∀ i x y, t i (x + y) = t i x + t i y) variables {s : finset α} {f : α → (ι →₀ A)} (i : ι) variables (g : ι →₀ A) (k : ι → A → γ → B) (x : γ) variables {β M M' N P G H R S : Type*} namespace finsupp /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive "`sum f g` is the sum of `g a (f a)` over the support of `f`. "] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } /-- Taking a product over `f : α →₀ M` is the same as multiplying the value on a single element `y ∈ f.support` by the product over `erase y f`. -/ @[to_additive /-" Taking a sum over over `f : α →₀ M` is the same as adding the value on a single element `y ∈ f.support` to the sum over `erase y f`. "-/] lemma mul_prod_erase (f : α →₀ M) (y : α) (g : α → M → N) (hyf : y ∈ f.support) : g y (f y) * (erase y f).prod g = f.prod g := begin rw [finsupp.prod, finsupp.prod, ←finset.mul_prod_erase _ _ hyf, finsupp.support_erase, finset.prod_congr rfl], intros h hx, rw finsupp.erase_ne (ne_of_mem_erase hx), end /-- Generalization of `finsupp.mul_prod_erase`: if `g` maps a second argument of 0 to 1, then its product over `f : α →₀ M` is the same as multiplying the value on any element `y : α` by the product over `erase y f`. -/ @[to_additive /-" Generalization of `finsupp.add_sum_erase`: if `g` maps a second argument of 0 to 0, then its sum over `f : α →₀ M` is the same as adding the value on any element `y : α` to the sum over `erase y f`. "-/] lemma mul_prod_erase' (f : α →₀ M) (y : α) (g : α → M → N) (hg : ∀ (i : α), g i 0 = 1) : g y (f y) * (erase y f).prod g = f.prod g := begin classical, by_cases hyf : y ∈ f.support, { exact finsupp.mul_prod_erase f y g hyf }, { rw [not_mem_support_iff.mp hyf, hg y, erase_of_not_mem_support hyf, one_mul] }, end @[to_additive] lemma _root_.submonoid_class.finsupp_prod_mem {S : Type*} [set_like S N] [submonoid_class S N] (s : S) (f : α →₀ M) (g : α → M → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ s) : f.prod g ∈ s := prod_mem $ λ i hi, h _ (finsupp.mem_support_iff.mp hi) @[to_additive] lemma prod_congr {f : α →₀ M} {g1 g2 : α → M → N} (h : ∀ x ∈ f.support, g1 x (f x) = g2 x (f x)) : f.prod g1 = f.prod g2 := finset.prod_congr rfl h end sum_prod end finsupp @[to_additive] lemma map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] {H : Type*} [monoid_hom_class H N P] (h : H) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_prod h _ _ /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_finsupp_sum` instead."] protected lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_finsupp_sum` instead."] protected lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g /-- Deprecated, use `_root_.map_finsupp_sum` instead. -/ protected lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := map_finsupp_sum h f g /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ protected lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_finset_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s (single_zero _) $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 end finsupp namespace finsupp lemma finset_sum_apply [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) (a : α) : (∑ i in S, f i) a = ∑ i in S, f i a := (apply_add_hom a : (α →₀ N) →+ _).map_sum _ _ @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := finset_sum_apply _ _ _ lemma coe_finset_sum [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) : ⇑(∑ i in S, f i) = ∑ i in S, f i := (coe_fn_add_hom : (α →₀ N) →+ _).map_sum _ _ lemma coe_sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → β →₀ N) : ⇑(f.sum g) = f.sum (λ a₁ b, g a₁ b) := coe_finset_sum _ _ lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] lemma support_finset_sum [decidable_eq β] [add_comm_monoid M] {s : finset α} {f : α → (β →₀ M)} : (finset.sum s f).support ⊆ s.bUnion (λ x, (f x).support) := begin rw ←finset.sup_eq_bUnion, induction s using finset.cons_induction_on with a s ha ih, { refl }, { rw [finset.sum_cons, finset.sup_cons], exact support_add.trans (finset.union_subset_union (finset.subset.refl _) ih), }, end @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (map_prod ((monoid_hom.id G)⁻¹) _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib /-- Taking the product under `h` is an additive-to-multiplicative homomorphism of finsupps, if `h` is an additive-to-multiplicative homomorphism on the support. This is a more general version of `finsupp.prod_add_index'`; the latter has simpler hypotheses. -/ @[to_additive "Taking the product under `h` is an additive homomorphism of finsupps, if `h` is an additive homomorphism on the support. This is a more general version of `finsupp.sum_add_index'`; the latter has simpler hypotheses."] lemma prod_add_index [add_zero_class M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀ a ∈ f.support ∪ g.support, h a 0 = 1) (h_add : ∀ (a ∈ f.support ∪ g.support) b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := begin rw [finsupp.prod_of_support_subset f (subset_union_left _ g.support) h h_zero, finsupp.prod_of_support_subset g (subset_union_right f.support _) h h_zero, ←finset.prod_mul_distrib, finsupp.prod_of_support_subset (f + g) finsupp.support_add h h_zero], exact finset.prod_congr rfl (λ x hx, (by apply h_add x hx)), end /-- Taking the product under `h` is an additive-to-multiplicative homomorphism of finsupps, if `h` is an additive-to-multiplicative homomorphism. This is a more specialized version of `finsupp.prod_add_index` with simpler hypotheses. -/ @[to_additive "Taking the sum under `h` is an additive homomorphism of finsupps, if `h` is an additive homomorphism. This is a more specific version of `finsupp.sum_add_index` with simpler hypotheses."] lemma prod_add_index' [add_zero_class M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := prod_add_index (λ a ha, h_zero a) (λ a ha, h_add a) @[simp] lemma sum_hom_add_index [add_zero_class M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index' (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_hom_add_index [add_zero_class M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index' (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_zero_class M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index' (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma sum_univ_single [add_comm_monoid M] [fintype α] (i : α) (m : M) : ∑ (j : α), (single i m) j = m := by simp [single] @[simp] lemma sum_univ_single' [add_comm_monoid M] [fintype α] (i : α) (m : M) : ∑ (j : α), (single j m) i = m := by simp [single] @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index' h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index' h₀ h₁, ih] lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [add_comm_monoid M] {g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) : (∑ i in s, g i).support = s.bUnion (λ i, (g i).support) := begin apply finset.induction_on s, { simp }, { intros i s hi, simp only [hi, sum_insert, not_false_iff, bUnion_insert], intro hs, rw [finsupp.support_add_eq, hs], rw [hs], intros x hx, simp only [mem_bUnion, exists_prop, inf_eq_inter, ne.def, mem_inter] at hx, obtain ⟨hxi, j, hj, hxj⟩ := hx, have hn : i ≠ j := λ H, hi (H.symm ▸ hj), apply h _ _ hn, simp [hxi, hxj] } end lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (multiset.map_add_monoid_hom m).map_sum _ f.support lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (multiset.sum_add_monoid_hom : multiset N →+ N).map_sum _ f.support /-- For disjoint `f1` and `f2`, and function `g`, the product of the products of `g` over `f1` and `f2` equals the product of `g` over `f1 + f2` -/ @[to_additive "For disjoint `f1` and `f2`, and function `g`, the sum of the sums of `g` over `f1` and `f2` equals the sum of `g` over `f1 + f2`"] lemma prod_add_index_of_disjoint [add_comm_monoid M] {f1 f2 : α →₀ M} (hd : disjoint f1.support f2.support) {β : Type*} [comm_monoid β] (g : α → M → β) : (f1 + f2).prod g = f1.prod g * f2.prod g := have ∀ {f1 f2 : α →₀ M}, disjoint f1.support f2.support → ∏ x in f1.support, g x (f1 x + f2 x) = f1.prod g := λ f1 f2 hd, finset.prod_congr rfl (λ x hx, by simp only [not_mem_support_iff.mp (disjoint_left.mp hd hx), add_zero]), by simp_rw [← this hd, ← this hd.symm, add_comm (f2 _), finsupp.prod, support_add_eq hd, prod_union hd, add_apply] lemma prod_dvd_prod_of_subset_of_dvd [add_comm_monoid M] [comm_monoid N] {f1 f2 : α →₀ M} {g1 g2 : α → M → N} (h1 : f1.support ⊆ f2.support) (h2 : ∀ (a : α), a ∈ f1.support → g1 a (f1 a) ∣ g2 a (f2 a)) : f1.prod g1 ∣ f2.prod g2 := begin simp only [finsupp.prod, finsupp.prod_mul], rw [←sdiff_union_of_subset h1, prod_union sdiff_disjoint], apply dvd_mul_of_dvd_right, apply prod_dvd_prod_of_dvd, exact h2, end end finsupp theorem finset.sum_apply' : (∑ k in s, f k) i = ∑ k in s, f k i := (finsupp.apply_add_hom i : (ι →₀ A) →+ A).map_sum f s theorem finsupp.sum_apply' : g.sum k x = g.sum (λ i b, k i b x) := finset.sum_apply _ _ _ section include h0 h1 open_locale classical theorem finsupp.sum_sum_index' : (∑ x in s, f x).sum t = ∑ x in s, (f x).sum t := finset.induction_on s rfl $ λ a s has ih, by simp_rw [finset.sum_insert has, finsupp.sum_add_index' h0 h1, ih] end section variables [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] lemma finsupp.sum_mul (b : S) (s : α →₀ R) {f : α → R → S} : (s.sum f) * b = s.sum (λ a c, (f a c) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma finsupp.mul_sum (b : S) (s : α →₀ R) {f : α → R → S} : b * (s.sum f) = s.sum (λ a c, b * (f a c)) := by simp only [finsupp.sum, finset.mul_sum] end namespace nat /-- If `0 : ℕ` is not in the support of `f : ℕ →₀ ℕ` then `0 < ∏ x in f.support, x ^ (f x)`. -/ lemma prod_pow_pos_of_zero_not_mem_support {f : ℕ →₀ ℕ} (hf : 0 ∉ f.support) : 0 < f.prod pow := finset.prod_pos (λ a ha, pos_iff_ne_zero.mpr (pow_ne_zero _ (λ H, by {subst H, exact hf ha}))) end nat
6d671bd284704daa4eebbbcc8918822a295dda88
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/archive/100-theorems-list/73_ascending_descending_sequences.lean
8791aeb18cb8284c7438c3f88bbe91bad133b45f
[ "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
8,134
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import tactic.basic import data.fintype.basic /-! # Erdős–Szekeres theorem This file proves Theorem 73 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also known as the Erdős–Szekeres theorem: given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. We use the proof outlined at https://en.wikipedia.org/wiki/Erdos-Szekeres_theorem#Pigeonhole_principle. ## Tags sequences, increasing, decreasing, Ramsey, Erdos-Szekeres, Erdős–Szekeres, Erdős-Szekeres -/ variables {α : Type*} [linear_order α] {β : Type*} open function finset open_locale classical /-- Given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. Proof idea: We label each value in the sequence with two numbers specifying the longest increasing subsequence ending there, and the longest decreasing subsequence ending there. We then show the pair of labels must be unique. Now if there is no increasing sequence longer than `r` and no decreasing sequence longer than `s`, then there are at most `r * s` possible labels, which is a contradiction if there are more than `r * s` elements. -/ theorem erdos_szekeres {r s n : ℕ} {f : fin n → α} (hn : r * s < n) (hf : injective f) : (∃ (t : finset (fin n)), r < t.card ∧ strict_mono_incr_on f ↑t) ∨ (∃ (t : finset (fin n)), s < t.card ∧ strict_mono_decr_on f ↑t) := begin -- Given an index `i`, produce the set of increasing (resp., decreasing) subsequences which ends -- at `i`. let inc_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = some i ∧ strict_mono_incr_on f ↑t), let dec_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = some i ∧ strict_mono_decr_on f ↑t), -- The singleton sequence is in both of the above collections. -- (This is useful to show that the maximum length subsequence is at least 1, and that the set -- of subsequences is nonempty.) have inc_i : ∀ i, {i} ∈ inc_sequences_ending_in i := λ i, by simp [strict_mono_incr_on], have dec_i : ∀ i, {i} ∈ dec_sequences_ending_in i := λ i, by simp [strict_mono_decr_on], -- Define the pair of labels: at index `i`, the pair is the maximum length of an increasing -- subsequence ending at `i`, paired with the maximum length of a decreasing subsequence ending -- at `i`. -- We call these labels `(a_i, b_i)`. let ab : fin n → ℕ × ℕ, { intro i, apply (max' ((inc_sequences_ending_in i).image card) (nonempty.image ⟨{i}, inc_i i⟩ _), max' ((dec_sequences_ending_in i).image card) (nonempty.image ⟨{i}, dec_i i⟩ _)) }, -- It now suffices to show that one of the labels is 'big' somewhere. In particular, if the -- first in the pair is more than `r` somewhere, then we have an increasing subsequence in our -- set, and if the second is more than `s` somewhere, then we have a decreasing subsequence. suffices : ∃ i, r < (ab i).1 ∨ s < (ab i).2, { obtain ⟨i, hi⟩ := this, apply or.imp _ _ hi, work_on_goal 0 { have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 1 { have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { intro hi, rw mem_image at this, obtain ⟨t, ht₁, ht₂⟩ := this, refine ⟨t, by rwa ht₂, _⟩, rw mem_filter at ht₁, apply ht₁.2.2 } }, -- Show first that the pair of labels is unique. have : injective ab, { apply injective_of_lt_imp_ne, intros i j k q, injection q with q₁ q₂, -- We have two cases: `f i < f j` or `f j < f i`. -- In the former we'll show `a_i < a_j`, and in the latter we'll show `b_i < b_j`. cases lt_or_gt_of_ne (λ _, ne_of_lt ‹i < j› (hf ‹f i = f j›)), work_on_goal 0 { apply ne_of_lt _ q₁, have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 1 { apply ne_of_lt _ q₂, have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { -- Reduce to showing there is a subsequence of length `a_i + 1` which ends at `j`. rw nat.lt_iff_add_one_le, apply le_max', rw mem_image at this ⊢, -- In particular we take the subsequence `t` of length `a_i` which ends at `i`, by definition of `a_i` rcases this with ⟨t, ht₁, ht₂⟩, rw mem_filter at ht₁, -- Ensure `t` ends at `i`. have : i ∈ t.max, simp [ht₁.2.1], -- Now our new subsequence is given by adding `j` at the end of `t`. refine ⟨insert j t, _, _⟩, -- First make sure it's valid, i.e., that this subsequence ends at `j` and is increasing { rw mem_filter, refine ⟨_, _, _⟩, { rw mem_powerset, apply subset_univ }, -- It ends at `j` since `i < j`. { convert max_insert, rw [ht₁.2.1, option.lift_or_get_some_some, max_eq_left, with_top.some_eq_coe], apply le_of_lt ‹i < j› }, -- To show it's increasing (i.e., `f` is monotone increasing on `t.insert j`), we do cases on -- what the possibilities could be - either in `t` or equals `j`. simp only [strict_mono_incr_on, strict_mono_decr_on, coe_insert, set.mem_insert_iff, mem_coe], -- Most of the cases are just bashes. rintros x ⟨rfl | _⟩ y ⟨rfl | _⟩ _, { apply (irrefl _ ‹j < j›).elim }, { exfalso, apply not_le_of_lt (trans ‹i < j› ‹j < y›) (le_max_of_mem ‹y ∈ t› ‹i ∈ t.max›) }, { apply lt_of_le_of_lt _ ‹f i < f j› <|> apply lt_of_lt_of_le ‹f j < f i› _, rcases lt_or_eq_of_le (le_max_of_mem ‹x ∈ t› ‹i ∈ t.max›) with _ | rfl, { apply le_of_lt (ht₁.2.2 _ ‹x ∈ t› i (mem_of_max ‹i ∈ t.max›) ‹x < i›) }, { refl } }, { apply ht₁.2.2 _ ‹x ∈ t› _ ‹y ∈ t› ‹x < y› } }, -- Finally show that this new subsequence is one longer than the old one. { rw [card_insert_of_not_mem, ht₂], intro _, apply not_le_of_lt ‹i < j› (le_max_of_mem ‹j ∈ t› ‹i ∈ t.max›) } } }, -- Finished both goals! -- Now that we have uniqueness of each label, it remains to do some counting to finish off. -- Suppose all the labels are small. by_contra q, push_neg at q, -- Then the labels `(a_i, b_i)` all fit in the following set: `{ (x,y) | 1 ≤ x ≤ r, 1 ≤ y ≤ s }` let ran : finset (ℕ × ℕ) := ((range r).image nat.succ).product ((range s).image nat.succ), -- which we prove here. have : image ab univ ⊆ ran, -- First some logical shuffling { rintro ⟨x₁, x₂⟩, simp only [mem_image, exists_prop, mem_range, mem_univ, mem_product, true_and, prod.mk.inj_iff], rintros ⟨i, rfl, rfl⟩, specialize q i, -- Show `1 ≤ a_i` and `1 ≤ b_i`, which is easy from the fact that `{i}` is a increasing and decreasing -- subsequence which we did right near the top. have z : 1 ≤ (ab i).1 ∧ 1 ≤ (ab i).2, { split; { apply le_max', rw mem_image, refine ⟨{i}, by solve_by_elim, card_singleton i⟩ } }, refine ⟨_, _⟩, -- Need to get `a_i ≤ r`, here phrased as: there is some `a < r` with `a+1 = a_i`. { refine ⟨(ab i).1 - 1, _, nat.succ_pred_eq_of_pos z.1⟩, rw nat.sub_lt_right_iff_lt_add z.1, apply nat.lt_succ_of_le q.1 }, { refine ⟨(ab i).2 - 1, _, nat.succ_pred_eq_of_pos z.2⟩, rw nat.sub_lt_right_iff_lt_add z.2, apply nat.lt_succ_of_le q.2 } }, -- To get our contradiction, it suffices to prove `n ≤ r * s` apply not_le_of_lt hn, -- Which follows from considering the cardinalities of the subset above, since `ab` is injective. simpa [nat.succ_injective, card_image_of_injective, ‹injective ab›] using card_le_of_subset this, end
fa6d2249655ebca8b1788fa092c2c2b73e2031b0
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/polynomial/gauss_lemma.lean
03ac6abb3307302b66a127e9369055673ccba7c5
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,958
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.int.basic import ring_theory.localization /-! # Gauss's Lemma Gauss's Lemma is one of a few results pertaining to irreducibility of primitive polynomials. ## Main Results - `polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map`: A primitive polynomial is irreducible iff it is irreducible in a fraction field. - `polynomial.is_primitive.int.irreducible_iff_irreducible_map_cast`: A primitive polynomial over `ℤ` is irreducible iff it is irreducible over `ℚ`. - `polynomial.is_primitive.dvd_iff_fraction_map_dvd_fraction_map`: Two primitive polynomials divide each other iff they do in a fraction field. - `polynomial.is_primitive.int.dvd_iff_map_cast_dvd_map_cast`: Two primitive polynomials over `ℤ` divide each other if they do in `ℚ`. -/ open_locale non_zero_divisors variables {R : Type*} [comm_ring R] [is_domain R] namespace polynomial section normalized_gcd_monoid variable [normalized_gcd_monoid R] section variables {S : Type*} [comm_ring S] [is_domain S] {φ : R →+* S} (hinj : function.injective φ) variables {f : polynomial R} (hf : f.is_primitive) include hinj hf lemma is_primitive.is_unit_iff_is_unit_map_of_injective : is_unit f ↔ is_unit (map φ f) := begin refine ⟨(map_ring_hom φ).is_unit_map, λ h, _⟩, rcases is_unit_iff.1 h with ⟨_, ⟨u, rfl⟩, hu⟩, have hdeg := degree_C u.ne_zero, rw [hu, degree_map' hinj] at hdeg, rw [eq_C_of_degree_eq_zero hdeg, is_primitive_iff_content_eq_one, content_C, normalize_eq_one] at hf, rwa [eq_C_of_degree_eq_zero hdeg, is_unit_C], end lemma is_primitive.irreducible_of_irreducible_map_of_injective (h_irr : irreducible (map φ f)) : irreducible f := begin refine ⟨λ h, h_irr.not_unit (is_unit.map ((map_ring_hom φ).to_monoid_hom) h), _⟩, intros a b h, rcases h_irr.is_unit_or_is_unit (by rw [h, map_mul]) with hu | hu, { left, rwa (hf.is_primitive_of_dvd (dvd.intro _ h.symm)).is_unit_iff_is_unit_map_of_injective hinj }, right, rwa (hf.is_primitive_of_dvd (dvd.intro_left _ h.symm)).is_unit_iff_is_unit_map_of_injective hinj end end section fraction_map variables {K : Type*} [field K] [algebra R K] [is_fraction_ring R K] lemma is_primitive.is_unit_iff_is_unit_map {p : polynomial R} (hp : p.is_primitive) : is_unit p ↔ is_unit (p.map (algebra_map R K)) := hp.is_unit_iff_is_unit_map_of_injective (is_fraction_ring.injective _ _) open is_localization lemma is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part {p : polynomial K} (h0 : p ≠ 0) (h : is_unit (integer_normalization R⁰ p).prim_part) : is_unit p := begin rcases is_unit_iff.1 h with ⟨_, ⟨u, rfl⟩, hu⟩, obtain ⟨⟨c, c0⟩, hc⟩ := integer_normalization_map_to_map R⁰ p, rw [subtype.coe_mk, algebra.smul_def, algebra_map_apply] at hc, apply is_unit_of_mul_is_unit_right, rw [← hc, (integer_normalization R⁰ p).eq_C_content_mul_prim_part, ← hu, ← ring_hom.map_mul, is_unit_iff], refine ⟨algebra_map R K ((integer_normalization R⁰ p).content * ↑u), is_unit_iff_ne_zero.2 (λ con, _), by simp⟩, replace con := (algebra_map R K).injective_iff.1 (is_fraction_ring.injective _ _) _ con, rw [mul_eq_zero, content_eq_zero_iff, is_fraction_ring.integer_normalization_eq_zero_iff] at con, rcases con with con | con, { apply h0 con }, { apply units.ne_zero _ con }, end /-- **Gauss's Lemma** states that a primitive polynomial is irreducible iff it is irreducible in the fraction field. -/ theorem is_primitive.irreducible_iff_irreducible_map_fraction_map {p : polynomial R} (hp : p.is_primitive) : irreducible p ↔ irreducible (p.map (algebra_map R K)) := begin refine ⟨λ hi, ⟨λ h, hi.not_unit (hp.is_unit_iff_is_unit_map.2 h), λ a b hab, _⟩, hp.irreducible_of_irreducible_map_of_injective (is_fraction_ring.injective _ _)⟩, obtain ⟨⟨c, c0⟩, hc⟩ := integer_normalization_map_to_map R⁰ a, obtain ⟨⟨d, d0⟩, hd⟩ := integer_normalization_map_to_map R⁰ b, rw [algebra.smul_def, algebra_map_apply, subtype.coe_mk] at hc hd, rw mem_non_zero_divisors_iff_ne_zero at c0 d0, have hcd0 : c * d ≠ 0 := mul_ne_zero c0 d0, rw [ne.def, ← C_eq_zero] at hcd0, have h1 : C c * C d * p = integer_normalization R⁰ a * integer_normalization R⁰ b, { apply map_injective (algebra_map R K) (is_fraction_ring.injective _ _) _, rw [map_mul, map_mul, map_mul, hc, hd, map_C, map_C, hab], ring }, obtain ⟨u, hu⟩ : associated (c * d) (content (integer_normalization R⁰ a) * content (integer_normalization R⁰ b)), { rw [← dvd_dvd_iff_associated, ← normalize_eq_normalize_iff, normalize.map_mul, normalize.map_mul, normalize_content, normalize_content, ← mul_one (normalize c * normalize d), ← hp.content_eq_one, ← content_C, ← content_C, ← content_mul, ← content_mul, ← content_mul, h1] }, rw [← ring_hom.map_mul, eq_comm, (integer_normalization R⁰ a).eq_C_content_mul_prim_part, (integer_normalization R⁰ b).eq_C_content_mul_prim_part, mul_assoc, mul_comm _ (C _ * _), ← mul_assoc, ← mul_assoc, ← ring_hom.map_mul, ← hu, ring_hom.map_mul, mul_assoc, mul_assoc, ← mul_assoc (C ↑u)] at h1, have h0 : (a ≠ 0) ∧ (b ≠ 0), { classical, rw [ne.def, ne.def, ← decidable.not_or_iff_and_not, ← mul_eq_zero, ← hab], intro con, apply hp.ne_zero (map_injective (algebra_map R K) (is_fraction_ring.injective _ _) _), simp [con] }, rcases hi.is_unit_or_is_unit (mul_left_cancel₀ hcd0 h1).symm with h | h, { right, apply is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part h0.2 (is_unit_of_mul_is_unit_right h) }, { left, apply is_unit_or_eq_zero_of_is_unit_integer_normalization_prim_part h0.1 h }, end lemma is_primitive.dvd_of_fraction_map_dvd_fraction_map {p q : polynomial R} (hp : p.is_primitive) (hq : q.is_primitive) (h_dvd : p.map (algebra_map R K) ∣ q.map (algebra_map R K)) : p ∣ q := begin rcases h_dvd with ⟨r, hr⟩, obtain ⟨⟨s, s0⟩, hs⟩ := integer_normalization_map_to_map R⁰ r, rw [subtype.coe_mk, algebra.smul_def, algebra_map_apply] at hs, have h : p ∣ q * C s, { use (integer_normalization R⁰ r), apply map_injective (algebra_map R K) (is_fraction_ring.injective _ _), rw [map_mul, map_mul, hs, hr, mul_assoc, mul_comm r], simp }, rw [← hp.dvd_prim_part_iff_dvd, prim_part_mul, hq.prim_part_eq, associated.dvd_iff_dvd_right] at h, { exact h }, { symmetry, rcases is_unit_prim_part_C s with ⟨u, hu⟩, use u, rw hu }, iterate 2 { apply mul_ne_zero hq.ne_zero, rw [ne.def, C_eq_zero], contrapose! s0, simp [s0, mem_non_zero_divisors_iff_ne_zero] } end variables (K) lemma is_primitive.dvd_iff_fraction_map_dvd_fraction_map {p q : polynomial R} (hp : p.is_primitive) (hq : q.is_primitive) : (p ∣ q) ↔ (p.map (algebra_map R K) ∣ q.map (algebra_map R K)) := ⟨λ ⟨a,b⟩, ⟨a.map (algebra_map R K), b.symm ▸ map_mul (algebra_map R K)⟩, λ h, hp.dvd_of_fraction_map_dvd_fraction_map hq h⟩ end fraction_map /-- **Gauss's Lemma** for `ℤ` states that a primitive integer polynomial is irreducible iff it is irreducible over `ℚ`. -/ theorem is_primitive.int.irreducible_iff_irreducible_map_cast {p : polynomial ℤ} (hp : p.is_primitive) : irreducible p ↔ irreducible (p.map (int.cast_ring_hom ℚ)) := hp.irreducible_iff_irreducible_map_fraction_map lemma is_primitive.int.dvd_iff_map_cast_dvd_map_cast (p q : polynomial ℤ) (hp : p.is_primitive) (hq : q.is_primitive) : (p ∣ q) ↔ (p.map (int.cast_ring_hom ℚ) ∣ q.map (int.cast_ring_hom ℚ)) := hp.dvd_iff_fraction_map_dvd_fraction_map ℚ hq end normalized_gcd_monoid end polynomial
2ffd1490e2c3374ca3351130af8f43504416cd7f
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/system/random/basic.lean
46b635213ea91e34a526cd1279b769f89a684cdf
[ "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
9,276
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import algebra.group_power import control.uliftable import control.monad.basic import data.bitvec.basic import data.list.basic import data.set.intervals.basic import data.stream.basic import data.fin import tactic.cache import tactic.interactive import tactic.norm_num import system.io import system.random /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `rand` monad for computations guided by randomness; * `random` class for objects that can be generated randomly; * `random` to generate one object; * `random_r` to generate one object inside a range; * `random_series` to generate an infinite series of objects; * `random_series_r` to generate an infinite series of objects inside a range; * `io.mk_generator` to create a new random number generator; * `io.run_rand` to run a randomized computation inside the `io` monad; * `tactic.run_rand` to run a randomized computation inside the `tactic` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random monad io ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ open list io applicative universes u v w /-- A monad to generate random objects using the generator type `g` -/ @[reducible] def rand_g (g : Type) (α : Type u) : Type u := state (ulift.{u} g) α /-- A monad to generate random objects using the generator type `std_gen` -/ @[reducible] def rand := rand_g std_gen instance (g : Type) : uliftable (rand_g.{u} g) (rand_g.{v} g) := @state_t.uliftable' _ _ _ _ _ (equiv.ulift.trans.{u u u u u} equiv.ulift.symm) open ulift (hiding inhabited) /-- Generate one more `ℕ` -/ def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ := ⟨ prod.map id up ∘ random_gen.next ∘ down ⟩ local infix ` .. `:41 := set.Icc open stream /-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/ class bounded_random (α : Type u) [preorder α] := (random_r : Π g [random_gen g] (x y : α), (x ≤ y) → rand_g g (x .. y)) /-- `random α` gives us machinery to generate values of type `α` -/ class random (α : Type u) [preorder α] extends bounded_random α := (random [] : Π (g : Type) [random_gen g], rand_g g α) attribute [instance, priority 100] random.to_bounded_random /-- shift_31_left = 2^31; multiplying by it shifts the binary representation of a number left by 31 bits, dividing by it shifts it right by 31 bits -/ def shift_31_left : ℕ := by apply_normed 2^31 namespace rand open stream variables (α : Type u) variables (g : Type) [random_gen g] /-- create a new random number generator distinct from the one stored in the state -/ def split : rand_g g g := ⟨ prod.map id up ∘ random_gen.split ∘ down ⟩ variables {g} section random variables [preorder α] [random α] export random (random) /-- Generate a random value of type `α`. -/ def random : rand_g g α := random.random α g /-- generate an infinite series of random values of type `α` -/ def random_series : rand_g g (stream α) := do gen ← uliftable.up (split g), pure $ stream.corec_state (random.random α g) gen end random variables {α} /-- Generate a random value between `x` and `y` inclusive. -/ def random_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (x .. y) := bounded_random.random_r g x y h /-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ def random_series_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (stream (x .. y)) := do gen ← uliftable.up (split g), pure $ corec_state (bounded_random.random_r g x y h) gen end rand namespace io private def accum_char (w : ℕ) (c : char) : ℕ := c.to_nat + 256 * w /-- create and a seed a random number generator -/ def mk_generator : io std_gen := do seed ← io.rand 0 shift_31_left, return $ mk_std_gen seed variables {α : Type} /-- Run `cmd` using a randomly seeded random number generator -/ def run_rand (cmd : _root_.rand α) : io α := do g ← io.mk_generator, return $ (cmd.run ⟨g⟩).1 /-- Run `cmd` using the provided seed. -/ def run_rand_with (seed : ℕ) (cmd : _root_.rand α) : io α := return $ (cmd.run ⟨mk_std_gen seed⟩).1 section random variables [preorder α] [random α] /-- randomly generate a value of type α -/ def random : io α := io.run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ def random_series : io (stream α) := io.run_rand (rand.random_series α) end random section bounded_random variables [preorder α] [bounded_random α] /-- randomly generate a value of type α between `x` and `y` -/ def random_r (x y : α) (p : x ≤ y) : io (x .. y) := io.run_rand (bounded_random.random_r _ x y p) /-- randomly generate an infinite series of value of type α between `x` and `y` -/ def random_series_r (x y : α) (h : x ≤ y) : io (stream $ x .. y) := io.run_rand (rand.random_series_r x y h) end bounded_random end io namespace tactic /-- create a seeded random number generator in the `tactic` monad -/ meta def mk_generator : tactic std_gen := do tactic.unsafe_run_io @io.mk_generator /-- run `cmd` using the a randomly seeded random number generator in the tactic monad -/ meta def run_rand {α : Type u} (cmd : rand α) : tactic α := do ⟨g⟩ ← tactic.up mk_generator, return (cmd.run ⟨g⟩).1 variables {α : Type u} section bounded_random variables [preorder α] [bounded_random α] /-- Generate a random value between `x` and `y` inclusive. -/ meta def random_r (x y : α) (h : x ≤ y) : tactic (x .. y) := run_rand (rand.random_r x y h) /-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ meta def random_series_r (x y : α) (h : x ≤ y) : tactic (stream $ x .. y) := run_rand (rand.random_series_r x y h) end bounded_random section random variables [preorder α] [random α] /-- randomly generate a value of type α -/ meta def random : tactic α := run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ meta def random_series : tactic (stream α) := run_rand (rand.random_series α) end random end tactic open nat (succ one_add mod_eq_of_lt zero_lt_succ add_one succ_le_succ) variables {g : Type} [random_gen g] open nat namespace fin variables {n : ℕ} [fact (0 < n)] /-- generate a `fin` randomly -/ protected def random : rand_g g (fin n) := ⟨ λ ⟨g⟩, prod.map of_nat' up $ rand_nat g 0 n ⟩ end fin open nat instance nat_bounded_random : bounded_random ℕ := { random_r := λ g inst x y hxy, do z ← @fin.random g inst (succ $ y - x) _, pure ⟨z.val + x, nat.le_add_left _ _, by rw ← nat.le_sub_right_iff_add_le hxy; apply le_of_succ_le_succ z.is_lt⟩ } instance fin_random (n : ℕ) [fact (0 < n)] : random (fin n) := { random := λ g inst, @fin.random g inst _ _, random_r := λ g inst (x y : fin n) p, do ⟨r, h, h'⟩ ← @rand.random_r ℕ g inst _ _ x.val y.val p, pure ⟨⟨r,lt_of_le_of_lt h' y.is_lt⟩, h, h'⟩ } /-- A shortcut for creating a `random (fin n)` instance from a proof that `0 < n` rather than on matching on `fin (succ n)` -/ def random_fin_of_pos : ∀ {n : ℕ} (h : 0 < n), random (fin n) | (succ n) _ := fin_random _ | 0 h := false.elim (not_lt_zero _ h) lemma bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x y : bool) (n : ℕ) : n ∈ (x.to_nat .. y.to_nat) → bool.of_nat n ∈ (x .. y) := begin simp only [and_imp, set.mem_Icc], intros h₀ h₁, split; [ have h₂ := bool.of_nat_le_of_nat h₀, have h₂ := bool.of_nat_le_of_nat h₁ ]; rw bool.of_nat_to_nat at h₂; exact h₂, end instance : random bool := { random := λ g inst, (bool.of_nat ∘ subtype.val) <$> @bounded_random.random_r ℕ _ _ g inst 0 1 (nat.zero_le _), random_r := λ g _inst x y p, subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$> @bounded_random.random_r ℕ _ _ g _inst x.to_nat y.to_nat (bool.to_nat_le_to_nat p) } open_locale fin_fact /-- generate a random bit vector of length `n` -/ def bitvec.random (n : ℕ) : rand_g g (bitvec n) := bitvec.of_fin <$> rand.random (fin $ 2^n) /-- generate a random bit vector of length `n` -/ def bitvec.random_r {n : ℕ} (x y : bitvec n) (h : x ≤ y) : rand_g g (x .. y) := have h' : ∀ (a : fin (2 ^ n)), a ∈ (x.to_fin .. y.to_fin) → bitvec.of_fin a ∈ (x .. y), begin simp only [and_imp, set.mem_Icc], intros z h₀ h₁, replace h₀ := bitvec.of_fin_le_of_fin_of_le h₀, replace h₁ := bitvec.of_fin_le_of_fin_of_le h₁, rw bitvec.of_fin_to_fin at h₀ h₁, split; assumption, end, subtype.map bitvec.of_fin h' <$> rand.random_r x.to_fin y.to_fin (bitvec.to_fin_le_to_fin_of_le h) open nat instance random_bitvec (n : ℕ) : random (bitvec n) := { random := λ _ inst, @bitvec.random _ inst n, random_r := λ _ inst x y p, @bitvec.random_r _ inst _ _ _ p }
4f65b40129f00a50228dc882ad1ca3f2f09ddf70
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/basic.lean
132bef9c151cc9326ea16aced751c1e4021170bf
[ "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
30,223
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import data.prod.basic import data.subtype /-! # Basic definitions about `≤` and `<` This file proves basic results about orders, provides extensive dot notation, defines useful order classes and allows to transfer order instances. ## Type synonyms * `order_dual α` : A type synonym reversing the meaning of all inequalities, with notation `αᵒᵈ`. * `as_linear_order α`: A type synonym to promote `partial_order α` to `linear_order α` using `is_total α (≤)`. ### Transfering orders - `order.preimage`, `preorder.lift`: Transfers a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `partial_order.lift`, `linear_order.lift`: Transfers a partial (resp., linear) order on `β` to a partial (resp., linear) order on `α` using an injective function `f`. ### Extra class * `has_sup`: type class for the `⊔` notation * `has_inf`: type class for the `⊓` notation * `densely_ordered`: An order with no gap, i.e. for any two elements `a < b` there exists `c` such that `a < c < b`. ## Notes `≤` and `<` are highly favored over `≥` and `>` in mathlib. The reason is that we can formulate all lemmas using `≤`/`<`, and `rw` has trouble unifying `≤` and `≥`. Hence choosing one direction spares us useless duplication. This is enforced by a linter. See Note [nolint_ge] for more infos. Dot notation is particularly useful on `≤` (`has_le.le`) and `<` (`has_lt.lt`). To that end, we provide many aliases to dot notation-less lemmas. For example, `le_trans` is aliased with `has_le.le.trans` and can be used to construct `hab.trans hbc : a ≤ c` when `hab : a ≤ b`, `hbc : b ≤ c`, `lt_of_le_of_lt` is aliased as `has_le.le.trans_lt` and can be used to construct `hab.trans hbc : a < c` when `hab : a ≤ b`, `hbc : b < c`. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## Tags preorder, order, partial order, poset, linear order, chain -/ open function universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} section preorder variables [preorder α] {a b c : α} lemma le_trans' : b ≤ c → a ≤ b → a ≤ c := flip le_trans lemma lt_trans' : b < c → a < b → a < c := flip lt_trans lemma lt_of_le_of_lt' : b ≤ c → a < b → a < c := flip lt_of_lt_of_le lemma lt_of_lt_of_le' : b < c → a ≤ b → a < c := flip lt_of_le_of_lt end preorder section partial_order variables [partial_order α] {a b : α} lemma ge_antisymm : a ≤ b → b ≤ a → b = a := flip le_antisymm lemma lt_of_le_of_ne' : a ≤ b → b ≠ a → a < b := λ h₁ h₂, lt_of_le_of_ne h₁ h₂.symm lemma ne.lt_of_le : a ≠ b → a ≤ b → a < b := flip lt_of_le_of_ne lemma ne.lt_of_le' : b ≠ a → a ≤ b → a < b := flip lt_of_le_of_ne' end partial_order attribute [simp] le_refl attribute [ext] has_le alias le_trans ← has_le.le.trans alias le_trans' ← has_le.le.trans' alias lt_of_le_of_lt ← has_le.le.trans_lt alias lt_of_le_of_lt' ← has_le.le.trans_lt' alias le_antisymm ← has_le.le.antisymm alias ge_antisymm ← has_le.le.antisymm' alias lt_of_le_of_ne ← has_le.le.lt_of_ne alias lt_of_le_of_ne' ← has_le.le.lt_of_ne' alias lt_of_le_not_le ← has_le.le.lt_of_not_le alias lt_or_eq_of_le ← has_le.le.lt_or_eq alias decidable.lt_or_eq_of_le ← has_le.le.lt_or_eq_dec alias le_of_lt ← has_lt.lt.le alias lt_trans ← has_lt.lt.trans alias lt_trans' ← has_lt.lt.trans' alias lt_of_lt_of_le ← has_lt.lt.trans_le alias lt_of_lt_of_le' ← has_lt.lt.trans_le' alias ne_of_lt ← has_lt.lt.ne alias lt_asymm ← has_lt.lt.asymm has_lt.lt.not_lt alias le_of_eq ← eq.le attribute [nolint decidable_classical] has_le.le.lt_or_eq_dec section variables [preorder α] {a b c : α} /-- A version of `le_refl` where the argument is implicit -/ lemma le_rfl : a ≤ a := le_refl a @[simp] lemma lt_self_iff_false (x : α) : x < x ↔ false := ⟨lt_irrefl x, false.elim⟩ lemma le_of_le_of_eq (hab : a ≤ b) (hbc : b = c) : a ≤ c := hab.trans hbc.le lemma le_of_eq_of_le (hab : a = b) (hbc : b ≤ c) : a ≤ c := hab.le.trans hbc lemma lt_of_lt_of_eq (hab : a < b) (hbc : b = c) : a < c := hab.trans_le hbc.le lemma lt_of_eq_of_lt (hab : a = b) (hbc : b < c) : a < c := hab.le.trans_lt hbc lemma le_of_le_of_eq' : b ≤ c → a = b → a ≤ c := flip le_of_eq_of_le lemma le_of_eq_of_le' : b = c → a ≤ b → a ≤ c := flip le_of_le_of_eq lemma lt_of_lt_of_eq' : b < c → a = b → a < c := flip lt_of_eq_of_lt lemma lt_of_eq_of_lt' : b = c → a < b → a < c := flip lt_of_lt_of_eq alias le_of_le_of_eq ← has_le.le.trans_eq alias le_of_le_of_eq' ← has_le.le.trans_eq' alias lt_of_lt_of_eq ← has_lt.lt.trans_eq alias lt_of_lt_of_eq' ← has_lt.lt.trans_eq' alias le_of_eq_of_le ← eq.trans_le alias le_of_eq_of_le' ← eq.trans_ge alias lt_of_eq_of_lt ← eq.trans_lt alias lt_of_eq_of_lt' ← eq.trans_gt end namespace eq variables [preorder α] {x y z : α} /-- If `x = y` then `y ≤ x`. Note: this lemma uses `y ≤ x` instead of `x ≥ y`, because `le` is used almost exclusively in mathlib. -/ protected lemma ge (h : x = y) : y ≤ x := h.symm.le lemma not_lt (h : x = y) : ¬ x < y := λ h', h'.ne h lemma not_gt (h : x = y) : ¬ y < x := h.symm.not_lt end eq namespace has_le.le @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma ge [has_le α] {x y : α} (h : x ≤ y) : y ≥ x := h lemma lt_iff_ne [partial_order α] {x y : α} (h : x ≤ y) : x < y ↔ x ≠ y := ⟨λ h, h.ne, h.lt_of_ne⟩ lemma le_iff_eq [partial_order α] {x y : α} (h : x ≤ y) : y ≤ x ↔ y = x := ⟨λ h', h'.antisymm h, eq.le⟩ lemma lt_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a < c ∨ c ≤ b := (lt_or_ge a c).imp id $ λ hc, le_trans hc h lemma le_or_lt [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c < b := (le_or_gt a c).imp id $ λ hc, lt_of_lt_of_le hc h lemma le_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c ≤ b := (h.le_or_lt c).elim or.inl (λ h, or.inr $ le_of_lt h) end has_le.le namespace has_lt.lt @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma gt [has_lt α] {x y : α} (h : x < y) : y > x := h protected lemma false [preorder α] {x : α} : x < x → false := lt_irrefl x lemma ne' [preorder α] {x y : α} (h : x < y) : y ≠ x := h.ne.symm lemma lt_or_lt [linear_order α] {x y : α} (h : x < y) (z : α) : x < z ∨ z < y := (lt_or_ge z y).elim or.inr (λ hz, or.inl $ h.trans_le hz) end has_lt.lt @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma ge.le [has_le α] {x y : α} (h : x ≥ y) : y ≤ x := h @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma gt.lt [has_lt α] {x y : α} (h : x > y) : y < x := h @[nolint ge_or_gt] -- see Note [nolint_ge] theorem ge_of_eq [preorder α] {a b : α} (h : a = b) : a ≥ b := h.ge @[simp, nolint ge_or_gt] -- see Note [nolint_ge] lemma ge_iff_le [has_le α] {a b : α} : a ≥ b ↔ b ≤ a := iff.rfl @[simp, nolint ge_or_gt] -- see Note [nolint_ge] lemma gt_iff_lt [has_lt α] {a b : α} : a > b ↔ b < a := iff.rfl lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a := (le_not_le_of_lt h).right alias not_le_of_lt ← has_lt.lt.not_le lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a := λ hba, hba.not_le h alias not_lt_of_le ← has_le.le.not_lt lemma ne_of_not_le [preorder α] {a b : α} (h : ¬ a ≤ b) : a ≠ b := λ hab, h (le_of_eq hab) -- See Note [decidable namespace] protected lemma decidable.le_iff_eq_or_lt [partial_order α] [@decidable_rel α (≤)] {a b : α} : a ≤ b ↔ a = b ∨ a < b := decidable.le_iff_lt_or_eq.trans or.comm lemma le_iff_eq_or_lt [partial_order α] {a b : α} : a ≤ b ↔ a = b ∨ a < b := le_iff_lt_or_eq.trans or.comm lemma lt_iff_le_and_ne [partial_order α] {a b : α} : a < b ↔ a ≤ b ∧ a ≠ b := ⟨λ h, ⟨le_of_lt h, ne_of_lt h⟩, λ ⟨h1, h2⟩, h1.lt_of_ne h2⟩ -- See Note [decidable namespace] protected lemma decidable.eq_iff_le_not_lt [partial_order α] [@decidable_rel α (≤)] {a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b := ⟨λ h, ⟨h.le, h ▸ lt_irrefl _⟩, λ ⟨h₁, h₂⟩, h₁.antisymm $ decidable.by_contradiction $ λ h₃, h₂ (h₁.lt_of_not_le h₃)⟩ lemma eq_iff_le_not_lt [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b := by haveI := classical.dec; exact decidable.eq_iff_le_not_lt lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b := h.lt_or_eq.symm lemma eq_or_gt_of_le [partial_order α] {a b : α} (h : a ≤ b) : b = a ∨ a < b := h.lt_or_eq.symm.imp eq.symm id alias decidable.eq_or_lt_of_le ← has_le.le.eq_or_lt_dec alias eq_or_lt_of_le ← has_le.le.eq_or_lt alias eq_or_gt_of_le ← has_le.le.eq_or_gt attribute [nolint decidable_classical] has_le.le.eq_or_lt_dec lemma eq_of_le_of_not_lt [partial_order α] {a b : α} (hab : a ≤ b) (hba : ¬ a < b) : a = b := hab.eq_or_lt.resolve_right hba lemma eq_of_ge_of_not_gt [partial_order α] {a b : α} (hab : a ≤ b) (hba : ¬ a < b) : b = a := (hab.eq_or_lt.resolve_right hba).symm alias eq_of_le_of_not_lt ← has_le.le.eq_of_not_lt alias eq_of_ge_of_not_gt ← has_le.le.eq_of_not_gt lemma ne.le_iff_lt [partial_order α] {a b : α} (h : a ≠ b) : a ≤ b ↔ a < b := ⟨λ h', lt_of_le_of_ne h' h, λ h, h.le⟩ lemma ne.not_le_or_not_le [partial_order α] {a b : α} (h : a ≠ b) : ¬ a ≤ b ∨ ¬ b ≤ a := not_and_distrib.1 $ le_antisymm_iff.not.1 h -- See Note [decidable namespace] protected lemma decidable.ne_iff_lt_iff_le [partial_order α] [decidable_eq α] {a b : α} : (a ≠ b ↔ a < b) ↔ a ≤ b := ⟨λ h, decidable.by_cases le_of_eq (le_of_lt ∘ h.mp), λ h, ⟨lt_of_le_of_ne h, ne_of_lt⟩⟩ @[simp] lemma ne_iff_lt_iff_le [partial_order α] {a b : α} : (a ≠ b ↔ a < b) ↔ a ≤ b := by haveI := classical.dec; exact decidable.ne_iff_lt_iff_le lemma lt_of_not_le [linear_order α] {a b : α} (h : ¬ b ≤ a) : a < b := ((le_total _ _).resolve_right h).lt_of_not_le h lemma lt_iff_not_le [linear_order α] {x y : α} : x < y ↔ ¬ y ≤ x := ⟨not_le_of_lt, lt_of_not_le⟩ lemma ne.lt_or_lt [linear_order α] {x y : α} (h : x ≠ y) : x < y ∨ y < x := lt_or_gt_of_ne h /-- A version of `ne_iff_lt_or_gt` with LHS and RHS reversed. -/ @[simp] lemma lt_or_lt_iff_ne [linear_order α] {x y : α} : x < y ∨ y < x ↔ x ≠ y := ne_iff_lt_or_gt.symm lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a := not_lt.trans $ decidable.le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl lemma exists_ge_of_linear [linear_order α] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := match le_total a b with | or.inl h := ⟨_, h, le_rfl⟩ | or.inr h := ⟨_, le_rfl, h⟩ end lemma lt_imp_lt_of_le_imp_le {β} [linear_order α] [preorder β] {a b : α} {c d : β} (H : a ≤ b → c ≤ d) (h : d < c) : b < a := lt_of_not_le $ λ h', (H h').not_lt h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma lt_iff_lt_of_le_iff_le' {β} [preorder α] [preorder β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c := lt_iff_le_not_le.trans $ (and_congr H' (not_congr H)).trans lt_iff_le_not_le.symm lemma lt_iff_lt_of_le_iff_le {β} [linear_order α] [linear_order β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c := not_le.symm.trans $ (not_congr H).trans $ not_le lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ (not_congr H).trans $ not_lt⟩ lemma eq_of_forall_le_iff [partial_order α] {a b : α} (H : ∀ c, c ≤ a ↔ c ≤ b) : a = b := ((H _).1 le_rfl).antisymm ((H _).2 le_rfl) lemma le_of_forall_le [preorder α] {a b : α} (H : ∀ c, c ≤ a → c ≤ b) : a ≤ b := H _ le_rfl lemma le_of_forall_le' [preorder α] {a b : α} (H : ∀ c, a ≤ c → b ≤ c) : b ≤ a := H _ le_rfl lemma le_of_forall_lt [linear_order α] {a b : α} (H : ∀ c, c < a → c < b) : a ≤ b := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le [linear_order α] {a b : α} : (∀ ⦃c⦄, c < a → c < b) ↔ a ≤ b := ⟨le_of_forall_lt, λ h c hca, lt_of_lt_of_le hca h⟩ lemma le_of_forall_lt' [linear_order α] {a b : α} (H : ∀ c, a < c → b < c) : b ≤ a := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le' [linear_order α] {a b : α} : (∀ ⦃c⦄, a < c → b < c) ↔ b ≤ a := ⟨le_of_forall_lt', λ h c hac, lt_of_le_of_lt h hac⟩ lemma eq_of_forall_ge_iff [partial_order α] {a b : α} (H : ∀ c, a ≤ c ↔ b ≤ c) : a = b := ((H _).2 le_rfl).antisymm ((H _).1 le_rfl) /-- A symmetric relation implies two values are equal, when it implies they're less-equal. -/ lemma rel_imp_eq_of_rel_imp_le [partial_order β] (r : α → α → Prop) [is_symm α r] {f : α → β} (h : ∀ a b, r a b → f a ≤ f b) {a b : α} : r a b → f a = f b := λ hab, le_antisymm (h a b hab) (h b a $ symm hab) /-- monotonicity of `≤` with respect to `→` -/ lemma le_implies_le_of_le_of_le {a b c d : α} [preorder α] (hca : c ≤ a) (hbd : b ≤ d) : a ≤ b → c ≤ d := λ hab, (hca.trans hab).trans hbd @[ext] lemma preorder.to_has_le_injective {α : Type*} : function.injective (@preorder.to_has_le α) := λ A B h, begin cases A, cases B, injection h with h_le, have : A_lt = B_lt, { funext a b, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le h_le, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, h_le], }, congr', end @[ext] lemma partial_order.to_preorder_injective {α : Type*} : function.injective (@partial_order.to_preorder α) := λ A B h, by { cases A, cases B, injection h, congr' } @[ext] lemma linear_order.to_partial_order_injective {α : Type*} : function.injective (@linear_order.to_partial_order α) := begin intros A B h, cases A, cases B, injection h, obtain rfl : A_le = B_le := ‹_›, obtain rfl : A_lt = B_lt := ‹_›, obtain rfl : A_decidable_le = B_decidable_le := subsingleton.elim _ _, obtain rfl : A_max = B_max := A_max_def.trans B_max_def.symm, obtain rfl : A_min = B_min := A_min_def.trans B_min_def.symm, congr end theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } /-- Given a relation `R` on `β` and a function `f : α → β`, the preimage relation on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique relation on `α` making `f` a `rel_embedding` (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) : Prop := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ /-! ### Order dual -/ /-- Type synonym to equip a type with the dual order: `≤` means `≥` and `<` means `>`. `αᵒᵈ` is notation for `order_dual α`. -/ def order_dual (α : Type*) : Type* := α notation α `ᵒᵈ`:std.prec.max_plus := order_dual α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty αᵒᵈ := h instance (α : Type*) [h : subsingleton α] : subsingleton αᵒᵈ := h instance (α : Type*) [has_le α] : has_le αᵒᵈ := ⟨λ x y : α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt αᵒᵈ := ⟨λ x y : α, y < x⟩ instance (α : Type*) [has_zero α] : has_zero αᵒᵈ := ⟨(0 : α)⟩ instance (α : Type*) [preorder α] : preorder αᵒᵈ := { le_refl := le_refl, le_trans := λ a b c hab hbc, hbc.trans hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order αᵒᵈ := { le_antisymm := λ a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order αᵒᵈ := { le_total := λ a b : α, le_total b a, decidable_le := (infer_instance : decidable_rel (λ a b : α, b ≤ a)), decidable_lt := (infer_instance : decidable_rel (λ a b : α, b < a)), min := @max α _, max := @min α _, min_def := @linear_order.max_def α _, max_def := @linear_order.min_def α _, .. order_dual.partial_order α } instance : Π [inhabited α], inhabited αᵒᵈ := id theorem preorder.dual_dual (α : Type*) [H : preorder α] : order_dual.preorder αᵒᵈ = H := preorder.ext $ λ _ _, iff.rfl theorem partial_order.dual_dual (α : Type*) [H : partial_order α] : order_dual.partial_order αᵒᵈ = H := partial_order.ext $ λ _ _, iff.rfl theorem linear_order.dual_dual (α : Type*) [H : linear_order α] : order_dual.linear_order αᵒᵈ = H := linear_order.ext $ λ _ _, iff.rfl end order_dual /-! ### Order instances on the function space -/ instance pi.has_le {ι : Type u} {α : ι → Type v} [∀ i, has_le (α i)] : has_le (Π i, α i) := { le := λ x y, ∀ i, x i ≤ y i } lemma pi.le_def {ι : Type u} {α : ι → Type v} [∀ i, has_le (α i)] {x y : Π i, α i} : x ≤ y ↔ ∀ i, x i ≤ y i := iff.rfl instance pi.preorder {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] : preorder (Π i, α i) := { le_refl := λ a i, le_refl (a i), le_trans := λ a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i), ..pi.has_le } lemma pi.lt_def {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] {x y : Π i, α i} : x < y ↔ x ≤ y ∧ ∃ i, x i < y i := by simp [lt_iff_le_not_le, pi.le_def] {contextual := tt} lemma le_update_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a : α i} : x ≤ function.update y i a ↔ x i ≤ a ∧ ∀ j ≠ i, x j ≤ y j := function.forall_update_iff _ (λ j z, x j ≤ z) lemma update_le_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a : α i} : function.update x i a ≤ y ↔ a ≤ y i ∧ ∀ j ≠ i, x j ≤ y j := function.forall_update_iff _ (λ j z, z ≤ y j) lemma update_le_update_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a b : α i} : function.update x i a ≤ function.update y i b ↔ a ≤ b ∧ ∀ j ≠ i, x j ≤ y j := by simp [update_le_iff] {contextual := tt} instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀ i, partial_order (α i)] : partial_order (Π i, α i) := { le_antisymm := λ f g h1 h2, funext (λ b, (h1 b).antisymm (h2 b)), ..pi.preorder } /-! ### `min`/`max` recursors -/ section min_max_rec variables [linear_order α] {p : α → Prop} {x y : α} lemma min_rec (hx : x ≤ y → p x) (hy : y ≤ x → p y) : p (min x y) := (le_total x y).rec (λ h, (min_eq_left h).symm.subst (hx h)) (λ h, (min_eq_right h).symm.subst (hy h)) lemma max_rec (hx : y ≤ x → p x) (hy : x ≤ y → p y) : p (max x y) := @min_rec αᵒᵈ _ _ _ _ hx hy lemma min_rec' (p : α → Prop) (hx : p x) (hy : p y) : p (min x y) := min_rec (λ _, hx) (λ _, hy) lemma max_rec' (p : α → Prop) (hx : p x) (hy : p y) : p (max x y) := max_rec (λ _, hx) (λ _, hy) end min_max_rec /-! ### `has_sup` and `has_inf` -/ /-- Typeclass for the `⊔` (`\lub`) notation -/ @[notation_class] class has_sup (α : Type u) := (sup : α → α → α) /-- Typeclass for the `⊓` (`\glb`) notation -/ @[notation_class] class has_inf (α : Type u) := (inf : α → α → α) infix ⊔ := has_sup.sup infix ⊓ := has_inf.inf /-! ### Lifts of order instances -/ /-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. See note [reducible non-instances]. -/ @[reducible] def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λ x y, f x ≤ f y, le_refl := λ a, le_rfl, le_trans := λ a b c, le_trans, lt := λ x y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } /-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective function `f : α → β`. See note [reducible non-instances]. -/ @[reducible] def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (h₁.antisymm h₂), .. preorder.lift f } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. This version takes `[has_sup α]` and `[has_inf α]` as arguments, then uses them for `max` and `min` fields. See `linear_order.lift'` for a version that autogenerates `min` and `max` fields. See note [reducible non-instances]. -/ @[reducible] def linear_order.lift {α β} [linear_order β] [has_sup α] [has_inf α] (f : α → β) (inj : injective f) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_order α := { le_total := λ x y, le_total (f x) (f y), decidable_le := λ x y, (infer_instance : decidable (f x ≤ f y)), decidable_lt := λ x y, (infer_instance : decidable (f x < f y)), decidable_eq := λ x y, decidable_of_iff (f x = f y) inj.eq_iff, min := (⊓), max := (⊔), min_def := by { ext x y, apply inj, rw [hinf, min_def, min_default, apply_ite f], refl }, max_def := by { ext x y, apply inj, rw [hsup, max_def, max_default, apply_ite f], refl }, .. partial_order.lift f inj } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. This version autogenerates `min` and `max` fields. See `linear_order.lift` for a version that takes `[has_sup α]` and `[has_inf α]`, then uses them as `max` and `min`. See note [reducible non-instances]. -/ @[reducible] def linear_order.lift' {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := @linear_order.lift α β _ ⟨λ x y, if f y ≤ f x then x else y⟩ ⟨λ x y, if f x ≤ f y then x else y⟩ f inj (λ x y, (apply_ite f _ _ _).trans (max_def _ _).symm) (λ x y, (apply_ite f _ _ _).trans (min_def _ _).symm) /-! ### Subtype of an order -/ namespace subtype instance [has_le α] {p : α → Prop} : has_le (subtype p) := ⟨λ x y, (x : α) ≤ y⟩ instance [has_lt α] {p : α → Prop} : has_lt (subtype p) := ⟨λ x y, (x : α) < y⟩ @[simp] lemma mk_le_mk [has_le α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : subtype p) ≤ ⟨y, hy⟩ ↔ x ≤ y := iff.rfl @[simp] lemma mk_lt_mk [has_lt α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : subtype p) < ⟨y, hy⟩ ↔ x < y := iff.rfl @[simp, norm_cast] lemma coe_le_coe [has_le α] {p : α → Prop} {x y : subtype p} : (x : α) ≤ y ↔ x ≤ y := iff.rfl @[simp, norm_cast] lemma coe_lt_coe [has_lt α] {p : α → Prop} {x y : subtype p} : (x : α) < y ↔ x < y := iff.rfl instance [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift (coe : subtype p → α) instance partial_order [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift coe subtype.coe_injective instance decidable_le [preorder α] [h : @decidable_rel α (≤)] {p : α → Prop} : @decidable_rel (subtype p) (≤) := λ a b, h a b instance decidable_lt [preorder α] [h : @decidable_rel α (<)] {p : α → Prop} : @decidable_rel (subtype p) (<) := λ a b, h a b /-- A subtype of a linear order is a linear order. We explicitly give the proofs of decidable equality and decidable order in order to ensure the decidability instances are all definitionally equal. -/ instance [linear_order α] (p : α → Prop) : linear_order (subtype p) := @linear_order.lift (subtype p) _ _ ⟨λ x y, ⟨max x y, max_rec' _ x.2 y.2⟩⟩ ⟨λ x y, ⟨min x y, min_rec' _ x.2 y.2⟩⟩ coe subtype.coe_injective (λ _ _, rfl) (λ _ _, rfl) end subtype /-! ### Pointwise order on `α × β` The lexicographic order is defined in `data.prod.lex`, and the instances are available via the type synonym `α ×ₗ β = α × β`. -/ namespace prod instance (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λ p q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ lemma le_def [has_le α] [has_le β] {x y : α × β} : x ≤ y ↔ x.1 ≤ y.1 ∧ x.2 ≤ y.2 := iff.rfl @[simp] lemma mk_le_mk [has_le α] [has_le β] {x₁ x₂ : α} {y₁ y₂ : β} : (x₁, y₁) ≤ (x₂, y₂) ↔ x₁ ≤ x₂ ∧ y₁ ≤ y₂ := iff.rfl @[simp] lemma swap_le_swap [has_le α] [has_le β] {x y : α × β} : x.swap ≤ y.swap ↔ x ≤ y := and_comm _ _ section preorder variables [preorder α] [preorder β] {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α × β} instance (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := λ ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := λ ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } @[simp] lemma swap_lt_swap : x.swap < y.swap ↔ x < y := and_congr swap_le_swap (not_congr swap_le_swap) lemma mk_le_mk_iff_left : (a₁, b) ≤ (a₂, b) ↔ a₁ ≤ a₂ := and_iff_left le_rfl lemma mk_le_mk_iff_right : (a, b₁) ≤ (a, b₂) ↔ b₁ ≤ b₂ := and_iff_right le_rfl lemma mk_lt_mk_iff_left : (a₁, b) < (a₂, b) ↔ a₁ < a₂ := lt_iff_lt_of_le_iff_le' mk_le_mk_iff_left mk_le_mk_iff_left lemma mk_lt_mk_iff_right : (a, b₁) < (a, b₂) ↔ b₁ < b₂ := lt_iff_lt_of_le_iff_le' mk_le_mk_iff_right mk_le_mk_iff_right lemma lt_iff : x < y ↔ x.1 < y.1 ∧ x.2 ≤ y.2 ∨ x.1 ≤ y.1 ∧ x.2 < y.2 := begin refine ⟨λ h, _, _⟩, { by_cases h₁ : y.1 ≤ x.1, { exact or.inr ⟨h.1.1, h.1.2.lt_of_not_le $ λ h₂, h.2 ⟨h₁, h₂⟩⟩ }, { exact or.inl ⟨h.1.1.lt_of_not_le h₁, h.1.2⟩ } }, { rintro (⟨h₁, h₂⟩ | ⟨h₁, h₂⟩), { exact ⟨⟨h₁.le, h₂⟩, λ h, h₁.not_le h.1⟩ }, { exact ⟨⟨h₁, h₂.le⟩, λ h, h₂.not_le h.2⟩ } } end @[simp] lemma mk_lt_mk : (a₁, b₁) < (a₂, b₂) ↔ a₁ < a₂ ∧ b₁ ≤ b₂ ∨ a₁ ≤ a₂ ∧ b₁ < b₂ := lt_iff end preorder /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `α ×ₗ β = α × β`.) -/ instance (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := λ ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (hac.antisymm hca) (hbd.antisymm hdb), .. prod.preorder α β } end prod /-! ### Additional order classes -/ /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [has_lt α] : Prop := (dense : ∀ a₁ a₂ : α, a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂) lemma exists_between [has_lt α] [densely_ordered α] : ∀ {a₁ a₂ : α}, a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [has_lt α] [densely_ordered α] : densely_ordered αᵒᵈ := ⟨λ a₁ a₂ ha, (@exists_between α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀ a, a₂ < a → a₁ ≤ a) : a₁ ≤ a₂ := le_of_not_gt $ λ ha, let ⟨a, ha₁, ha₂⟩ := exists_between ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀ a, a₂ < a → a₁ ≤ a) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀ a₃ < a₁, a₃ ≤ a₂) : a₁ ≤ a₂ := le_of_not_gt $ λ ha, let ⟨a, ha₁, ha₂⟩ := exists_between ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀ a₃ < a₁, a₃ ≤ a₂) : a₁ = a₂ := (le_of_forall_ge_of_dense h₂).antisymm h₁ lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃ a, a₁ < a ∧ a < a₂) ∨ ((∀ a, a₁ < a → a₂ ≤ a) ∧ (∀ a < a₂, a ≤ a₁)) := or_iff_not_imp_left.2 $ λ h, ⟨λ a ha₁, le_of_not_gt $ λ ha₂, h ⟨a, ha₁, ha₂⟩, λ a ha₂, le_of_not_gt $ λ ha₁, h ⟨a, ha₁, ha₂⟩⟩ variables {s : β → β → Prop} {t : γ → γ → Prop} /-! ### Linear order from a total partial order -/ /-- Type synonym to create an instance of `linear_order` from a `partial_order` and `is_total α (≤)` -/ def as_linear_order (α : Type u) := α instance {α} [inhabited α] : inhabited (as_linear_order α) := ⟨ (default : α) ⟩ noncomputable instance as_linear_order.linear_order {α} [partial_order α] [is_total α (≤)] : linear_order (as_linear_order α) := { le_total := @total_of α (≤) _, decidable_le := classical.dec_rel _, .. (_ : partial_order α) }
e42557b45a5d2ddab306e5c5bc5711d8f14ca970
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/group_theory/presented_group.lean
b16ae36e6db932f4d4f7ab0aa1d94faa0bb365c8
[ "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
2,837
lean
/- Copyright (c) 2019 Michael Howes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Howes Defining a group given by generators and relations -/ import group_theory.free_group import group_theory.quotient_group variables {α : Type} /-- Given a set of relations, rels, over a type α, presented_group constructs the group with generators α and relations rels as a quotient of free_group α.-/ def presented_group (rels : set (free_group α)) : Type := quotient_group.quotient $ subgroup.normal_closure rels namespace presented_group instance (rels : set (free_group α)) : group (presented_group (rels)) := quotient_group.group _ /-- `of x` is the canonical map from α to a presented group with generators α. The term x is mapped to the equivalence class of the image of x in free_group α. -/ def of {rels : set (free_group α)} (x : α) : presented_group rels := quotient_group.mk (free_group.of x) section to_group /- Presented groups satisfy a universal property. If β is a group and f : α → β is a map such that the images of f satisfy all the given relations, then f extends uniquely to a group homomorphism from presented_group rels to β -/ variables {β : Type} [group β] {f : α → β} {rels : set (free_group α)} local notation `F` := free_group.to_group f variable (h : ∀ r ∈ rels, F r = 1) -- FIXME why is apply_instance needed here? surely this should be a [] argument in `subgroup.normal_closure_le_normal` lemma closure_rels_subset_ker : subgroup.normal_closure rels ≤ monoid_hom.ker F := subgroup.normal_closure_le_normal (by apply_instance) (λ x w, (monoid_hom.mem_ker _).2 (h x w)) lemma to_group_eq_one_of_mem_closure : ∀ x ∈ subgroup.normal_closure rels, F x = 1 := λ x w, (monoid_hom.mem_ker _).1 $ closure_rels_subset_ker h w /-- The extension of a map f : α → β that satisfies the given relations to a group homomorphism from presented_group rels → β. -/ def to_group : presented_group rels →* β := quotient_group.lift (subgroup.normal_closure rels) (monoid_hom.of F) (to_group_eq_one_of_mem_closure h) @[simp] lemma to_group.of {x : α} : to_group h (of x) = f x := free_group.to_group.of -- FIXME remove the next three, they're now unnecessary @[simp] lemma to_group.mul {x y} : to_group h (x * y) = to_group h x * to_group h y := is_mul_hom.map_mul _ _ _ @[simp] lemma to_group.one : to_group h 1 = 1 := is_group_hom.map_one _ @[simp] lemma to_group.inv {x}: to_group h x⁻¹ = (to_group h x)⁻¹ := is_group_hom.map_inv _ _ theorem to_group.unique (g : presented_group rels →* β) (hg : ∀ x : α, g (of x) = f x) : ∀ {x}, g x = to_group h x := λ x, quotient_group.induction_on x (λ _, free_group.to_group.unique (g.comp (quotient_group.mk' _)) hg) end to_group end presented_group
ebb79f5fed776e481996f537991a3703b02d14ca
35b83be3126daae10419b573c55e1fed009d3ae8
/_target/deps/mathlib/data/holor.lean
db39d993d1ef44934da137f4619f71fc1690719d
[]
no_license
AHassan1024/Lean_Playground
ccb25b72029d199c0d23d002db2d32a9f2689ebc
a00b004c3a2eb9e3e863c361aa2b115260472414
refs/heads/master
1,586,221,905,125
1,544,951,310,000
1,544,951,310,000
157,934,290
0
0
null
null
null
null
UTF-8
Lean
false
false
13,392
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp Basic properties of holors. Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. Based on the tensor library found in https://www.isa-afp.org/entries/Deep_Learning.html. -/ import data.list.basic import algebra.module import tactic.interactive import tactic.tidy import tactic.pi_instances universes u open list /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimenstions `ds` -/ def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds} namespace holor_index variables {ds₁ ds₂ ds₃ : list ℕ} def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩ def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂ | ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩ lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm) lemma take_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left]) lemma drop_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds:list ℕ) := holor_index ds → α namespace holor variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ} instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩ instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩ instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, (x t) + (y t)⟩ instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩ instance [add_semigroup α] : add_semigroup (holor α ds) := by pi_instance instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by pi_instance instance [add_monoid α] : add_monoid (holor α ds) := by pi_instance instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by pi_instance instance [add_group α] : add_group (holor α ds) := by pi_instance instance [add_comm_group α] : add_comm_group (holor α ds) := by pi_instance /- scalar product -/ instance [has_mul α] : has_scalar α (holor α ds) := ⟨λ a x, λ t, a * x t⟩ instance [ring α] : module α (holor α ds) := by pi_instance instance [field α] : vector_space α (holor α ds) := ⟨α, (holor α ds)⟩ /- tensor product -/ def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := λ t, x (t.take) * y (t.drop) local infix ` ⊗ ` : 70 := mul lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm) lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left := funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃): mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext (λt, right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))) @[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) : (0 : holor α ds₁) ⊗ x = 0 := funext (λ t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) : x ⊗ (0 :holor α ds₂) = 0 := funext (λ t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) : x ⊗ y = x ⟨[], forall₂.nil⟩ • y := by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := (λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩) def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := λ ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop): Π (t : holor_index (d :: ds)), (∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t | ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨(i :: is), hforall₂⟩ hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis, have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forall₂_cons.1 hiisdds).1, have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 := funext $ λ t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)): slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)]) lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) : slice (0 : holor α (d :: ds)) i hid = 0 := funext (λ t, by simp [slice]; refl) lemma slice_sum [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)): finset.sum s (λ x, slice (f x) i hid) = slice (finset.sum s f) i hid := begin letI := classical.dec_eq β, refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) : (finset.range d).attach.sum (λ i, unit_vec d i.1 ⊗ slice x i.1 (nat.succ_le_of_lt (finset.mem_range.1 i.2))) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i _), { simp, refl }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩), have hbi' : i ≠ b.val, { apply not.imp hbi, { assume h0 : i = b.val, apply subtype.eq, simp only [h0] }, { exact finset.mem_range.2 hid } }, simp [hbi']}, { assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop | nil (x : holor α []) : cprank_max1 x | cons {d} {ds} (x : holor α [d]) (y : holor α ds) : cprank_max1 y → cprank_max1 (x ⊗ y) inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop | zero {ds} : cprank_max 0 (0 : holor α ds) | succ n {ds} (x : holor α ds) (y : holor α ds) : cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid α] [add_monoid α]: ∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds}, cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hx₂ hy } end lemma cprank_max_mul [ring α] : ∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x y₂ hy₂ } end lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (finset.sum s f) := by letI := classical.dec_eq β; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x ∉ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (finset.sum s f), { apply ih, assume (x : β) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Π (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)), from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end noncomputable def cprank [ring α] (x : holor α ds) : nat := @nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod := λ ds (x : holor α ds), by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
f94a94cbd2de9d8ed5f885833724679d4ab30367
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/sites/compatible_plus.lean
3e654c5ccbef904712ae4f4c256924f1aa07b4fe
[ "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
8,149
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.sites.sheafification import category_theory.sites.whiskering /-! In this file, we prove that the plus functor is compatible with functors which preserve the correct limits and colimits. See `category_theory/sites/compatible_sheafification` for the compatibility of sheafification, which follows easily from the content in this file. -/ namespace category_theory.grothendieck_topology open category_theory open category_theory.limits open opposite universes w₁ w₂ v u variables {C : Type u} [category.{v} C] (J : grothendieck_topology C) variables {D : Type w₁} [category.{max v u} D] variables {E : Type w₂} [category.{max v u} E] variables (F : D ⥤ E) noncomputable theory variables [∀ (α β : Type (max v u)) (fst snd : β → α), has_limits_of_shape (walking_multicospan fst snd) D] variables [∀ (α β : Type (max v u)) (fst snd : β → α), has_limits_of_shape (walking_multicospan fst snd) E] variables [∀ (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] variables (P : Cᵒᵖ ⥤ D) /-- The diagram used to define `P⁺`, composed with `F`, is isomorphic to the diagram used to define `P ⋙ F`. -/ def diagram_comp_iso (X : C) : J.diagram P X ⋙ F ≅ J.diagram (P ⋙ F) X := nat_iso.of_components (λ W, begin refine _ ≪≫ has_limit.iso_of_nat_iso (W.unop.multicospan_comp _ _).symm, refine (is_limit_of_preserves F (limit.is_limit _)).cone_point_unique_up_to_iso (limit.is_limit _) end) begin intros A B f, ext, dsimp, simp only [functor.map_cone_π_app, multiequalizer.multifork_π_app_left, iso.symm_hom, multiequalizer.lift_ι, eq_to_hom_refl, category.comp_id, limit.cone_point_unique_up_to_iso_hom_comp, grothendieck_topology.cover.multicospan_comp_hom_inv_left, has_limit.iso_of_nat_iso_hom_π, category.assoc], simp only [← F.map_comp, multiequalizer.lift_ι], end @[simp, reassoc] lemma diagram_comp_iso_hom_ι (X : C) (W : (J.cover X)ᵒᵖ) (i : W.unop.arrow): (J.diagram_comp_iso F P X).hom.app W ≫ multiequalizer.ι _ i = F.map (multiequalizer.ι _ _) := begin delta diagram_comp_iso, dsimp, simp, end variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ E] variables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] /-- The isomorphism between `P⁺ ⋙ F` and `(P ⋙ F)⁺`. -/ def plus_comp_iso : J.plus_obj P ⋙ F ≅ J.plus_obj (P ⋙ F) := nat_iso.of_components (λ X, begin refine _ ≪≫ has_colimit.iso_of_nat_iso (J.diagram_comp_iso F P X.unop), refine (is_colimit_of_preserves F (colimit.is_colimit (J.diagram P (unop X)))).cocone_point_unique_up_to_iso (colimit.is_colimit _) end) begin intros X Y f, apply (is_colimit_of_preserves F (colimit.is_colimit (J.diagram P X.unop))).hom_ext, intros W, dsimp [plus_obj, plus_map], simp only [functor.map_comp, category.assoc], slice_rhs 1 2 { erw (is_colimit_of_preserves F (colimit.is_colimit (J.diagram P X.unop))).fac }, slice_lhs 1 3 { simp only [← F.map_comp], dsimp [colim_map, is_colimit.map, colimit.pre], simp only [colimit.ι_desc_assoc, colimit.ι_desc], dsimp [cocones.precompose], rw [category.assoc, colimit.ι_desc], dsimp [cocone.whisker], rw F.map_comp }, simp only [category.assoc], slice_lhs 2 3 { erw (is_colimit_of_preserves F (colimit.is_colimit (J.diagram P Y.unop))).fac }, dsimp, simp only [has_colimit.iso_of_nat_iso_ι_hom_assoc, grothendieck_topology.diagram_pullback_app, colimit.ι_pre, has_colimit.iso_of_nat_iso_ι_hom, ι_colim_map_assoc], simp only [← category.assoc], congr' 1, ext, dsimp, simp only [category.assoc], erw [multiequalizer.lift_ι, diagram_comp_iso_hom_ι, diagram_comp_iso_hom_ι, ← F.map_comp, multiequalizer.lift_ι], end @[simp, reassoc] lemma ι_plus_comp_iso_hom (X) (W) : F.map (colimit.ι _ W) ≫ (J.plus_comp_iso F P).hom.app X = (J.diagram_comp_iso F P X.unop).hom.app W ≫ colimit.ι _ W := begin delta diagram_comp_iso plus_comp_iso, dsimp [is_colimit.cocone_point_unique_up_to_iso], simp only [← category.assoc], erw (is_colimit_of_preserves F (colimit.is_colimit (J.diagram P (unop X)))).fac, dsimp, simp, end @[simp, reassoc] lemma plus_comp_iso_whisker_left {F G : D ⥤ E} (η : F ⟶ G) (P : Cᵒᵖ ⥤ D) [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] [∀ (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ G] [∀ (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan G] : whisker_left _ η ≫ (J.plus_comp_iso G P).hom = (J.plus_comp_iso F P).hom ≫ J.plus_map (whisker_left _ η) := begin ext X, apply (is_colimit_of_preserves F (colimit.is_colimit (J.diagram P X.unop))).hom_ext, intros W, dsimp [plus_obj, plus_map], simp only [ι_plus_comp_iso_hom, ι_colim_map, whisker_left_app, ι_plus_comp_iso_hom_assoc, nat_trans.naturality_assoc, grothendieck_topology.diagram_nat_trans_app], simp only [← category.assoc], congr' 1, ext, dsimp, simpa, end /-- The isomorphism between `P⁺ ⋙ F` and `(P ⋙ F)⁺`, functorially in `F`. -/ @[simps hom_app inv_app] def plus_functor_whisker_left_iso (P : Cᵒᵖ ⥤ D) [∀ (F : D ⥤ E) (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ F] [∀ (F : D ⥤ E) (X : C) (W : J.cover X) (P : Cᵒᵖ ⥤ D), preserves_limit (W.index P).multicospan F] : (whiskering_left _ _ E).obj (J.plus_obj P) ≅ (whiskering_left _ _ _).obj P ⋙ J.plus_functor E := nat_iso.of_components (λ X, plus_comp_iso _ _ _) $ λ F G η, plus_comp_iso_whisker_left _ _ _ @[simp, reassoc] lemma plus_comp_iso_whisker_right {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : whisker_right (J.plus_map η) F ≫ (J.plus_comp_iso F Q).hom = (J.plus_comp_iso F P).hom ≫ J.plus_map (whisker_right η F) := begin ext X, apply (is_colimit_of_preserves F (colimit.is_colimit (J.diagram P X.unop))).hom_ext, intros W, dsimp [plus_obj, plus_map], simp only [ι_colim_map, whisker_right_app, ι_plus_comp_iso_hom_assoc, grothendieck_topology.diagram_nat_trans_app], simp only [← category.assoc, ← F.map_comp], dsimp [colim_map, is_colimit.map], simp only [colimit.ι_desc], dsimp [cocones.precompose], simp only [functor.map_comp, category.assoc, ι_plus_comp_iso_hom], simp only [← category.assoc], congr' 1, ext, dsimp, simp only [diagram_comp_iso_hom_ι_assoc, multiequalizer.lift_ι, diagram_comp_iso_hom_ι, category.assoc], simp only [← F.map_comp, multiequalizer.lift_ι], end /-- The isomorphism between `P⁺ ⋙ F` and `(P ⋙ F)⁺`, functorially in `P`. -/ @[simps hom_app inv_app] def plus_functor_whisker_right_iso : J.plus_functor D ⋙ (whiskering_right _ _ _).obj F ≅ (whiskering_right _ _ _).obj F ⋙ J.plus_functor E := nat_iso.of_components (λ P, J.plus_comp_iso _ _) $ λ P Q η, plus_comp_iso_whisker_right _ _ _ @[simp, reassoc] lemma whisker_right_to_plus_comp_plus_comp_iso_hom : whisker_right (J.to_plus _) _ ≫ (J.plus_comp_iso F P).hom = J.to_plus _ := begin ext, dsimp [to_plus], simp only [ι_plus_comp_iso_hom, functor.map_comp, category.assoc], simp only [← category.assoc], congr' 1, ext, delta cover.to_multiequalizer, simp only [diagram_comp_iso_hom_ι, category.assoc, ← F.map_comp], erw [multiequalizer.lift_ι, multiequalizer.lift_ι], refl, end @[simp] lemma to_plus_comp_plus_comp_iso_inv : J.to_plus _ ≫ (J.plus_comp_iso F P).inv = whisker_right (J.to_plus _) _ := by simp [iso.comp_inv_eq] lemma plus_comp_iso_inv_eq_plus_lift (hP : presheaf.is_sheaf J ((J.plus_obj P) ⋙ F)) : (J.plus_comp_iso F P).inv = J.plus_lift (whisker_right (J.to_plus _) _) hP := by { apply J.plus_lift_unique, simp [iso.comp_inv_eq] } end category_theory.grothendieck_topology
ba648f984034ff49f7cd6d1a966a1fee5117b711
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/order/basic.lean
cfcad957ae5e947bc1d38db2ecbee5f36f41ec78
[ "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,370
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import data.subtype import data.prod /-! # Basic definitions about `≤` and `<` ## Definitions ### Predicates on functions - `monotone f`: a function between two types equipped with `≤` is monotone if `a ≤ b` implies `f a ≤ f b`. - `strict_mono f` : a function between two types equipped with `<` is strictly monotone if `a < b` implies `f a < f b`. - `order_dual α` : a type tag reversing the meaning of all inequalities. ### Transfering orders - `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `partial_order.lift`, `linear_order.lift`: transfer a partial (resp., linear) order on `β` to a partial (resp., linear) order on `α` using an injective function `f`. ### Extra classes - `no_top_order`, `no_bot_order`: an order without a maximal/minimal element. - `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists `c`, `a<c<b`. ## Main theorems - `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then `f` is monotone; - `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## See also - `algebra.order` for basic lemmas about orders, and projection notation for orders ## Tags preorder, order, partial order, linear order, monotone, strictly monotone -/ open function universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} @[simp] lemma lt_self_iff_false [preorder α] (a : α) : a < a ↔ false := by simp [lt_irrefl a] attribute [ext] has_le @[ext] lemma preorder.to_has_le_injective {α : Type*} : function.injective (@preorder.to_has_le α) := λ A B h, begin cases A, cases B, injection h with h_le, have : A_lt = B_lt, { funext a b, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le h_le, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, h_le], }, congr', end @[ext] lemma partial_order.to_preorder_injective {α : Type*} : function.injective (@partial_order.to_preorder α) := λ A B h, by { cases A, cases B, injection h, congr' } @[ext] lemma linear_order.to_partial_order_injective {α : Type*} : function.injective (@linear_order.to_partial_order α) := λ A B h, by { cases A, cases B, injection h, congr' } theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { ext x y, exact H x y } /-- Given a relation `R` on `β` and a function `f : α → β`, the preimage relation on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique relation on `α` making `f` a `rel_embedding` (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) protected theorem monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) := nat.rec_on n monotone_id (λ n ihn, ihn.comp hf) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma monotone.reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } /-- If `f` is a monotone function from `ℕ` to a preorder such that `y` lies between `f x` and `f (x + 1)`, then `y` doesn't lie in the range of `f`. -/ lemma monotone.ne_of_lt_of_lt_nat {α} [preorder α] {f : ℕ → α} (hf : monotone f) (x x' : ℕ) {y : α} (h1 : f x < y) (h2 : y < f (x + 1)) : f x' ≠ y := by { rintro rfl, apply (hf.reflect_lt h1).not_le, exact nat.le_of_lt_succ (hf.reflect_lt h2) } /-- If `f` is a monotone function from `ℤ` to a preorder such that `y` lies between `f x` and `f (x + 1)`, then `y` doesn't lie in the range of `f`. -/ lemma monotone.ne_of_lt_of_lt_int {α} [preorder α] {f : ℤ → α} (hf : monotone f) (x x' : ℤ) {y : α} (h1 : f x < y) (h2 : y < f (x + 1)) : f x' ≠ y := by { rintro rfl, apply (hf.reflect_lt h1).not_le, exact int.le_of_lt_add_one (hf.reflect_lt h2) } end monotone /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b lemma strict_mono_id [has_lt α] : strict_mono (id : α → α) := λ a b, id /-- A function `f` is strictly monotone increasing on `t` if `x < y` for `x,y ∈ t` implies `f x < f y`. -/ def strict_mono_incr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ t) ⦃y⦄ (hy : y ∈ t), x < y → f x < f y /-- A function `f` is strictly monotone decreasing on `t` if `x < y` for `x,y ∈ t` implies `f y < f x`. -/ def strict_mono_decr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ t) ⦃y⦄ (hy : y ∈ t), x < y → f y < f x /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [h : subsingleton α] : subsingleton (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl lemma dual_compares [has_lt α] {a b : α} {o : ordering} : @ordering.compares (order_dual α) _ o a b ↔ @ordering.compares α _ o b a := by { cases o, exacts [iff.rfl, eq_comm, iff.rfl] } instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, hbc.trans hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.partial_order α } instance : Π [inhabited α], inhabited (order_dual α) := id theorem preorder.dual_dual (α : Type*) [H : preorder α] : order_dual.preorder (order_dual α) = H := preorder.ext $ λ _ _, iff.rfl theorem partial_order.dual_dual (α : Type*) [H : partial_order α] : order_dual.partial_order (order_dual α) = H := partial_order.ext $ λ _ _, iff.rfl theorem linear_order.dual_dual (α : Type*) [H : linear_order α] : order_dual.linear_order (order_dual α) = H := linear_order.ext $ λ _ _, iff.rfl theorem cmp_le_flip {α} [has_le α] [@decidable_rel α (≤)] (x y : α) : @cmp_le (order_dual α) _ _ x y = cmp_le y x := rfl end order_dual namespace strict_mono_incr_on section dual variables [preorder α] [preorder β] {f : α → β} {s : set α} protected lemma dual (H : strict_mono_incr_on f s) : @strict_mono_incr_on (order_dual α) (order_dual β) _ _ f s := λ x hx y hy, H hy hx protected lemma dual_right (H : strict_mono_incr_on f s) : @strict_mono_decr_on α (order_dual β) _ _ f s := H end dual variables [linear_order α] [preorder β] {f : α → β} {s : set α} {x y : α} lemma le_iff_le (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≤ f y ↔ x ≤ y := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H hy hx h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H hx hy h')) (λ h', h' ▸ le_refl _)⟩ lemma lt_iff_lt (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x < f y ↔ x < y := by simp only [H.le_iff_le, hx, hy, lt_iff_le_not_le] protected theorem compares (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : ∀ {o}, ordering.compares o (f x) (f y) ↔ ordering.compares o x y | ordering.lt := H.lt_iff_lt hx hy | ordering.eq := ⟨λ h, le_antisymm ((H.le_iff_le hx hy).1 h.le) ((H.le_iff_le hy hx).1 h.symm.le), congr_arg _⟩ | ordering.gt := H.lt_iff_lt hy hx end strict_mono_incr_on namespace strict_mono_decr_on section dual variables [preorder α] [preorder β] {f : α → β} {s : set α} protected lemma dual (H : strict_mono_decr_on f s) : @strict_mono_decr_on (order_dual α) (order_dual β) _ _ f s := λ x hx y hy, H hy hx protected lemma dual_right (H : strict_mono_decr_on f s) : @strict_mono_incr_on α (order_dual β) _ _ f s := H end dual variables [linear_order α] [preorder β] {f : α → β} {s : set α} {x y : α} lemma le_iff_le (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≤ f y ↔ y ≤ x := H.dual_right.le_iff_le hy hx lemma lt_iff_lt (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x < f y ↔ y < x := H.dual_right.lt_iff_lt hy hx protected theorem compares (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) {o : ordering} : ordering.compares o (f x) (f y) ↔ ordering.compares o y x := order_dual.dual_compares.trans $ H.dual_right.compares hy hx end strict_mono_decr_on namespace strict_mono open ordering function protected lemma strict_mono_incr_on [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) (s : set α) : strict_mono_incr_on f s := λ x hx y hy hxy, hf hxy lemma comp [has_lt α] [has_lt β] [has_lt γ] {g : β → γ} {f : α → β} (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) protected theorem iterate [has_lt α] {f : α → α} (hf : strict_mono f) (n : ℕ) : strict_mono (f^[n]) := nat.rec_on n strict_mono_id (λ n ihn, ihn.comp hf) lemma id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n := λ n, nat.rec_on n (nat.zero_le _) (λ n hn, nat.succ_le_of_lt (lt_of_le_of_lt hn $ h $ nat.lt_succ_self n)) protected lemma ite' [preorder α] [has_lt β] {f g : α → β} (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ ⦃x y⦄, p x → ¬p y → x < y → f x < g y) : strict_mono (λ x, if p x then f x else g x) := begin intros x y h, by_cases hy : p y, { have hx : p x := hp h hy, simpa [hx, hy] using hf h }, { by_cases hx : p x, { simpa [hx, hy] using hfg hx hy h }, { simpa [hx, hy] using hg h} } end protected lemma ite [preorder α] [preorder β] {f g : α → β} (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ x, f x ≤ g x) : strict_mono (λ x, if p x then f x else g x) := hf.ite' hg hp $ λ x y hx hy h, (hf h).trans_le (hfg y) section variables [linear_order α] [preorder β] {f : α → β} lemma lt_iff_lt (H : strict_mono f) {a b} : f a < f b ↔ a < b := (H.strict_mono_incr_on set.univ).lt_iff_lt trivial trivial protected theorem compares (H : strict_mono f) {a b} {o} : compares o (f a) (f b) ↔ compares o a b := (H.strict_mono_incr_on set.univ).compares trivial trivial lemma injective (H : strict_mono f) : injective f := λ x y h, show compares eq x y, from H.compares.1 h lemma le_iff_le (H : strict_mono f) {a b} : f a ≤ f b ↔ a ≤ b := (H.strict_mono_incr_on set.univ).le_iff_le trivial trivial lemma top_preimage_top (H : strict_mono f) {a} (h_top : ∀ p, p ≤ f a) (x : α) : x ≤ a := H.le_iff_le.mp (h_top (f x)) lemma bot_preimage_bot (H : strict_mono f) {a} (h_bot : ∀ p, f a ≤ p) (x : α) : a ≤ x := H.le_iff_le.mp (h_bot (f x)) end protected lemma nat {β} [preorder β] {f : ℕ → β} (h : ∀n, f n < f (n+1)) : strict_mono f := by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact ih.trans (h _) } -- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation, -- then `strict_mono f` is vacuously true. lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f := λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (@H _ _)) (by rintro rfl; refl) end strict_mono section open function lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : injective f := begin intros x y k, contrapose k, rw [←ne.def, ne_iff_lt_or_gt] at k, cases k, { apply h _ _ k }, { rw eq_comm, apply h _ _ k } end lemma strict_mono_of_monotone_of_injective [partial_order α] [partial_order β] {f : α → β} (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, begin rw lt_iff_le_and_ne at ⊢ h, exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩ end lemma monotone.strict_mono_iff_injective [linear_order α] [partial_order β] {f : α → β} (h : monotone f) : strict_mono f ↔ injective f := ⟨λ h, h.injective, strict_mono_of_monotone_of_injective h⟩ lemma strict_mono_of_le_iff_le [preorder α] [preorder β] {f : α → β} (h : ∀ x y, x ≤ y ↔ f x ≤ f y) : strict_mono f := λ a b, by simp [lt_iff_le_not_le, h] {contextual := tt} end /-! ### Order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } lemma pi.le_def {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] {x y : Π i, α i} : x ≤ y ↔ ∀ i, x i ≤ y i := iff.rfl lemma pi.lt_def {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] {x y : Π i, α i} : x < y ↔ x ≤ y ∧ ∃ i, x i < y i := by simp [lt_iff_le_not_le, pi.le_def] {contextual := tt} lemma le_update_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a : α i} : x ≤ function.update y i a ↔ x i ≤ a ∧ ∀ j ≠ i, x j ≤ y j := function.forall_update_iff _ (λ j z, x j ≤ z) lemma update_le_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a : α i} : function.update x i a ≤ y ↔ a ≤ y i ∧ ∀ j ≠ i, x j ≤ y j := function.forall_update_iff _ (λ j z, z ≤ y j) lemma update_le_update_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a b : α i} : function.update x i a ≤ function.update y i b ↔ a ≤ b ∧ ∀ j ≠ i, x j ≤ y j := by simp [update_le_iff] {contextual := tt} instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] protected theorem monotone.order_dual {f : α → γ} (hf : monotone f) : @monotone (order_dual α) (order_dual γ) _ _ f := λ x y hxy, hf hxy theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone theorem strict_mono.order_dual [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) : @strict_mono (order_dual α) (order_dual β) _ _ f := λ x y hxy, hf hxy /-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/ def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } /-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective function `f : α → β`. -/ def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. -/ def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := { le_total := λx y, le_total (f x) (f y), decidable_le := λ x y, (infer_instance : decidable (f x ≤ f y)), decidable_lt := λ x y, (infer_instance : decidable (f x < f y)), decidable_eq := λ x y, decidable_of_iff _ inj.eq_iff, .. partial_order.lift f inj } instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val @[simp] lemma subtype.mk_le_mk {α} [preorder α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : subtype p) ≤ ⟨y, hy⟩ ↔ x ≤ y := iff.rfl @[simp] lemma subtype.mk_lt_mk {α} [preorder α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : subtype p) < ⟨y, hy⟩ ↔ x < y := iff.rfl @[simp, norm_cast] lemma subtype.coe_le_coe {α} [preorder α] {p : α → Prop} {x y : subtype p} : (x : α) ≤ y ↔ x ≤ y := iff.rfl @[simp, norm_cast] lemma subtype.coe_lt_coe {α} [preorder α] {p : α → Prop} {x y : subtype p} : (x : α) < y ↔ x < y := iff.rfl instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective lemma subtype.mono_coe [preorder α] (t : set α) : monotone (coe : (subtype t) → α) := λ x y, id lemma subtype.strict_mono_coe [preorder α] (t : set α) : strict_mono (coe : (subtype t) → α) := λ x y, id instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /-! ### Additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top instance nonempty_gt {α : Type u} [preorder α] [no_top_order α] (a : α) : nonempty {x // a < x} := nonempty_subtype.2 (no_top a) /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ instance nonempty_lt {α : Type u} [preorder α] [no_bot_order α] (a : α) : nonempty {x // x < a} := nonempty_subtype.2 (no_bot a) /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma exists_between [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@exists_between α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := exists_between ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃<a₁, a₃ ≤ a₂) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := exists_between ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₃ ≤ a₂) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a₂ ≤ a) ∧ (∀a<a₂, a ≤ a₁)) := or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ variables {s : β → β → Prop} {t : γ → γ → Prop} /-- Type synonym to create an instance of `linear_order` from a `partial_order` and `[is_total α (≤)]` -/ def as_linear_order (α : Type u) := α instance {α} [inhabited α] : inhabited (as_linear_order α) := ⟨ (default α : α) ⟩ noncomputable instance as_linear_order.linear_order {α} [partial_order α] [is_total α (≤)] : linear_order (as_linear_order α) := { le_total := @total_of α (≤) _, decidable_le := classical.dec_rel _, .. (_ : partial_order α) }
6268e75b7b995afd3990d5072c6c31a745cec6af
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/RightShelf.lean
84cdf68e31d49d4dbacae3222e33c4241ad0ee7f
[]
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
5,962
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 RightShelf structure RightShelf (A : Type) : Type := (rinv : (A → (A → A))) (rightDistributive : (∀ {x y z : A} , (rinv (rinv y z) x) = (rinv (rinv y x) (rinv z x)))) open RightShelf structure Sig (AS : Type) : Type := (rinvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (rinvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (rightDistributiveP : (∀ {xP yP zP : (Prod A A)} , (rinvP (rinvP yP zP) xP) = (rinvP (rinvP yP xP) (rinvP zP xP)))) structure Hom {A1 : Type} {A2 : Type} (Ri1 : (RightShelf A1)) (Ri2 : (RightShelf A2)) : Type := (hom : (A1 → A2)) (pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Ri1) x1 x2)) = ((rinv Ri2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (RightShelf A1)) (Ri2 : (RightShelf A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Ri1) x1 x2) ((rinv Ri2) y1 y2)))))) inductive RightShelfTerm : Type | rinvL : (RightShelfTerm → (RightShelfTerm → RightShelfTerm)) open RightShelfTerm inductive ClRightShelfTerm (A : Type) : Type | sing : (A → ClRightShelfTerm) | rinvCl : (ClRightShelfTerm → (ClRightShelfTerm → ClRightShelfTerm)) open ClRightShelfTerm inductive OpRightShelfTerm (n : ℕ) : Type | v : ((fin n) → OpRightShelfTerm) | rinvOL : (OpRightShelfTerm → (OpRightShelfTerm → OpRightShelfTerm)) open OpRightShelfTerm inductive OpRightShelfTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRightShelfTerm2) | sing2 : (A → OpRightShelfTerm2) | rinvOL2 : (OpRightShelfTerm2 → (OpRightShelfTerm2 → OpRightShelfTerm2)) open OpRightShelfTerm2 def simplifyCl {A : Type} : ((ClRightShelfTerm A) → (ClRightShelfTerm A)) | (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRightShelfTerm n) → (OpRightShelfTerm n)) | (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpRightShelfTerm2 n A) → (OpRightShelfTerm2 n A)) | (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((RightShelf A) → (RightShelfTerm → A)) | Ri (rinvL x1 x2) := ((rinv Ri) (evalB Ri x1) (evalB Ri x2)) def evalCl {A : Type} : ((RightShelf A) → ((ClRightShelfTerm A) → A)) | Ri (sing x1) := x1 | Ri (rinvCl x1 x2) := ((rinv Ri) (evalCl Ri x1) (evalCl Ri x2)) def evalOpB {A : Type} {n : ℕ} : ((RightShelf A) → ((vector A n) → ((OpRightShelfTerm n) → A))) | Ri vars (v x1) := (nth vars x1) | Ri vars (rinvOL x1 x2) := ((rinv Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) def evalOp {A : Type} {n : ℕ} : ((RightShelf A) → ((vector A n) → ((OpRightShelfTerm2 n A) → A))) | Ri vars (v2 x1) := (nth vars x1) | Ri vars (sing2 x1) := x1 | Ri vars (rinvOL2 x1 x2) := ((rinv Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) def inductionB {P : (RightShelfTerm → Type)} : ((∀ (x1 x2 : RightShelfTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : RightShelfTerm) , (P x))) | prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB prinvl x1) (inductionB prinvl x2)) def inductionCl {A : Type} {P : ((ClRightShelfTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRightShelfTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClRightShelfTerm A)) , (P x)))) | psing prinvcl (sing x1) := (psing x1) | psing prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing prinvcl x1) (inductionCl psing prinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpRightShelfTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRightShelfTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpRightShelfTerm n)) , (P x)))) | pv prinvol (v x1) := (pv x1) | pv prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv prinvol x1) (inductionOpB pv prinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpRightShelfTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRightShelfTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpRightShelfTerm2 n A)) , (P x))))) | pv2 psing2 prinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 prinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 prinvol2 x1) (inductionOp pv2 psing2 prinvol2 x2)) def stageB : (RightShelfTerm → (Staged RightShelfTerm)) | (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClRightShelfTerm A) → (Staged (ClRightShelfTerm A))) | (sing x1) := (Now (sing x1)) | (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpRightShelfTerm n) → (Staged (OpRightShelfTerm n))) | (v x1) := (const (code (v x1))) | (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpRightShelfTerm2 n A) → (Staged (OpRightShelfTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (rinvT : ((Repr A) → ((Repr A) → (Repr A)))) end RightShelf
0273c8249850e2ed8bd3984b9f817f391494624a
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/library/data/set.lean
769f7b4bdfffaedd6b9a86e68cee4007706c91eb
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,976
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.set Author: Jeremy Avigad, Leonardo de Moura -/ import logic open eq.ops namespace set definition set (T : Type) := T → Prop definition mem [reducible] {T : Type} (x : T) (s : set T) := s x notation e ∈ s := mem e s variable {T : Type} definition eqv (A B : set T) : Prop := ∀x, x ∈ A ↔ x ∈ B notation a ∼ b := eqv a b theorem eqv_refl (A : set T) : A ∼ A := take x, iff.rfl theorem eqv_symm {A B : set T} (H : A ∼ B) : B ∼ A := take x, iff.symm (H x) theorem eqv_trans {A B C : set T} (H1 : A ∼ B) (H2 : B ∼ C) : A ∼ C := take x, iff.trans (H1 x) (H2 x) definition empty [reducible] : set T := λx, false notation `∅` := empty theorem mem_empty (x : T) : ¬ (x ∈ ∅) := assume H : x ∈ ∅, H definition univ : set T := λx, true theorem mem_univ (x : T) : x ∈ univ := trivial definition inter [reducible] (A B : set T) : set T := λx, x ∈ A ∧ x ∈ B notation a ∩ b := inter a b theorem mem_inter (x : T) (A B : set T) : x ∈ A ∩ B ↔ (x ∈ A ∧ x ∈ B) := !iff.refl theorem inter_id (A : set T) : A ∩ A ∼ A := take x, iff.intro (assume H, and.elim_left H) (assume H, and.intro H H) theorem inter_empty_right (A : set T) : A ∩ ∅ ∼ ∅ := take x, iff.intro (assume H, and.elim_right H) (assume H, false.elim H) theorem inter_empty_left (A : set T) : ∅ ∩ A ∼ ∅ := take x, iff.intro (assume H, and.elim_left H) (assume H, false.elim H) theorem inter_comm (A B : set T) : A ∩ B ∼ B ∩ A := take x, !and.comm theorem inter_assoc (A B C : set T) : (A ∩ B) ∩ C ∼ A ∩ (B ∩ C) := take x, !and.assoc definition union [reducible] (A B : set T) : set T := λx, x ∈ A ∨ x ∈ B notation a ∪ b := union a b theorem mem_union (x : T) (A B : set T) : x ∈ A ∪ B ↔ (x ∈ A ∨ x ∈ B) := !iff.refl theorem union_id (A : set T) : A ∪ A ∼ A := take x, iff.intro (assume H, match H with | or.inl H₁ := H₁ | or.inr H₂ := H₂ end) (assume H, or.inl H) theorem union_empty_right (A : set T) : A ∪ ∅ ∼ A := take x, iff.intro (assume H, match H with | or.inl H₁ := H₁ | or.inr H₂ := false.elim H₂ end) (assume H, or.inl H) theorem union_empty_left (A : set T) : ∅ ∪ A ∼ A := take x, iff.intro (assume H, match H with | or.inl H₁ := false.elim H₁ | or.inr H₂ := H₂ end) (assume H, or.inr H) theorem union_comm (A B : set T) : A ∪ B ∼ B ∪ A := take x, or.comm theorem union_assoc (A B C : set T) : (A ∪ B) ∪ C ∼ A ∪ (B ∪ C) := take x, or.assoc definition subset (A B : set T) := ∀ x, x ∈ A → x ∈ B infix `⊆`:50 := subset definition eqv_of_subset (A B : set T) : A ⊆ B → B ⊆ A → A ∼ B := assume H₁ H₂, take x, iff.intro (H₁ x) (H₂ x) end set
63a43bbced8598ba594470d307dec59761aef672
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/set/intervals/basic.lean
e3d5e7c29ca18d4c842f1c588a079b9d6d6305da
[ "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
34,826
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot, Yury Kudryashov -/ import algebra.order_functions import data.set.basic /-! # Intervals In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). TODO: This is just the beginning; a lot of rules are missing -/ universe u namespace set open set section intervals variables {α : Type u} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} lemma Ioo_def (a b : α) : {x | a < x ∧ x < b} = Ioo a b := rfl lemma Ico_def (a b : α) : {x | a ≤ x ∧ x < b} = Ico a b := rfl lemma Iio_def (a : α) : {x | x < a} = Iio a := rfl lemma Icc_def (a b : α) : {x | a ≤ x ∧ x ≤ b} = Icc a b := rfl lemma Iic_def (b : α) : {x | x ≤ b} = Iic b := rfl lemma Ioc_def (a b : α) : {x | a < x ∧ x ≤ b} = Ioc a b := rfl lemma Ici_def (a : α) : {x | a ≤ x} = Ici a := rfl lemma Ioi_def (a : α) : {x | a < x} = Ioi a := rfl @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : @Ici (order_dual α) _ a = @Iic α _ a := rfl @[simp] lemma dual_Iic : @Iic (order_dual α) _ a = @Ici α _ a := rfl @[simp] lemma dual_Ioi : @Ioi (order_dual α) _ a = @Iio α _ a := rfl @[simp] lemma dual_Iio : @Iio (order_dual α) _ a = @Ioi α _ a := rfl @[simp] lemma dual_Icc : @Icc (order_dual α) _ a b = @Icc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : @Ioc (order_dual α) _ a b = @Ico α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : @Ico (order_dual α) _ a b = @Ioc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : @Ioo (order_dual α) _ a b = @Ioo α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, le_trans hx.1 hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_le_of_lt hx.1 hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_lt_of_le hx.1 hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, lt_trans ha hb, dense⟩ @[simp] lemma nonempty_Ioi [no_top_order α] : (Ioi a).nonempty := no_top a @[simp] lemma nonempty_Iio [no_bot_order α] : (Iio a).nonempty := no_bot a @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ le_refl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, le_trans h hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici (order_dual α) _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, lt_of_lt_of_le h hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Icc_subset_Ioo (ha : a₂ < a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ := λ x hx, ⟨lt_of_lt_of_le ha hx.1, lt_of_le_of_lt hx.2 hb⟩ lemma Icc_subset_Ici_self : Icc a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Iic_self : Icc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, le_trans hx₂ h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h (le_refl _) lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Ioc_subset_Ioo_right (h : b₁ < b₂) : Ioc a b₁ ⊆ Ioo a b₂ := λ x, and.imp_right $ λ h', lt_of_le_of_lt h' h lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λx hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λx hx, le_of_lt hx lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λx hx, lt_of_le_of_lt h hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λx hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl end intervals section partial_order variables {α : Type u} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] @[simp] lemma Icc_diff_left : Icc a b \ {a} = Ioc a b := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm, and.right_comm] @[simp] lemma Icc_diff_right : Icc a b \ {b} = Ico a b := ext $ λ x, by simp [lt_iff_le_and_ne, and_assoc] @[simp] lemma Ico_diff_left : Ico a b \ {a} = Ioo a b := ext $ λ x, by simp [and.right_comm, ← lt_iff_le_and_ne, eq_comm] @[simp] lemma Ioc_diff_right : Ioc a b \ {b} = Ioo a b := ext $ λ x, by simp [and_assoc, ← lt_iff_le_and_ne] @[simp] lemma Icc_diff_both : Icc a b \ {a, b} = Ioo a b := by rw [insert_eq, ← diff_diff, Icc_diff_left, Ioc_diff_right] @[simp] lemma Ici_diff_left : Ici a \ {a} = Ioi a := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm] @[simp] lemma Iic_diff_right : Iic a \ {a} = Iio a := ext $ λ x, by simp [lt_iff_le_and_ne] @[simp] lemma Ico_diff_Ioo_same (h : a < b) : Ico a b \ Ioo a b = {a} := by rw [← Ico_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Ico.2 h)] @[simp] lemma Ioc_diff_Ioo_same (h : a < b) : Ioc a b \ Ioo a b = {b} := by rw [← Ioc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Ioc.2 h)] @[simp] lemma Icc_diff_Ico_same (h : a ≤ b) : Icc a b \ Ico a b = {b} := by rw [← Icc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioc_same (h : a ≤ b) : Icc a b \ Ioc a b = {a} := by rw [← Icc_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioo_same (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} := by { rw [← Icc_diff_both, diff_diff_cancel_left], simp [insert_subset, h] } @[simp] lemma Ici_diff_Ioi_same : Ici a \ Ioi a = {a} := by rw [← Ici_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 left_mem_Ici)] @[simp] lemma Iic_diff_Iio_same : Iic a \ Iio a = {a} := by rw [← Iic_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 right_mem_Iic)] @[simp] lemma Ioi_union_left : Ioi a ∪ {a} = Ici a := ext $ λ x, by simp [eq_comm, le_iff_eq_or_lt] @[simp] lemma Iio_union_right : Iio a ∪ {a} = Iic a := ext $ λ x, le_iff_lt_or_eq.symm lemma mem_Ici_Ioi_of_subset_of_subset {s : set α} (ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) : s ∈ ({Ici a, Ioi a} : set (set α)) := classical.by_cases (λ h : a ∈ s, or.inl $ subset.antisymm hc $ by rw [← Ioi_union_left, union_subset_iff]; simp *) (λ h, or.inr $ subset.antisymm (λ x hx, lt_of_le_of_ne (hc hx) (λ heq, h $ heq.symm ▸ hx)) ho) lemma mem_Iic_Iio_of_subset_of_subset {s : set α} (ho : Iio a ⊆ s) (hc : s ⊆ Iic a) : s ∈ ({Iic a, Iio a} : set (set α)) := @mem_Ici_Ioi_of_subset_of_subset (order_dual α) _ a s ho hc lemma mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) : s ∈ ({Icc a b, Ico a b, Ioc a b, Ioo a b} : set (set α)) := begin classical, by_cases ha : a ∈ s; by_cases hb : b ∈ s, { refine or.inl (subset.antisymm hc _), rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha, ← Icc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho }, { refine (or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_right], exact subset_diff_singleton hc hb }, { rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha] at ho } }, { refine (or.inr $ or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_left], exact subset_diff_singleton hc ha }, { rwa [← Ioc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho } }, { refine (or.inr $ or.inr $ or.inr $ subset.antisymm _ ho), rw [← Ico_diff_left, ← Icc_diff_right], apply_rules [subset_diff_singleton] } end lemma mem_Ioo_or_eq_endpoints_of_mem_Icc {x : α} (hmem : x ∈ Icc a b) : x = a ∨ x = b ∨ x ∈ Ioo a b := begin rw [mem_Icc, le_iff_lt_or_eq, le_iff_lt_or_eq] at hmem, rcases hmem with ⟨hxa | hxa, hxb | hxb⟩, { exact or.inr (or.inr ⟨hxa, hxb⟩) }, { exact or.inr (or.inl hxb) }, all_goals { exact or.inl hxa.symm } end lemma mem_Ioo_or_eq_left_of_mem_Ico {x : α} (hmem : x ∈ Ico a b) : x = a ∨ x ∈ Ioo a b := begin rw [mem_Ico, le_iff_lt_or_eq] at hmem, rcases hmem with ⟨hxa | hxa, hxb⟩, { exact or.inr ⟨hxa, hxb⟩ }, { exact or.inl hxa.symm } end lemma mem_Ioo_or_eq_right_of_mem_Ioc {x : α} (hmem : x ∈ Ioc a b) : x = b ∨ x ∈ Ioo a b := begin have := @mem_Ioo_or_eq_left_of_mem_Ico (order_dual α) _ b a x, rw [dual_Ioo, dual_Ico] at this, exact this hmem end lemma Ici_singleton_of_top {a : α} (h_top : ∀ x, x ≤ a) : Ici a = {a} := begin ext, exact ⟨λ h, le_antisymm (h_top _) h, λ h, le_of_eq h.symm⟩, end lemma Iic_singleton_of_bot {a : α} (h_bot : ∀ x, a ≤ x) : Iic a = {a} := @Ici_singleton_of_top (order_dual α) _ a h_bot end partial_order section order_top_or_bot variables {α : Type u} @[simp] lemma Ici_top [order_top α] : Ici (⊤ : α) = {⊤} := Ici_singleton_of_top (λ _, le_top) @[simp] lemma Ici_bot [order_bot α] : Iic (⊥ : α) = {⊥} := Iic_singleton_of_bot (λ _, bot_le) end order_top_or_bot section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ : α} @[simp] lemma compl_Iic : (Iic a)ᶜ = Ioi a := ext $ λ _, not_le @[simp] lemma compl_Ici : (Ici a)ᶜ = Iio a := ext $ λ _, not_le @[simp] lemma compl_Iio : (Iio a)ᶜ = Ici a := ext $ λ _, not_lt @[simp] lemma compl_Ioi : (Ioi a)ᶜ = Iic a := ext $ λ _, not_lt @[simp] lemma Ici_diff_Ici : Ici a \ Ici b = Ico a b := by rw [diff_eq, compl_Ici, Ici_inter_Iio] @[simp] lemma Ici_diff_Ioi : Ici a \ Ioi b = Icc a b := by rw [diff_eq, compl_Ioi, Ici_inter_Iic] @[simp] lemma Ioi_diff_Ioi : Ioi a \ Ioi b = Ioc a b := by rw [diff_eq, compl_Ioi, Ioi_inter_Iic] @[simp] lemma Ioi_diff_Ici : Ioi a \ Ici b = Ioo a b := by rw [diff_eq, compl_Ici, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iic : Iic b \ Iic a = Ioc a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iic] @[simp] lemma Iio_diff_Iic : Iio b \ Iic a = Ioo a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iio : Iic b \ Iio a = Icc a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iic] @[simp] lemma Iio_diff_Iio : Iio b \ Iio a = Ico a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iio] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := dense h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases dense h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le ca (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := by rw [← diff_eq_empty, Iio_diff_Iic, Ioo_eq_empty_iff] /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a) @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a) @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a) /-! #### A finite and an infinite interval -/ lemma Ioi_subset_Ioo_union_Ici : Ioi a ⊆ Ioo a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioo_union_Ici lemma Ici_subset_Ico_union_Ici : Ici a ⊆ Ico a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ico_union_Ici_eq_Ici (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Ico_union_Ici lemma Ioi_subset_Ioc_union_Ioi : Ioi a ⊆ Ioc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_le_of_lt h)) Ioi_subset_Ioc_union_Ioi lemma Ici_subset_Icc_union_Ioi : Ici a ⊆ Icc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Icc_union_Ioi_eq_Ici (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (λ hx, le_trans h (le_of_lt hx))) Ici_subset_Icc_union_Ioi lemma Ioi_subset_Ioc_union_Ici : Ioi a ⊆ Ioc a b ∪ Ici b := subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left _ Ioo_subset_Ioc_self) @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioc_union_Ici lemma Ici_subset_Icc_union_Ici : Ici a ⊆ Icc a b ∪ Ici b := subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left _ Ico_subset_Icc_self) @[simp] lemma Icc_union_Ici_eq_Ici (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Icc_union_Ici /-! #### An infinite and a finite interval -/ lemma Iic_subset_Iio_union_Icc : Iic b ⊆ Iio a ∪ Icc a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans (le_of_lt hx) h) and.right) Iic_subset_Iio_union_Icc lemma Iio_subset_Iio_union_Ico : Iio b ⊆ Iio a ∪ Ico a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_lt_of_le hx h) and.right) Iio_subset_Iio_union_Ico lemma Iic_subset_Iic_union_Ioc : Iic b ⊆ Iic a ∪ Ioc a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Ioc lemma Iio_subset_Iic_union_Ioo : Iio b ⊆ Iic a ∪ Ioo a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ioo lemma Iic_subset_Iic_union_Icc : Iic b ⊆ Iic a ∪ Icc a b := subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Icc lemma Iio_subset_Iic_union_Ico : Iio b ⊆ Iic a ∪ Ico a b := subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ico /-! #### Two finite intervals, `I?o` and `Ic?` -/ variable {c : α} lemma Ioo_subset_Ioo_union_Ico : Ioo a c ⊆ Ioo a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioo_subset_Ioo_union_Ico lemma Ico_subset_Ico_union_Ico : Ico a c ⊆ Ico a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Ico_subset_Ico_union_Ico lemma Icc_subset_Ico_union_Icc : Icc a c ⊆ Ico a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Icc_subset_Ico_union_Icc lemma Ioc_subset_Ioo_union_Icc : Ioc a c ⊆ Ioo a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioc_subset_Ioo_union_Icc /-! #### Two finite intervals, `I?c` and `Io?` -/ lemma Ioo_subset_Ioc_union_Ioo : Ioo a c ⊆ Ioc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioo_eq_Ioo (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ioo lemma Ico_subset_Icc_union_Ioo : Ico a c ⊆ Icc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioo_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩)) Ico_subset_Icc_union_Ioo lemma Icc_subset_Icc_union_Ioc : Icc a c ⊆ Icc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩)) Icc_subset_Icc_union_Ioc lemma Ioc_subset_Ioc_union_Ioc : Ioc a c ⊆ Ioc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioc_eq_Ioc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Ioc /-! #### Two finite intervals with a common point -/ lemma Ioo_subset_Ioc_union_Ico : Ioo a c ⊆ Ioc a b ∪ Ico b c := subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Ioc_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ico lemma Ico_subset_Icc_union_Ico : Ico a c ⊆ Icc a b ∪ Ico b c := subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Icc_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Ico_subset_Icc_union_Ico lemma Icc_subset_Icc_union_Icc : Icc a c ⊆ Icc a b ∪ Icc b c := subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Icc_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Icc_subset_Icc_union_Icc lemma Ioc_subset_Ioc_union_Icc : Ioc a c ⊆ Ioc a b ∪ Icc b c := subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Ioc_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Icc end linear_order section lattice section inf variables {α : Type u} [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Iio_inter_Iio [is_total α (≤)] {a b : α} : Iio a ∩ Iio b = Iio (a ⊓ b) := by { ext x, simp [Iio] } end inf section sup variables {α : Type u} [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ioi_inter_Ioi [is_total α (≤)] {a b : α} : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := by { ext x, simp [Ioi] } end sup section both variables {α : Type u} [lattice α] [ht : is_total α (≤)] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self] include ht lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl end both end lattice section decidable_linear_order variables {α : Type u} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} @[simp] lemma Ico_diff_Iio : Ico a b \ Iio c = Ico (max a c) b := ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio : Ico a b ∩ Iio c = Ico a (min b c) := ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} lemma Ioc_union_Ioc (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { ext x, simp [iff_def, and_imp, or_imp_distrib, (h₂.lt_or_le x).symm, h₁.lt_or_le] { contextual := tt } }, all_goals { simp [*] } end @[simp] lemma Ioc_union_Ioc_right : Ioc a b ∪ Ioc a c = Ioc a (max b c) := by rw [Ioc_union_Ioc, min_self]; exact (min_le_left _ _).trans (le_max_left _ _) @[simp] lemma Ioc_union_Ioc_left : Ioc a c ∪ Ioc b c = Ioc (min a b) c := by rw [Ioc_union_Ioc, max_self]; exact (min_le_right _ _).trans (le_max_right _ _) @[simp] lemma Ioc_union_Ioc_symm : Ioc a b ∪ Ioc b a = Ioc (min a b) (max a b) := by { rw max_comm, apply Ioc_union_Ioc; rw max_comm; exact min_le_max } @[simp] lemma Ioc_union_Ioc_union_Ioc_cycle : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc (min a (min b c)) (max a (max b c)) := begin rw [Ioc_union_Ioc, Ioc_union_Ioc], ac_refl, all_goals { solve_by_elim [min_le_left_of_le, min_le_right_of_le, le_max_left_of_le, le_max_right_of_le, le_refl] { max_depth := 5 }} end end decidable_linear_order section decidable_linear_ordered_add_comm_group variables {α : Type u} [decidable_linear_ordered_add_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp* }, { use max x (x + dy), simp [*, le_refl] } end end decidable_linear_ordered_add_comm_group end set
feaadf491b39e585ce4216d577d524244e78f942
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/real/cau_seq.lean
2d0f93b184312b79d7ebb493ae390cab66d9ee78
[ "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
24,838
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.big_operators algebra.ordered_field /-! # Cauchy sequences A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology. This is a concrete implementation that is useful for simplicity and computability reasons. ## Important definitions * `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val * `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy. ## Tags sequence, cauchy, abs val, absolute value -/ /-- A function f is an absolute value if it is nonnegative, zero only at 0, additive, and multiplicative. -/ class is_absolute_value {α} [discrete_linear_ordered_field α] {β} [ring β] (f : β → α) : Prop := (abv_nonneg [] : ∀ x, 0 ≤ f x) (abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0) (abv_add [] : ∀ x y, f (x + y) ≤ f x + f y) (abv_mul [] : ∀ x y, f (x * y) = f x * f y) namespace is_absolute_value variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl theorem abv_one' (h : (1:β) ≠ 0) : abv 1 = 1 := (domain.mul_left_inj $ mt (abv_eq_zero abv).1 h).1 $ by rw [← abv_mul abv, mul_one, mul_one] theorem abv_one {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] : abv 1 = 1 := abv_one' abv one_ne_zero theorem abv_pos {a : β} : 0 < abv a ↔ a ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv] theorem abv_neg (a : β) : abv (-a) = abv a := by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _), ← abv_mul abv, ← abv_mul abv]; simp theorem abv_sub (a b : β) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv_neg abv] theorem abv_inv {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a : β) : abv a⁻¹ = (abv a)⁻¹ := classical.by_cases (λ h : a = 0, by simp [h, abv_zero abv]) (λ h, (domain.mul_left_inj (mt (abv_eq_zero abv).1 h)).1 $ by rw [← abv_mul abv]; simp [h, mt (abv_eq_zero abv).1 h, abv_one abv]) theorem abv_div {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a b : β) : abv (a / b) = abv a / abv b := by rw [division_def, abv_mul abv, abv_inv abv]; refl lemma abv_sub_le (a b c : β) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg] using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : β) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b lemma abs_abv_sub_le_abv_sub (a b : β) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _, by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩ lemma abv_pow {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] (a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n := by induction n; simp [abv_mul abv, _root_.pow_succ, abv_one abv, *] end is_absolute_value instance abs_is_absolute_value {α} [discrete_linear_ordered_field α] : is_absolute_value (abs : α → α) := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} : (∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) → ∃ i, ∀ j ≥ i, P j ∧ Q j | ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩ section variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem rat_add_continuous_lemma {ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε := ⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂, by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩ theorem rat_mul_continuous_lemma {ε K₁ K₂ : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ → abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε := begin have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _), have εK := div_pos (half_pos ε0) K0, refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)), replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK) (mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) this end theorem rat_inv_continuous_lemma {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] {ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) : ∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b → abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε := begin have KK := mul_pos K0 K0, have εK := mul_pos ε0 KK, refine ⟨_, εK, λ a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel ε (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos ε0 KK) KK end end /-- A sequence is Cauchy if the distance between its entries tends to zero. -/ def is_cau_seq {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) (f : ℕ → β) := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε namespace is_cau_seq variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} theorem cauchy₂ (hf : is_cau_seq abv f) {ε:α} (ε0 : ε > 0) : ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := begin refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _), rw ← add_halves ε, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end theorem cauchy₃ (hf : is_cau_seq abv f) {ε:α} (ε0 : ε > 0) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩ end is_cau_seq def cau_seq {α : Type*} [discrete_linear_ordered_field α] (β : Type*) [ring β] (abv : β → α) := {f : ℕ → β // is_cau_seq abv f} namespace cau_seq variables {α : Type*} [discrete_linear_ordered_field α] section ring variables {β : Type*} [ring β] {abv : β → α} instance : has_coe_to_fun (cau_seq β abv) := ⟨_, subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq β abv) _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2 theorem cauchy (f : cau_seq β abv) : ∀ {ε}, ε > 0 → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2 def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv := ⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ variable [is_absolute_value abv] theorem cauchy₂ (f : cau_seq β abv) {ε:α} : ε > 0 → ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂ theorem cauchy₃ (f : cau_seq β abv) {ε:α} : ε > 0 → ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃ theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := (finset.range (i+1)).sum (λ j, abv (f j)), have : ∀ j ≤ i, abv (f j) ≤ R, { intros j ij, change (λ j, abv (f j)) j ≤ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, λ j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ instance : has_add (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl variable (abv) /-- The constant Cauchy sequence. -/ def const (x : β) : cau_seq β abv := ⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y := ⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩ instance : has_zero (cau_seq β abv) := ⟨const 0⟩ instance : has_one (cau_seq β abv) := ⟨const 1⟩ instance : inhabited (cau_seq β abv) := ⟨0⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl theorem const_add (x y : β) : const (x + y) = const x + const y := ext $ λ i, rfl instance : has_mul (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl theorem const_mul (x y : β) : const (x * y) = const x * const y := ext $ λ i, rfl instance : has_neg (cau_seq β abv) := ⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : β) : const (-x) = -const x := ext $ λ i, rfl instance : ring (cau_seq β abv) := by refine {neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, ..}; { intros, apply ext, simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm] } instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] : comm_ring (cau_seq β abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } theorem const_sub (x y : β) : const (x - y) = const x - const y := by rw [sub_eq_add_neg, const_add, const_neg, sub_eq_add_neg] @[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl /-- `lim_zero f` holds when `f` approaches 0. -/ def lim_zero (f : cau_seq β abv) := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε theorem add_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | ε ε0 := (exists_forall_ge_and (hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $ λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂) theorem mul_lim_zero_right (f : cau_seq β abv) {g} (hg : lim_zero g) : lim_zero (f * g) | ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos ε0 F0).imp $ λ i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem mul_lim_zero_left {f} (g : cau_seq β abv) (hg : lim_zero f) : lim_zero (f * g) | ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in (hg _ $ div_pos ε0 G0).imp $ λ i H j ij, by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _); rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero_right _ hf theorem sub_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := add_lim_zero hf (neg_lim_zero hg) theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) := by simpa using neg_lim_zero hfg theorem zero_lim_zero : lim_zero (0 : cau_seq β abv) | ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩ theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _), λ e, e.symm ▸ zero_lim_zero⟩ instance equiv : setoid (cau_seq β abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], λ f g h, by simpa using neg_lim_zero h, λ f g h fg gh, by simpa [sub_eq_add_neg] using add_lim_zero fg gh⟩⟩ theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε:α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε := (exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $ λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, λ l, by simpa using add_lim_zero h l⟩ theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (λ ε ε0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos ε0) with i hi, rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩, refine ⟨j, λ k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : ℕ → β) (g : cau_seq β abv) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f | ε ε0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in ⟨i, λ j ij, begin cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f := assume : lim_zero f, have lim_zero (f - 0), by simpa, hf this lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 := have lim_zero (f - 0), from hf, have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa, show lim_zero (g*f - 0), by simpa lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 := assume : lim_zero (f*g - 0), have hlz : lim_zero (f*g), by simpa, have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf), have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg), begin rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩, rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩, have : a1 * a2 > 0, from mul_pos ha1 ha2, cases hlz _ this with N hN, let i := max N (max N1 N2), have hN' := hN i (le_max_left _ _), have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)), have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)), apply not_le_of_lt hN', change _ ≤ abv (_ * _), rw is_absolute_value.abv_mul abv, apply mul_le_mul; try { assumption }, { apply le_of_lt ha2 }, { apply is_absolute_value.abv_nonneg abv } end theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] end ring section comm_ring variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 := by rw mul_comm; apply mul_equiv_zero _ hf end comm_ring section integral_domain variables {β : Type*} [integral_domain β] (abv : β → α) [is_absolute_value abv] lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) := assume h, have ∀ ε > 0, ∃ i, ∀ k, k ≥ i → abv (1 - 0) < ε, from h, have h1 : abv 1 ≤ 0, from le_of_not_gt $ assume h2 : abv 1 > 0, exists.elim (this _ h2) $ λ i hi, lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _), have h2 : abv 1 ≥ 0, from is_absolute_value.abv_nonneg _ _, have abv 1 = 0, from le_antisymm h1 h2, have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this, absurd this one_ne_zero end integral_domain section field variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩ def inv (f) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 := λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, λ j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using ε0⟩ theorem const_inv {x : β} (hx : x ≠ 0) : const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := ext (assume n, by simp[inv_apply, const_apply]) end field section abs local notation `const` := const abs /-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/ def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, h₂⟩ := h _ (le_refl _) in not_lt_of_le h₁ (abs_lt.1 h₂).2 theorem const_pos {x : α} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)), λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩ theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩ theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, λ j ij, begin cases h j ij with h₁ h₂, have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (λ h, ⟨K, K0, i, λ j ij, _⟩); have := (hi _ ij).1; cases hi _ (le_refl _) with h₁ h₂, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ h₂ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ } end instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq α abs} (fg : f < g) (gh : g ≈ h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq α abs} (fg : f ≈ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) lemma le_of_eq_of_le {f g h : cau_seq α abs} (hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h := hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg) (or.inr ∘ setoid.trans hfg) lemma le_of_le_of_eq {f g h : cau_seq α abs} (hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h := hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh)) (λ h, or.inr (setoid.trans h hgh)) instance : preorder (cau_seq α abs) := { lt := (<), le := λ f g, f < g ∨ f ≈ g, le_refl := λ f, or.inr (setoid.refl _), le_trans := λ f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := λ f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_right (mt (λ h, or.inr (setoid.symm h)) h₂)⟩ } theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f := (trichotomy (g - f)).imp_right (λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : α} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv lemma le_of_exists {f g : cau_seq α abs} (h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g := let ⟨i, hi⟩ := h in (or.assoc.2 (cau_seq.lt_total f g)).elim id (λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in not_lt_of_ge (hi (max i j) (le_max_left _ _)) (sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _)))))) theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, λ i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ end abs end cau_seq
1b0f56eab9950a3b9fb0188ea2a5ddec0b278949
05b503addd423dd68145d68b8cde5cd595d74365
/src/data/list/basic.lean
83c993608cf619ac20f79a77e531c09feb3b34d6
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
222,222
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import tactic.interactive tactic.mk_iff_of_inductive_prop logic.basic logic.function logic.relator algebra.group order.basic data.list.defs data.nat.basic data.option.basic data.bool data.prod data.fin /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /- mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] /- length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ lemma injective_length_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end lemma injective_length [subsingleton α] : injective (length : list α → ℕ) := injective_length_iff.mpr $ by apply_instance /- set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq [decidable_eq α] (x : α) : ({x} : list α) = [x] := by refl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [y, x] := by { rw [insert_neg, singleton_eq], show y ∉ [x], rw [mem_singleton], exact h.symm } /- bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [mem_cons_iff, forall_mem_cons'] theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /- list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /- append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_left h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_right' h rfl theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /- join -/ attribute [simp] join theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /- repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] /- pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /- bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ /- concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by simp theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by simp /- reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl theorem reverse_injective : injective (@reverse α) := injective_of_left_inverse reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /- last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, refl} /- sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact append_sublist_append_of_sublist_right ih [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp only [reverse_reverse] at this; assumption, reverse_sublist⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp only [reverse_append, append_sublist_append_left, reverse_sublist_iff] at this; assumption, λ h, append_sublist_append_of_sublist_right h l⟩ theorem append_sublist_append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (append_sublist_append_of_sublist_right hl _).trans ((append_sublist_append_left _).2 hr) theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (subset_of_sublist s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ subset_of_sublist s theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /- index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp, priority 990] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp, priority 980] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /- nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < n) : (list.repeat a n).nth_le m (by rwa list.length_repeat) = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length: ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[ext] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], } @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /- map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem injective_map_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /- map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /- take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_length (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /- foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp /- scanl -/ lemma length_scanl {β : Type*} {f : α → β → α} : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /- mfoldl, mfoldr -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl variables [is_lawful_monad m] @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /- prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[to_additive] theorem prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α → β) [is_monoid_hom f] : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, (is_monoid_hom.map_one f).symm], exact l.foldl_hom _ _ _ 1 (is_monoid_hom.map_mul f) } end monoid @[simp, to_additive] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end /- lexicographic ordering -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {} {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /- all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /- map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap /- find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /- lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /- filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem map_sublist_map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s /- filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := subset_of_sublist $ filter_sublist l theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /- count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /- prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_left_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_left_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /- sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s, { simp only [sublists'_nil, mem_singleton], exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, simp only [sublists'_cons, mem_append, IH, mem_map], split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ h }, { exact cons_sublist_cons _ h }, { cases h with _ _ _ h s _ _ h, { exact or.inl h }, { exact or.inr ⟨s, h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, pow_succ, mul_succ, mul_zero, zero_add] @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc] theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih, {refl}, simp only [ih, foldr_cons] end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil] | (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := rfl | (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l] theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind], congr, funext x, apply congr_arg _, rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map, map_eq_map, map_id' (append_nil), append_nil] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l with hd tl ih; [refl, simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro, {rwa foldr}, simp only [foldr, mem_cons_iff, false_or, not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp only [map, map_append, sublists_concat]; exact ((append_sublist_append_left _).2 $ singleton_sublist.2 $ mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans ((append_sublist_append_right _).2 IH) /- sublists_len -/ def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β | 0 l f r := f [] :: r | (n+1) [] f r := r | (n+1) (a::l) f r := sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ list.cons a) r) def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) := sublists_len_aux n l id [] lemma sublists_len_aux_append {α β γ : Type*} : ∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ), sublists_len_aux n l (g ∘ f) (r.map g ++ s) = (sublists_len_aux n l f r).map g ++ s | 0 l f g r s := rfl | (n+1) [] f g r s := rfl | (n+1) (a::l) f g r s := begin unfold sublists_len_aux, rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl, sublists_len_aux_append, sublists_len_aux_append] end lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) : sublists_len_aux n l f r = (sublists_len n l).map f ++ r := by rw [sublists_len, ← sublists_len_aux_append]; refl lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) : sublists_len_aux 0 l f r = f [] :: r := by cases l; refl @[simp] lemma sublists_len_zero {α : Type*} (l : list α) : sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _ @[simp] lemma sublists_len_succ_nil {α : Type*} (n) : sublists_len (n+1) (@nil α) = [] := rfl @[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) : sublists_len (n + 1) (a::l) = sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) := by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id, append_nil]; refl @[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α), length (sublists_len n l) = nat.choose (length l) n | 0 l := by simp | (n+1) [] := by simp | (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α), sublists_len n l <+ sublists' l | 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _)) | (n+1) [] := nil_sublist _ | (n+1) (a::l) := begin rw [sublists_len_succ_cons, sublists'_cons], exact append_sublist_append (sublists_len_sublist_sublists' _ _) (map_sublist_map _ (sublists_len_sublist_sublists' _ _)) end lemma sublists_len_sublist_of_sublist {α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl}, { refine IH.trans _, rw sublists_len_succ_cons, apply sublist_append_left }, { simp [sublists_len_succ_cons], exact append_sublist_append IH (map_sublist_map _ (IHn s)) } end lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α}, l' ∈ sublists_len n l → length l' = n | 0 l l' (or.inl rfl) := rfl | (n+1) (a::l) l' h := begin rw [sublists_len_succ_cons, mem_append, mem_map] at h, rcases h with h | ⟨l', h, rfl⟩, { exact length_of_sublists_len h }, { exact congr_arg (+1) (length_of_sublists_len h) }, end lemma mem_sublists_len_self {α : Type*} {l l' : list α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH, { exact or.inl rfl }, { cases l₁ with b l₁, { exact or.inl rfl }, { rw [length, sublists_len_succ_cons], exact mem_append_left _ IH } }, { rw [length, sublists_len_succ_cons], exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) } end @[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := ⟨λ h, ⟨mem_sublists'.1 (subset_of_sublist (sublists_len_sublist_sublists' _ _) h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩ /- forall₂ -/ section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff @[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} : forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := ⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩ theorem forall₂.imp {R S : α → β → Prop} (H : ∀ a b, R a b → S a b) {l₁ l₂} (h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ := by induction h; constructor; solve_by_elim lemma forall₂.mp {r q s : α → β → Prop} (h : ∀a b, r a b → q a b → s a b) : ∀{l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂ | [] [] forall₂.nil forall₂.nil := forall₂.nil | (a::l₁) (b::l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) := forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs) lemma forall₂.flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l | [] _ := forall₂.nil | (a::as) h := forall₂.cons (h _ (mem_cons_self _ _)) (forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha) lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l := forall₂_same $ assume a h, is_refl.refl _ _ lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) := begin funext a b, apply propext, split, { assume h, induction h, {refl}, simp only [*]; split; refl }, { assume h, subst h, exact forall₂_refl _ } end @[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ @[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_cons_right_iff {b l u} : forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} : ∀l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀a∈l, p a) ∧ forall₂ r l u | [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and] | (a::l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons, and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm] @[simp] lemma forall₂_map_left_iff {f : γ → α} : ∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u | [] _ := by simp only [map, forall₂_nil_left_iff] | (a::l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff] @[simp] lemma forall₂_map_right_iff {f : γ → β} : ∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u | _ [] := by simp only [map, forall₂_nil_right_iff] | _ (b::u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff] lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r) | a₀ nil a₁ forall₂.nil forall₂.nil := rfl | (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r) | nil a₀ a₁ forall₂.nil forall₂.nil := rfl | (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) := ⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩ theorem forall₂_length_eq {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂ | _ _ forall₂.nil := rfl | _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂) theorem forall₂_zip {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b | _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁ | _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃ theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b := ⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩, λ h, begin cases h with h₁ h₂, induction l₁ with a l₁ IH generalizing l₂, { cases length_eq_zero.1 h₁.symm, constructor }, { cases l₂ with b l₂; injection h₁ with h₁, exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) } end⟩ theorem forall₂_take {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂) | 0 _ _ _ := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n] theorem forall₂_drop {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂) | 0 _ _ h := by simp only [drop, h] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n] theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ := have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h, by rwa [take_left] at h' theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ := have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h, by rwa [drop_left] at h' lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp only [not_mem_nil] | a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂) lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map | f g h [] [] forall₂.nil := forall₂.nil | f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂) lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append | [] [] h l₁ l₂ hl := hl | (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl) lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join | [] [] forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂) lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind := assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁) lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs) lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : (r ⇒ (↔)) p q) : (forall₂ r ⇒ forall₂ r) (filter p) (filter q) | _ _ forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := begin by_cases p a, { have : q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], }, end theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { rw filter_map_cons_none _ _ eq }, { rw filter_map_cons_some _ _ _ eq }, end lemma rel_filter_map : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := rel_foldl hf h end forall₂ /- sections -/ theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L := begin refine ⟨λ h, _, λ h, _⟩, { induction L generalizing f, {cases mem_singleton.1 h, exact forall₂.nil}, simp only [sections, bind_eq_bind, mem_bind, mem_map] at h, rcases h with ⟨_, _, _, _, rfl⟩, simp only [*, forall₂_cons, true_and] }, { induction h with a l f L al fL fs, {exact or.inl rfl}, simp only [sections, bind_eq_bind, mem_bind, mem_map], exact ⟨_, fs, _, al, rfl, rfl⟩ } end theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L := forall₂_length_eq (mem_sections.1 h) lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections | _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil | _ _ (forall₂.cons h₀ h₁) := rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀) /- permutations -/ section permutations @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl end permutations /- insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /- erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := subset_of_sublist (erasep_sublist l) theorem erasep_sublist_erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /- erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp, priority 980] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := subset_of_sublist (erase_sublist a l) theorem erase_sublist_erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact erasep_sublist_erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /- diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := subset_of_sublist $ diff_sublist _ _ theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem diff_sublist_of_sublist : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, diff_sublist_of_sublist (erase_sublist_erase _ h)] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (erase_sublist_erase b h) end diff /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := (zip_nil_right _).symm | l₁ [] := by rw zip_nil_right; refl | (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := rfl | l₁ [] := by simp only [length, zip_nil_right, min_zero] | (a::l₁) (b::l₂) := by by simp only [length, zip_cons_cons, length_zip l₁ l₂, min_add_add_right] theorem zip_append : ∀ {l₁ l₂ r₁ r₂ : list α} (h : length l₁ = length l₂), zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ | [] l₂ r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl | l₁ [] r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl | (a::l₁) (b::l₂) r₁ r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ_inj h)]; split; refl theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g) | [] l₂ := rfl | l₁ [] := by simp only [map, zip_nil_right] | (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) : zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) := by rw [← zip_map, map_id] theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) : zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) := by rw [← zip_map, map_id] theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α), zip (l.map f) (l.map g) = l.map (λ a, (f a, g a)) | [] := rfl | (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ | (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩ | (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h] @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd) | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp only [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp only [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁ | [] l₂ h := rfl | l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl | (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) : (unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)] @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := unzip_zip (length_reverse l).symm @[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l := by rw [← unzip_left, unzip_revzip] @[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse := by rw [← unzip_right, unzip_revzip] theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip] theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse := by simp [revzip] /- enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : ∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end /- product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /- sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /- of_fn -/ theorem length_of_fn_aux {n} (f : fin n → α) : ∀ m h l, length (of_fn_aux f m h l) = length l + m | 0 h l := rfl | (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _) @[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) theorem nth_of_fn_aux {n} (f : fin n → α) (i) : ∀ m h l, (∀ i, nth l i = of_fn_nth_val f (i + m)) → nth (of_fn_aux f m h l) i = of_fn_nth_val f i | 0 h l H := H i | (succ m) h l H := nth_of_fn_aux m _ _ begin intro j, cases j with j, { simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] }, { simp only [nth, H, succ_add] } end @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = of_fn_nth_val f i := nth_of_fn_aux f _ _ _ _ $ λ i, by simp only [of_fn_nth_val, dif_neg (not_lt.2 (le_add_left n i))]; refl @[simp] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) : nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i := option.some.inj $ by rw [← nth_le_nth]; simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.2] theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read := suffices ∀ {m h l}, d_array.rev_iterate_aux a (λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, simp only [d_array.rev_iterate_aux, of_fn_aux, IH] end theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl theorem of_fn_succ {n} (f : fin (succ n) → α) : of_fn f = f 0 :: of_fn (λ i, f i.succ) := suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l = f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, rw [of_fn_aux, IH], refl end theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l | [] := rfl | (a::l) := by rw of_fn_succ; congr; simp only [fin.succ_val]; exact of_fn_nth_le l /- disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] := by rw disjoint_comm; exact disjoint_nil_left _ @[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /- union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /- inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter /- bag_inter -/ section bag_inter variable [decidable_eq α] @[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] := by cases l; refl @[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] := by cases l; refl @[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) : (a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) := by cases l₂; exact if_pos h @[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) : (a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ := begin cases l₂, {simp only [bag_inter_nil]}, simp only [erase_of_not_mem h, list.bag_inter, if_neg h] end @[simp] theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ | [] l₂ := by simp only [nil_bag_inter, not_mem_nil, false_and] | (b::l₁) l₂ := begin by_cases b ∈ l₂, { rw [cons_bag_inter_of_pos _ h, mem_cons_iff, mem_cons_iff, mem_bag_inter], by_cases ba : a = b, { simp only [ba, h, eq_self_iff_true, true_or, true_and] }, { simp only [mem_erase_of_ne ba, ba, false_or] } }, { rw [cons_bag_inter_of_neg _ h, mem_bag_inter, mem_cons_iff, or_and_distrib_right], symmetry, apply or_iff_right_of_imp, rintro ⟨rfl, h'⟩, exact h.elim h' } end @[simp] theorem count_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, count a (l₁.bag_inter l₂) = min (count a l₁) (count a l₂) | [] l₂ := by simp | l₁ [] := by simp | (h₁ :: l₁) (h₂ :: l₂) := begin simp only [list.bag_inter, list.mem_cons_iff], by_cases p₁ : h₂ = h₁; by_cases p₂ : h₁ = a, { simp only [p₁, p₂, count_bag_inter, min_succ_succ, erase_cons_head, if_true, mem_cons_iff, count_cons_self, true_or, eq_self_iff_true] }, { simp only [p₁, ne.symm p₂, count_bag_inter, count_cons, erase_cons_head, if_true, mem_cons_iff, true_or, eq_self_iff_true, if_false] }, { rw p₂ at p₁, by_cases p₃ : a ∈ l₂, { simp only [p₁, ne.symm p₁, p₂, p₃, erase_cons, count_bag_inter, eq.symm (min_succ_succ _ _), succ_pred_eq_of_pos (count_pos.2 p₃), if_true, mem_cons_iff, false_or, count_cons_self, eq_self_iff_true, if_false, ne.def, not_false_iff, count_erase_self, list.count_cons_of_ne] }, { simp [ne.symm p₁, p₂, p₃] } }, { by_cases p₄ : h₁ ∈ l₂; simp only [ne.symm p₁, ne.symm p₂, p₄, count_bag_inter, if_true, if_false, mem_cons_iff, false_or, eq_self_iff_true, ne.def, not_false_iff,count_erase_of_ne, count_cons_of_ne] } end theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁ | [] l₂ := by simp [nil_sublist] | (b::l₁) l₂ := begin by_cases b ∈ l₂; simp [h], { apply cons_sublist_cons, apply bag_inter_sublist_left }, { apply sublist_cons_of_sublist, apply bag_inter_sublist_left } end theorem bag_inter_nil_iff_inter_nil : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ = [] ↔ l₁ ∩ l₂ = [] | [] l₂ := by simp | (b::l₁) l₂ := begin by_cases h : b ∈ l₂; simp [h], exact bag_inter_nil_iff_inter_nil l₁ l₂ end end bag_inter /- pairwise relation (generalized no duplicate) -/ section pairwise run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pairwise_iff variable {R : α → α → Prop} theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp only [pairwise.nil, pairwise_cons] at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; [exact pairwise.nil, simp only [*, pairwise_cons, forall_2_true_iff, and_true]] theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i) theorem forall_of_forall_of_pairwise (H : symmetric R) {l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) : ∀ (x ∈ l) (y ∈ l), R x y := begin induction l with a l IH, { exact forall_mem_nil _ }, cases forall_mem_cons.1 H₁ with H₁₁ H₁₂, cases pairwise_cons.1 H₂ with H₂₁ H₂₂, rintro x (rfl | hx) y (rfl | hy), exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy] end lemma forall_of_pairwise (H : symmetric R) {l : list α} (hl : pairwise R l) : (∀a∈l, ∀b∈l, a ≠ b → R a b) := forall_of_forall_of_pairwise (λ a b h hne, H (h hne.symm)) (λ _ _ h, (h rfl).elim) (pairwise.imp (λ _ _ h _, h) hl) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append], simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]] theorem pairwise_append_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_append_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp only [map, pairwise.nil] | (b::l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'], by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map] theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp only [option.mem_def], induction l with a l IH, { simp only [filter_map, pairwise.nil] }, cases e : f a with b, { rw [filter_map_cons_none _ _ e, IH, pairwise_cons], simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] }, rw [filter_map_cons_some _ _ _ e], simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'], end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons], simp only [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH, pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h] theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (not_lt_zero j).elim h | (a::l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (not_lt_zero _).elim h₂}, cases i with i, { exact H.1 _ (nth_le_mem l _ _) }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ pairwise.nil := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this /- pairwise reduct -/ variable [decidable_rel R] @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_map (f : β → α) : Π (l : list β), pw_filter R (map f l) = map f (pw_filter (λ x y, R (f x) (f y)) l) | [] := rfl | (x :: xs) := if h : ∀ b ∈ pw_filter R (map f xs), R (f x) b then have h' : ∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ b hb, h _ (by rw [pw_filter_map]; apply mem_map_of_mem _ hb), by rw [map,pw_filter_cons_of_pos h,pw_filter_cons_of_pos h',pw_filter_map,map] else have h' : ¬∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ hh, h $ λ a ha, by { rw [pw_filter_map,mem_map] at ha, rcases ha with ⟨b,hb₀,hb₁⟩, subst a, exact hh _ hb₀, }, by rw [map,pw_filter_cons_of_neg h,pw_filter_cons_of_neg h',pw_filter_map] theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := subset_of_sublist (pw_filter_sublist _) theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {refl}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH, { exact λ _ _, false.elim }, simp only [forall_mem_cons], by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end pairwise /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ section chain run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff variable {R : α → α → Prop} theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp' {S : α → α → Prop} (HRS : ∀ ⦃a b⦄, R a b → S a b) {a b : α} (Hab : ∀ ⦃c⦄, R a c → S b c) {l : list α} (p : chain R a l) : chain S b l := by induction p with _ a c l r p IH generalizing b; constructor; [exact Hab r, exact IH (@HRS _)] theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := p.imp' H (H a) theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp only [chain_cons, chain.nil, and_true] theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp only [map, chain.nil, chain_cons, *] theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, IH r'⟩ end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {exact pairwise_singleton _ _}, apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x::l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ @[simp] theorem chain'_nil : chain' R [] := trivial @[simp] theorem chain'_singleton (a : α) : chain' R [a] := chain.nil theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔ chain' R (l₁++[a]) ∧ chain' R (a::l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b::l₁) l₂ := chain_split theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R l := ((chain'_map f).1 p).imp H theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem pairwise.chain' : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a::l) h := chain_of_pairwise h theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a::l) := chain_iff_pairwise tr @[simp] theorem chain'_cons {x y l} : chain' R (x :: y :: l) ↔ R x y ∧ chain' R (y :: l) := chain_cons theorem chain'.cons {x y l} (h₁ : R x y) (h₂ : chain' R (y :: l)) : chain' R (x :: y :: l) := chain'_cons.2 ⟨h₁, h₂⟩ theorem chain'.tail : ∀ {l} (h : chain' R l), chain' R l.tail | [] _ := trivial | [x] _ := trivial | (x :: y :: l) h := (chain'_cons.mp h).right theorem chain'_pair {x y} : chain' R [x, y] ↔ R x y := by simp only [chain'_singleton, chain'_cons, and_true] theorem chain'_reverse : ∀ {l}, chain' R (reverse l) ↔ chain' (flip R) l | [] := iff.rfl | [a] := by simp only [chain'_singleton, reverse_singleton] | (a :: b :: l) := by rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append, nil_append, chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip] end chain /- no duplicates predicate -/ section nodup @[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_nil : @nodup α [] := pairwise.nil @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp only [nodup, pairwise_cons, forall_mem_ne] lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp only [nodup_nil] | _ _ (forall₂.cons hab h) := by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin induction l with a l IH; intro h, {exact nodup_nil}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1 | 0 := by simp [nat.zero_le] | 1 := by simp | (n+2) := iff_of_false (λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (le_add_left 2 n))) (not_le_of_lt $ le_add_left 2 n) @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp only [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_append_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp only [nodup_append, and.left_comm, disjoint_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) := nodup_map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup_of_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm] theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH, {refl}, by_cases b = a, { subst h, rw [erase_cons_head, filter_cons_of_neg], symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl }, { rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h } end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem nodup_diff [decidable_eq α] : ∀ {l₁ l₂ : list α} (h : l₁.nodup), (l₁.diff l₂).nodup | l₁ [] h := h | l₁ (a::l₂) h := by rw diff_cons; exact nodup_diff (nodup_erase_of_nodup _ h) 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 only [mem_filter, and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, forall_eq'] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂, d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := if h' : a ∈ l then by rw [insert_of_mem h']; exact h else by rw [insert_of_not_mem h', nodup_cons]; split; assumption theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] lemma nodup_sublists_len {α : Type*} (n) {l : list α} (nd : nodup l) : (sublists_len n l).nodup := nodup_of_sublist (sublists_len_sublist_sublists' _ _) (nodup_sublists'.2 nd) lemma diff_eq_filter_of_nodup [decidable_eq α] : ∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂) | l₁ [] hl₁ := by simp | l₁ (a::l₂) hl₁ := begin rw [diff_cons, diff_eq_filter_of_nodup (nodup_erase_of_nodup _ hl₁), nodup_erase_eq_filter _ hl₁, filter_filter], simp only [mem_cons_iff, not_or_distrib, and.comm], congr end lemma mem_diff_iff_of_nodup [decidable_eq α] {l₁ l₂ : list α} (hl₁ : l₁.nodup) {a : α} : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by rw [diff_eq_filter_of_nodup hl₁, mem_filter] lemma nodup_update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l), (l.update_nth n a).nodup | [] n a hl ha := nodup_nil | (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩ | (b::l) (n+1) a hl ha := nodup_cons.2 ⟨λ h, (mem_or_eq_of_mem_update_nth h).elim (nodup_cons.1 hl).1 (λ hba, ha (hba ▸ mem_cons_self _ _)), nodup_update_nth (nodup_cons.1 hl).2 (mt (mem_cons_of_mem _) ha)⟩ end nodup /- erase duplicates function -/ section erase_dup variable [decidable_eq α] @[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) : erase_dup (a::l) = erase_dup l := pw_filter_cons_of_neg $ by simpa only [forall_mem_ne] using h theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) : erase_dup (a::l) = a :: erase_dup l := pw_filter_cons_of_pos $ by simpa only [forall_mem_ne] using h @[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l := by simpa only [erase_dup, forall_mem_ne, not_not] using not_congr (@forall_mem_pw_filter α (≠) _ (λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l) @[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) : erase_dup (a::l) = erase_dup l := erase_dup_cons_of_mem' $ mem_erase_dup.2 h @[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) : erase_dup (a::l) = a :: erase_dup l := erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l := λ a, mem_erase_dup.2 theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self @[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l := pw_filter_idempotent theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ := begin induction l₁ with a l₁ IH, {refl}, rw [cons_union, ← IH], show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)), by_cases a ∈ erase_dup (l₁ ++ l₂); [ rw [erase_dup_cons_of_mem' h, insert_of_mem h], rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]] end end erase_dup /- iota and range(') -/ @[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n | s 0 := rfl | s (n+1) := congr_arg succ (length_range' _ _) @[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n | s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1 | s (succ n) := have m = s → m < s + n + 1, from λ e, e ▸ lt_succ_of_le (le_add_right _ _), have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m, by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm, (mem_cons_iff _ _ _).trans $ by simp only [mem_range', or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n | s 0 := rfl | s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n) theorem map_sub_range' (a) : ∀ (s n : ℕ) (h : a ≤ s), map (λ x, x - a) (range' s n) = range' (s - a) n | s 0 _ := rfl | s (n+1) h := begin convert congr_arg (cons (s-a)) (map_sub_range' (s+1) n (nat.le_succ_of_le h)), rw nat.succ_sub h, refl, end theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) @[simp] theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa only [length_range'] using length_le_of_sublist h, λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩ theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n := ⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $ (mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2, λ h, subset_of_sublist (range'_sublist_right.2 h)⟩ theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m) | s 0 (n+1) _ := rfl | s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] := by rw add_comm n 1; exact (range'_append s n 1).symm theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s) | 0 n := rfl | (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1) theorem range_eq_range' (n : ℕ) : range n = range' 0 n := (range_core_range' n 0).trans $ by rw zero_add theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) := by rw [range_eq_range', range_eq_range', range', add_comm, ← map_add_range']; congr; exact funext one_add theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) := by rw [range_eq_range', map_add_range']; refl @[simp] theorem length_range (n : ℕ) : length (range n) = n := by simp only [range_eq_range', length_range'] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp only [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp only [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp only [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp only [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add] @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := mt mem_range.1 $ lt_irrefl _ theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m := by simp only [range_eq_range', nth_range' _ h, zero_add] theorem range_concat (n : ℕ) : range (succ n) = range n ++ [n] := by simp only [range_eq_range', range'_concat, zero_add] theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp only [iota_eq_reverse_range', length_reverse, length_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff] theorem reverse_range' : ∀ s n : ℕ, reverse (range' s n) = map (λ i, s + n - 1 - i) (range n) | s 0 := rfl | s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map]; simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘), λ a i, show a - 1 - i = a - succ i, from pred_sub _ _, reverse_singleton, map_cons, nat.sub_zero, cons_append, nil_append, eq_self_iff_true, true_and, map_map] using reverse_range' s n /-- All elements of `fin n`, from `0` to `n-1`. -/ def fin_range (n : ℕ) : list (fin n) := (range n).pmap fin.mk (λ _, list.mem_range.1) @[simp] lemma mem_fin_range {n : ℕ} (a : fin n) : a ∈ fin_range n := mem_pmap.2 ⟨a.1, mem_range.2 a.2, fin.eta _ _⟩ lemma nodup_fin_range (n : ℕ) : (fin_range n).nodup := nodup_pmap (λ _ _ _ _, fin.veq_of_eq) (nodup_range _) @[simp] lemma length_fin_range (n : ℕ) : (fin_range n).length = n := by rw [fin_range, length_pmap, length_range] @[to_additive] theorem prod_range_succ {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) : ((range n.succ).map f).prod = ((range n).map f).prod * f n := by rw [range_concat, map_append, map_singleton, prod_append, prod_cons, prod_nil, mul_one] /-- `Ico n m` is the list of natural numbers `n ≤ x < m`. (Ico stands for "interval, closed-open".) See also `data/set/intervals.lean` for `set.Ico`, modelling intervals in general preorders, and `multiset.Ico` and `finset.Ico` for `n ≤ x < m` as a multiset or as a finset. @TODO (anyone): Define `Ioo` and `Icc`, state basic lemmas about them. @TODO (anyone): Prove that `finset.Ico` and `set.Ico` agree. @TODO (anyone): Also do the versions for integers? @TODO (anyone): One could generalise even further, defining 'locally finite partial orders', for which `set.Ico a b` is `[finite]`, and 'locally finite total orders', for which there is a list model. -/ def Ico (n m : ℕ) : list ℕ := range' n (m - n) namespace Ico theorem zero_bot (n : ℕ) : Ico 0 n = range n := by rw [Ico, nat.sub_zero, range_eq_range'] @[simp] theorem length (n m : ℕ) : length (Ico n m) = m - n := by dsimp [Ico]; simp only [length_range'] theorem pairwise_lt (n m : ℕ) : pairwise (<) (Ico n m) := by dsimp [Ico]; simp only [pairwise_lt_range'] theorem nodup (n m : ℕ) : nodup (Ico n m) := by dsimp [Ico]; simp only [nodup_range'] @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := suffices n ≤ l ∧ l < n + (m - n) ↔ n ≤ l ∧ l < m, by simp [Ico, this], begin cases le_total n m with hnm hmn, { rw [nat.add_sub_of_le hnm] }, { rw [nat.sub_eq_zero_of_le hmn, add_zero], exact and_congr_right (assume hnl, iff.intro (assume hln, (not_le_of_gt hln hnl).elim) (assume hlm, lt_of_lt_of_le hlm hmn)) } end theorem eq_nil_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = [] := by simp [Ico, nat.sub_eq_zero_of_le h] theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := by rw [Ico, Ico, map_add_range', nat.add_sub_add_right, add_comm n k] theorem map_sub (n m k : ℕ) (h₁ : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := begin by_cases h₂ : n < m, { rw [Ico, Ico], rw nat.sub_sub_sub_cancel_right h₁, rw [map_sub_range' _ _ _ h₁] }, { simp at h₂, rw [eq_nil_of_le h₂], rw [eq_nil_of_le (nat.sub_le_sub_right h₂ _)], refl } end @[simp] theorem self_empty {n : ℕ} : Ico n n = [] := eq_nil_of_le (le_refl n) @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = [] ↔ m ≤ n := iff.intro (assume h, nat.le_of_sub_eq_zero $ by rw [← length, h]; refl) eq_nil_of_le lemma append_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ++ Ico m l = Ico n l := begin dunfold Ico, convert range'_append _ _ _, { exact (nat.add_sub_of_le hnm).symm }, { rwa [← nat.add_sub_assoc hnm, nat.sub_add_cancel] } end @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = [] := begin apply eq_nil_iff_forall_not_mem.2, intro a, simp only [and_imp, not_and, not_lt, list.mem_inter, list.Ico.mem], intros h₁ h₂ h₃, exfalso, exact not_lt_of_ge h₃ h₂ end @[simp] lemma bag_inter_consecutive (n m l : ℕ) : list.bag_inter (Ico n m) (Ico m l) = [] := (bag_inter_nil_iff_inter_nil _ _).2 (inter_consecutive n m l) @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = [n] := by dsimp [Ico]; simp [nat.add_sub_cancel_left] theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] := by rwa [← succ_singleton, append_consecutive]; exact nat.le_succ _ theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := by rw [← append_consecutive (nat.le_succ n) h, succ_singleton]; refl @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = [m - 1] := by dsimp [Ico]; rw nat.sub_sub_self h; simp theorem chain'_succ (n m : ℕ) : chain' (λa b, b = succ a) (Ico n m) := begin by_cases n < m, { rw [eq_cons h], exact chain_succ_range' _ _ }, { rw [eq_nil_of_le (le_of_not_gt h)], trivial } end @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := by simp; intros; refl lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := filter_eq_self.2 $ assume k hk, lt_of_lt_of_le (mem.1 hk).2 hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = [] := filter_eq_nil.2 $ assume k hk, not_lt_of_le $ le_trans hln $ (mem.1 hk).1 lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := begin cases le_total n l with hnl hln, { rw [← append_consecutive hnl hlm, filter_append, filter_lt_of_top_le (le_refl l), filter_lt_of_le_bot (le_refl l), append_nil] }, { rw [eq_nil_of_le hln, filter_lt_of_le_bot hln] } end @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := begin cases le_total m l with hml hlm, { rw [min_eq_left hml, filter_lt_of_top_le hml] }, { rw [min_eq_right hlm, filter_lt_of_ge hlm] } end lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := filter_eq_self.2 $ assume k hk, le_trans hln (mem.1 hk).1 lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = [] := filter_eq_nil.2 $ assume k hk, not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml) lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := begin cases le_total l m with hlm hml, { rw [← append_consecutive hnl hlm, filter_append, filter_le_of_top_le (le_refl l), filter_le_of_le_bot (le_refl l), nil_append] }, { rw [eq_nil_of_le hml, filter_le_of_top_le hml] } end @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (_root_.max n l) m := begin cases le_total n l with hnl hln, { rw [max_eq_right hnl, filter_le_of_le hnl] }, { rw [max_eq_left hln, filter_le_of_le_bot hln] } end /-- For any natural numbers n, a, and b, one of the following holds: 1. n < a 2. n ≥ b 3. n ∈ Ico a b -/ lemma trichotomy (n a b : ℕ) : n < a ∨ b ≤ n ∨ n ∈ Ico a b := begin by_cases h₁ : n < a, { left, exact h₁ }, { right, by_cases h₂ : n ∈ Ico a b, { right, exact h₂ }, { left, simp only [Ico.mem, not_and, not_lt] at *, exact h₂ h₁ }} end end Ico @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp only [enum, enum_from_map_fst, range_eq_range'] theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val @[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) : nth_le (range n) i H = i := option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)] theorem of_fn_eq_pmap {α n} {f : fin n → α} : of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) := by rw [pmap_eq_map_attach]; from ext_le (by simp) (λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩]) theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) : nodup (of_fn f) := by rw of_fn_eq_pmap; from nodup_pmap (λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n) section tfae /- tfae: The Following (propositions) Are Equivalent -/ theorem tfae_nil : tfae [] := forall_mem_nil _ theorem tfae_singleton (p) : tfae [p] := by simp [tfae, -eq_iff_iff] theorem tfae_cons_of_mem {a b} {l : list Prop} (h : b ∈ l) : tfae (a::l) ↔ (a ↔ b) ∧ tfae l := ⟨λ H, ⟨H a (by simp) b (or.inr h), λ p hp q hq, H _ (or.inr hp) _ (or.inr hq)⟩, begin rintro ⟨ab, H⟩ p (rfl | hp) q (rfl | hq), { refl }, { exact ab.trans (H _ h _ hq) }, { exact (ab.trans (H _ h _ hp)).symm }, { exact H _ hp _ hq } end⟩ theorem tfae_cons_cons {a b} {l : list Prop} : tfae (a::b::l) ↔ (a ↔ b) ∧ tfae (b::l) := tfae_cons_of_mem (or.inl rfl) theorem tfae_of_forall (b : Prop) (l : list Prop) (h : ∀ a ∈ l, a ↔ b) : tfae l := λ a₁ h₁ a₂ h₂, (h _ h₁).trans (h _ h₂).symm theorem tfae_of_cycle {a b} {l : list Prop} : list.chain (→) a (b::l) → (ilast' b l → a) → tfae (a::b::l) := begin induction l with c l IH generalizing a b; simp only [tfae_cons_cons, tfae_singleton, and_true, chain_cons, chain.nil] at *, { intros a b, exact iff.intro a b }, rintros ⟨ab,⟨bc,ch⟩⟩ la, have := IH ⟨bc,ch⟩ (ab ∘ la), exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (ilast'_mem _ _)).1 ∘ bc⟩, this⟩ end theorem tfae.out {l} (h : tfae l) (n₁ n₂) (h₁ : n₁ < list.length l . tactic.exact_dec_trivial) (h₂ : n₂ < list.length l . tactic.exact_dec_trivial) : list.nth_le l n₁ h₁ ↔ list.nth_le l n₂ h₂ := h _ (list.nth_le_mem _ _ _) _ (list.nth_le_mem _ _ _) end tfae lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n := by simp [rotate] @[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; refl @[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate] @[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl @[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate'] @[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length | [] n := rfl | (a::l) 0 := rfl | (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp lemma rotate'_eq_take_append_drop : ∀ {l : list α} {n : ℕ}, n ≤ l.length → l.rotate' n = l.drop n ++ l.take n | [] n h := by simp [drop_append_of_le_length h] | l 0 h := by simp [take_append_of_le_length h] | (a::l) (n+1) h := have hnl : n ≤ l.length, from le_of_succ_le_succ h, have hnl' : n ≤ (l ++ [a]).length, by rw [length_append, length_cons, list.length, zero_add]; exact (le_of_succ_le h), by rw [rotate'_cons_succ, rotate'_eq_take_append_drop hnl', drop, take, drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m) | (a::l) 0 m := by simp | [] n m := by simp | (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ] @[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l := by rw rotate'_eq_take_append_drop (le_refl _); simp @[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l | 0 := by simp | (n+1) := calc l.rotate' (l.length * (n + 1)) = (l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length : by simp [-rotate'_length, nat.mul_succ, rotate'_rotate'] ... = l : by rw [rotate'_length, rotate'_length_mul] lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n := calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul ... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div] lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n := if h : l.length = 0 then by simp [length_eq_zero, *] at * else by rw [← rotate'_mod, rotate'_eq_take_append_drop (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))]; simp [rotate] lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate n.succ = (l ++ [a]).rotate n := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ] @[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l | [] _ n := by simp | (a::l) _ 0 := by simp | (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm] @[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length := by rw [rotate_eq_rotate', length_rotate'] lemma rotate_eq_take_append_drop {l : list α} {n : ℕ} : n ≤ l.length → l.rotate n = l.drop n ++ l.take n := by rw rotate_eq_rotate'; exact rotate'_eq_take_append_drop lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate'] @[simp] lemma rotate_length (l : list α) : rotate l l.length = l := by rw [rotate_eq_rotate', rotate'_length] @[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l := by rw [rotate_eq_rotate', rotate'_length_mul] lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ), (l.rotate n).prod = 1 | [] _ _ := by simp | (a::l) hl n := have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial), by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl; rw [← rotate_mod, rotate_eq_take_append_drop this, list.prod_append, mul_eq_one_iff_inv_eq, ← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one] section choose variables (p : α → Prop) [decidable_pred p] (l : list α) 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 namespace func variables {a : α} variables {as as1 as2 as3 : list α} localized "notation as ` {` m ` ↦ ` a `}` := list.func.set a as m" in list.func /- set -/ lemma length_set [inhabited α] : ∀ {m : ℕ} {as : list α}, (as {m ↦ a}).length = _root_.max as.length (m+1) | 0 [] := rfl | 0 (a::as) := by {rw max_eq_left, refl, simp [nat.le_add_right]} | (m+1) [] := by simp only [set, nat.zero_max, length, @length_set m] | (m+1) (a::as) := by simp only [set, nat.max_succ_succ, length, @length_set m] @[simp] lemma get_nil [inhabited α] {k : ℕ} : get k [] = default α := by {cases k; refl} lemma get_eq_default_of_le [inhabited α] : ∀ (k : ℕ) {as : list α}, as.length ≤ k → get k as = default α | 0 [] h1 := rfl | 0 (a::as) h1 := by cases h1 | (k+1) [] h1 := rfl | (k+1) (a::as) h1 := begin apply get_eq_default_of_le k, rw ← nat.succ_le_succ_iff, apply h1, end @[simp] lemma get_set [inhabited α] {a : α} : ∀ {k : ℕ} {as : list α}, get k (as {k ↦ a}) = a | 0 as := by {cases as; refl, } | (k+1) as := by {cases as; simp [get_set]} lemma eq_get_of_mem [inhabited α] {a : α} : ∀ {as : list α}, a ∈ as → ∃ n : nat, ∀ d : α, a = (get n as) | [] h := by cases h | (b::as) h := begin rw mem_cons_iff at h, cases h, { existsi 0, intro d, apply h }, { cases eq_get_of_mem h with n h2, existsi (n+1), apply h2 } end lemma mem_get_of_le [inhabited α] : ∀ {n : ℕ} {as : list α}, n < as.length → get n as ∈ as | _ [] h1 := by cases h1 | 0 (a::as) _ := or.inl rfl | (n+1) (a::as) h1 := begin apply or.inr, unfold get, apply mem_get_of_le, apply nat.lt_of_succ_lt_succ h1, end lemma mem_get_of_ne_zero [inhabited α] : ∀ {n : ℕ} {as : list α}, get n as ≠ default α → get n as ∈ as | _ [] h1 := begin exfalso, apply h1, rw get_nil end | 0 (a::as) h1 := or.inl rfl | (n+1) (a::as) h1 := begin unfold get, apply (or.inr (mem_get_of_ne_zero _)), apply h1 end lemma get_set_eq_of_ne [inhabited α] {a : α} : ∀ {as : list α} (k : ℕ) (m : ℕ), m ≠ k → get m (as {k ↦ a}) = get m as | as 0 m h1 := by { cases m, contradiction, cases as; simp only [set, get, get_nil] } | as (k+1) m h1 := begin cases as; cases m, simp only [set, get], { have h3 : get m (nil {k ↦ a}) = default α, { rw [get_set_eq_of_ne k m, get_nil], intro hc, apply h1, simp [hc] }, apply h3 }, simp only [set, get], { apply get_set_eq_of_ne k m, intro hc, apply h1, simp [hc], } end lemma get_map [inhabited α] [inhabited β] {f : α → β} : ∀ {n : ℕ} {as : list α}, n < as.length → get n (as.map f) = f (get n as) | _ [] h := by cases h | 0 (a::as) h := rfl | (n+1) (a::as) h1 := begin have h2 : n < length as, { rw [← nat.succ_le_iff, ← nat.lt_succ_iff], apply h1 }, apply get_map h2, end lemma get_map' [inhabited α] [inhabited β] {f : α → β} {n : ℕ} {as : list α} : f (default α) = (default β) → get n (as.map f) = f (get n as) := begin intro h1, by_cases h2 : n < as.length, { apply get_map h2, }, { rw not_lt at h2, rw [get_eq_default_of_le _ h2, get_eq_default_of_le, h1], rw [length_map], apply h2 } end lemma forall_val_of_forall_mem [inhabited α] {as : list α} {p : α → Prop} : p (default α) → (∀ x ∈ as, p x) → (∀ n, p (get n as)) := begin intros h1 h2 n, by_cases h3 : n < as.length, { apply h2 _ (mem_get_of_le h3) }, { rw not_lt at h3, rw get_eq_default_of_le _ h3, apply h1 } end /- equiv -/ lemma equiv_refl [inhabited α] : equiv as as := λ k, rfl lemma equiv_symm [inhabited α] : equiv as1 as2 → equiv as2 as1 := λ h1 k, (h1 k).symm lemma equiv_trans [inhabited α] : equiv as1 as2 → equiv as2 as3 → equiv as1 as3 := λ h1 h2 k, eq.trans (h1 k) (h2 k) lemma equiv_of_eq [inhabited α] : as1 = as2 → equiv as1 as2 := begin intro h1, rw h1, apply equiv_refl end lemma eq_of_equiv [inhabited α] : ∀ {as1 as2 : list α}, as1.length = as2.length → equiv as1 as2 → as1 = as2 | [] [] h1 h2 := rfl | (_::_) [] h1 h2 := by cases h1 | [] (_::_) h1 h2 := by cases h1 | (a1::as1) (a2::as2) h1 h2 := begin congr, { apply h2 0 }, have h3 : as1.length = as2.length, { simpa [add_left_inj, add_comm, length] using h1 }, apply eq_of_equiv h3, intro m, apply h2 (m+1) end /- neg -/ @[simp] lemma get_neg [add_group α] {k : ℕ} {as : list α} : @get α ⟨0⟩ k (neg as) = -(@get α ⟨0⟩ k as) := by {unfold neg, rw (@get_map' α α ⟨0⟩), apply neg_zero} @[simp] lemma length_neg [has_neg α] (as : list α) : (neg as).length = as.length := by simp only [neg, length_map] /- pointwise -/ lemma nil_pointwise [inhabited α] [inhabited β] {f : α → β → γ} : ∀ bs : list β, pointwise f [] bs = bs.map (f $ default α) | [] := rfl | (b::bs) := by simp only [nil_pointwise bs, pointwise, eq_self_iff_true, and_self, map] lemma pointwise_nil [inhabited α] [inhabited β] {f : α → β → γ} : ∀ as : list α, pointwise f as [] = as.map (λ a, f a $ default β) | [] := rfl | (a::as) := by simp only [pointwise_nil as, pointwise, eq_self_iff_true, and_self, list.map] lemma get_pointwise [inhabited α] [inhabited β] [inhabited γ] {f : α → β → γ} (h1 : f (default α) (default β) = default γ) : ∀ (k : nat) (as : list α) (bs : list β), get k (pointwise f as bs) = f (get k as) (get k bs) | k [] [] := by simp only [h1, get_nil, pointwise, get] | 0 [] (b::bs) := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) [] (b::bs) := by { have : get k (map (f $ default α) bs) = f (default α) (get k bs), { simpa [nil_pointwise, get_nil] using (get_pointwise k [] bs) }, simpa [get, get_nil, pointwise, map] } | 0 (a::as) [] := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) (a::as) [] := by simpa [get, get_nil, pointwise, map, pointwise_nil, get_nil] using get_pointwise k as [] | 0 (a::as) (b::bs) := by simp only [pointwise, get] | (k+1) (a::as) (b::bs) := by simp only [pointwise, get, get_pointwise k] lemma length_pointwise [inhabited α] [inhabited β] {f : α → β → γ} : ∀ {as : list α} {bs : list β}, (pointwise f as bs).length = _root_.max as.length bs.length | [] [] := rfl | [] (b::bs) := by simp only [pointwise, length, length_map, max_eq_right (nat.zero_le (length bs + 1))] | (a::as) [] := by simp only [pointwise, length, length_map, max_eq_left (nat.zero_le (length as + 1))] | (a::as) (b::bs) := by simp only [pointwise, length, nat.max_succ_succ, @length_pointwise as bs] /- add -/ @[simp] lemma get_add {α : Type u} [add_monoid α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (add xs ys) = ( @get α ⟨0⟩ k xs + @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply zero_add} @[simp] lemma length_add {α : Type u} [has_zero α] [has_add α] {xs ys : list α} : (add xs ys).length = _root_.max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_add {α : Type u} [add_monoid α] (as : list α) : add [] as = as := begin rw [add, @nil_pointwise α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, zero_add], refl end @[simp] lemma add_nil {α : Type u} [add_monoid α] (as : list α) : add as [] = as := begin rw [add, @pointwise_nil α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, add_zero], refl end lemma map_add_map {α : Type u} [add_monoid α] (f g : α → α) {as : list α} : add (as.map f) (as.map g) = as.map (λ x, f x + g x) := begin apply @eq_of_equiv _ (⟨0⟩ : inhabited α), { rw [length_map, length_add, max_eq_left, length_map], apply le_of_eq, rw [length_map, length_map] }, intros m, rw [get_add], by_cases h : m < length as, { repeat {rw [@get_map α α ⟨0⟩ ⟨0⟩ _ _ _ h]} }, rw not_lt at h, repeat {rw [get_eq_default_of_le m]}; try {rw length_map, apply h}, apply zero_add end /- sub -/ @[simp] lemma get_sub {α : Type u} [add_group α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (sub xs ys) = (@get α ⟨0⟩ k xs - @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply sub_zero} @[simp] lemma length_sub [has_zero α] [has_sub α] {xs ys : list α} : (sub xs ys).length = _root_.max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_sub {α : Type} [add_group α] (as : list α) : sub [] as = neg as := begin rw [sub, nil_pointwise], congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, zero_sub] end @[simp] lemma sub_nil {α : Type} [add_group α] (as : list α) : sub as [] = as := begin rw [sub, pointwise_nil], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, sub_zero], refl end end func namespace nat /-- The antidiagonal of a natural number `n` is the list of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : list (ℕ × ℕ) := (range (n+1)).map (λ i, (i, n - i)) /-- 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 := begin rw [antidiagonal, mem_map], split, { rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_sub_of_le hi }, { rintro rfl, refine ⟨x.fst, _, _⟩, { rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ }, { exact prod.ext rfl (nat.add_sub_cancel_left _ _) } } end /-- The length of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 := by rw [antidiagonal, length_map, length_range] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] := ext_le (length_antidiagonal 0) $ λ n h₁ h₂, begin rw [length_antidiagonal, lt_succ_iff, le_zero_iff] at h₁, subst n, simp [antidiagonal] end /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := nodup_map (@injective_of_left_inverse ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl) (nodup_range _) end nat end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm
ad0e2328cc02316ec7dae22c312cb7a18290a1a5
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/ring_theory/jacobson.lean
380a4ce05058993c2ab449e7d297d7b97a90710c
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
34,367
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import ring_theory.localization.away import ring_theory.ideal.over import ring_theory.jacobson_ideal /-! # Jacobson Rings The following conditions are equivalent for a ring `R`: 1. Every radical ideal `I` is equal to its Jacobson radical 2. Every radical ideal `I` can be written as an intersection of maximal ideals 3. Every prime ideal `I` is equal to its Jacobson radical Any ring satisfying any of these equivalent conditions is said to be Jacobson. Some particular examples of Jacobson rings are also proven. `is_jacobson_quotient` says that the quotient of a Jacobson ring is Jacobson. `is_jacobson_localization` says the localization of a Jacobson ring to a single element is Jacobson. `is_jacobson_polynomial_iff_is_jacobson` says polynomials over a Jacobson ring form a Jacobson ring. ## Main definitions Let `R` be a commutative ring. Jacobson Rings are defined using the first of the above conditions * `is_jacobson R` is the proposition that `R` is a Jacobson ring. It is a class, implemented as the predicate that for any ideal, `I.radical = I` implies `I.jacobson = I`. ## Main statements * `is_jacobson_iff_prime_eq` is the equivalence between conditions 1 and 3 above. * `is_jacobson_iff_Inf_maximal` is the equivalence between conditions 1 and 2 above. * `is_jacobson_of_surjective` says that if `R` is a Jacobson ring and `f : R →+* S` is surjective, then `S` is also a Jacobson ring * `is_jacobson_mv_polynomial` says that multi-variate polynomials over a Jacobson ring are Jacobson. ## Tags Jacobson, Jacobson Ring -/ namespace ideal open polynomial open_locale polynomial section is_jacobson variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R} /-- A ring is a Jacobson ring if for every radical ideal `I`, the Jacobson radical of `I` is equal to `I`. See `is_jacobson_iff_prime_eq` and `is_jacobson_iff_Inf_maximal` for equivalent definitions. -/ class is_jacobson (R : Type*) [comm_ring R] : Prop := (out' : ∀ (I : ideal R), I.radical = I → I.jacobson = I) theorem is_jacobson_iff {R} [comm_ring R] : is_jacobson R ↔ ∀ (I : ideal R), I.radical = I → I.jacobson = I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_jacobson.out {R} [comm_ring R] : is_jacobson R → ∀ {I : ideal R}, I.radical = I → I.jacobson = I := is_jacobson_iff.1 /-- A ring is a Jacobson ring if and only if for all prime ideals `P`, the Jacobson radical of `P` is equal to `P`. -/ lemma is_jacobson_iff_prime_eq : is_jacobson R ↔ ∀ P : ideal R, is_prime P → P.jacobson = P := begin refine is_jacobson_iff.trans ⟨λ h I hI, h I (is_prime.radical hI), _⟩, refine λ h I hI, le_antisymm (λ x hx, _) (λ x hx, mem_Inf.mpr (λ _ hJ, hJ.left hx)), rw [← hI, radical_eq_Inf I, mem_Inf], intros P hP, rw set.mem_set_of_eq at hP, erw mem_Inf at hx, erw [← h P hP.right, mem_Inf], exact λ J hJ, hx ⟨le_trans hP.left hJ.left, hJ.right⟩ end /-- A ring `R` is Jacobson if and only if for every prime ideal `I`, `I` can be written as the infimum of some collection of maximal ideals. Allowing ⊤ in the set `M` of maximal ideals is equivalent, but makes some proofs cleaner. -/ lemma is_jacobson_iff_Inf_maximal : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal.1 (H.out (is_prime.radical h)), λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal.2 (H hP))⟩ lemma is_jacobson_iff_Inf_maximal' : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal'.1 (H.out (is_prime.radical h)), λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal'.2 (H hP))⟩ lemma radical_eq_jacobson [H : is_jacobson R] (I : ideal R) : I.radical = I.jacobson := le_antisymm (le_Inf (λ J ⟨hJ, hJ_max⟩, (is_prime.radical_le_iff hJ_max.is_prime).mpr hJ)) ((H.out (radical_idem I)) ▸ (jacobson_mono le_radical)) /-- Fields have only two ideals, and the condition holds for both of them. -/ @[priority 100] instance is_jacobson_field {K : Type*} [field K] : is_jacobson K := ⟨λ I hI, or.rec_on (eq_bot_or_top I) (λ h, le_antisymm (Inf_le ⟨le_of_eq rfl, (eq.symm h) ▸ bot_is_maximal⟩) ((eq.symm h) ▸ bot_le)) (λ h, by rw [h, jacobson_eq_top_iff])⟩ theorem is_jacobson_of_surjective [H : is_jacobson R] : (∃ (f : R →+* S), function.surjective f) → is_jacobson S := begin rintros ⟨f, hf⟩, rw is_jacobson_iff_Inf_maximal, intros p hp, use map f '' {J : ideal R | comap f p ≤ J ∧ J.is_maximal }, use λ j ⟨J, hJ, hmap⟩, hmap ▸ or.symm (map_eq_top_or_is_maximal_of_surjective f hf hJ.right), have : p = map f ((comap f p).jacobson), from (is_jacobson.out' (comap f p) (by rw [← comap_radical, is_prime.radical hp])).symm ▸ (map_comap_of_surjective f hf p).symm, exact eq.trans this (map_Inf hf (λ J ⟨hJ, _⟩, le_trans (ideal.ker_le_comap f) hJ)), end @[priority 100] instance is_jacobson_quotient [is_jacobson R] : is_jacobson (R ⧸ I) := is_jacobson_of_surjective ⟨quotient.mk I, (by rintro ⟨x⟩; use x; refl)⟩ lemma is_jacobson_iso (e : R ≃+* S) : is_jacobson R ↔ is_jacobson S := ⟨λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e : R →+* S), e.surjective⟩, λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e.symm : S →+* R), e.symm.surjective⟩⟩ lemma is_jacobson_of_is_integral [algebra R S] (hRS : algebra.is_integral R S) (hR : is_jacobson R) : is_jacobson S := begin rw is_jacobson_iff_prime_eq, introsI P hP, by_cases hP_top : comap (algebra_map R S) P = ⊤, { simp [comap_eq_top_iff.1 hP_top] }, { haveI : nontrivial (R ⧸ comap (algebra_map R S) P) := quotient.nontrivial hP_top, rw jacobson_eq_iff_jacobson_quotient_eq_bot, refine eq_bot_of_comap_eq_bot (is_integral_quotient_of_is_integral hRS) _, rw [eq_bot_iff, ← jacobson_eq_iff_jacobson_quotient_eq_bot.1 ((is_jacobson_iff_prime_eq.1 hR) (comap (algebra_map R S) P) (comap_is_prime _ _)), comap_jacobson], refine Inf_le_Inf (λ J hJ, _), simp only [true_and, set.mem_image, bot_le, set.mem_set_of_eq], haveI : J.is_maximal, { simpa using hJ }, exact exists_ideal_over_maximal_of_is_integral (is_integral_quotient_of_is_integral hRS) J (comap_bot_le_of_injective _ algebra_map_quotient_injective) } end lemma is_jacobson_of_is_integral' (f : R →+* S) (hf : f.is_integral) (hR : is_jacobson R) : is_jacobson S := @is_jacobson_of_is_integral _ _ _ _ f.to_algebra hf hR end is_jacobson section localization open is_localization submonoid variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R} variables (y : R) [algebra R S] [is_localization.away y S] lemma disjoint_powers_iff_not_mem (hI : I.radical = I) : disjoint ((submonoid.powers y) : set R) ↑I ↔ y ∉ I.1 := begin refine ⟨λ h, set.disjoint_left.1 h (mem_powers _), λ h, (disjoint_iff).mpr (eq_bot_iff.mpr _)⟩, rintros x ⟨⟨n, rfl⟩, hx'⟩, rw [← hI] at hx', exact absurd (hI ▸ mem_radical_of_pow_mem hx' : y ∈ I.carrier) h end variables (S) /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its comap. See `le_rel_iso_of_maximal` for the more general relation isomorphism -/ lemma is_maximal_iff_is_maximal_disjoint [H : is_jacobson R] (J : ideal S) : J.is_maximal ↔ (comap (algebra_map R S) J).is_maximal ∧ y ∉ ideal.comap (algebra_map R S) J := begin split, { refine λ h, ⟨_, λ hy, h.ne_top (ideal.eq_top_of_is_unit_mem _ hy (map_units _ ⟨y, submonoid.mem_powers _⟩))⟩, have hJ : J.is_prime := is_maximal.is_prime h, rw is_prime_iff_is_prime_disjoint (submonoid.powers y) at hJ, have : y ∉ (comap (algebra_map R S) J).1 := set.disjoint_left.1 hJ.right (submonoid.mem_powers _), erw [← H.out (is_prime.radical hJ.left), mem_Inf] at this, push_neg at this, rcases this with ⟨I, hI, hI'⟩, convert hI.right, by_cases hJ : J = map (algebra_map R S) I, { rw [hJ, comap_map_of_is_prime_disjoint (powers y) S I (is_maximal.is_prime hI.right)], rwa disjoint_powers_iff_not_mem y (is_maximal.is_prime hI.right).radical }, { have hI_p : (map (algebra_map R S) I).is_prime, { refine is_prime_of_is_prime_disjoint (powers y) _ I hI.right.is_prime _, rwa disjoint_powers_iff_not_mem y (is_maximal.is_prime hI.right).radical }, have : J ≤ map (algebra_map R S) I := (map_comap (submonoid.powers y) S J) ▸ (map_mono hI.left), exact absurd (h.1.2 _ (lt_of_le_of_ne this hJ)) hI_p.1 } }, { refine λ h, ⟨⟨λ hJ, h.1.ne_top (eq_top_iff.2 _), λ I hI, _⟩⟩, { rwa [eq_top_iff, ← (is_localization.order_embedding (powers y) S).le_iff_le] at hJ }, { have := congr_arg (map (algebra_map R S)) (h.1.1.2 _ ⟨comap_mono (le_of_lt hI), _⟩), rwa [map_comap (powers y) S I, map_top] at this, refine λ hI', hI.right _, rw [← map_comap (powers y) S I, ← map_comap (powers y) S J], exact map_mono hI' } } end variables {S} /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its map. See `le_rel_iso_of_maximal` for the more general statement, and the reverse of this implication -/ lemma is_maximal_of_is_maximal_disjoint [is_jacobson R] (I : ideal R) (hI : I.is_maximal) (hy : y ∉ I) : (map (algebra_map R S) I).is_maximal := begin rw [is_maximal_iff_is_maximal_disjoint S y, comap_map_of_is_prime_disjoint (powers y) S I (is_maximal.is_prime hI) ((disjoint_powers_iff_not_mem y (is_maximal.is_prime hI).radical).2 hy)], exact ⟨hI, hy⟩ end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y` -/ def order_iso_of_maximal [is_jacobson R] : {p : ideal S // p.is_maximal} ≃o {p : ideal R // p.is_maximal ∧ y ∉ p} := { to_fun := λ p, ⟨ideal.comap (algebra_map R S) p.1, (is_maximal_iff_is_maximal_disjoint S y p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map (algebra_map R S) p.1, is_maximal_of_is_maximal_disjoint y p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap (powers y) S J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint _ _ I.1 (is_maximal.is_prime I.2.1) ((disjoint_powers_iff_not_mem y I.2.1.is_prime.radical).2 I.2.2)), map_rel_iff' := λ I I', ⟨λ h, (show I.val ≤ I'.val, from (map_comap (powers y) S I.val) ▸ (map_comap (powers y) S I'.val) ▸ (ideal.map_mono h)), λ h x hx, h hx⟩ } include y /-- If `S` is the localization of the Jacobson ring `R` at the submonoid generated by `y : R`, then `S` is Jacobson. -/ lemma is_jacobson_localization [H : is_jacobson R] : is_jacobson S := begin rw is_jacobson_iff_prime_eq, refine λ P' hP', le_antisymm _ le_jacobson, obtain ⟨hP', hPM⟩ := (is_localization.is_prime_iff_is_prime_disjoint (powers y) S P').mp hP', have hP := H.out (is_prime.radical hP'), refine (le_of_eq (is_localization.map_comap (powers y) S P'.jacobson).symm).trans ((map_mono _).trans (le_of_eq (is_localization.map_comap (powers y) S P'))), have : Inf { I : ideal R | comap (algebra_map R S) P' ≤ I ∧ I.is_maximal ∧ y ∉ I } ≤ comap (algebra_map R S) P', { intros x hx, have hxy : x * y ∈ (comap (algebra_map R S) P').jacobson, { rw [ideal.jacobson, mem_Inf], intros J hJ, by_cases y ∈ J, { exact J.mul_mem_left x h }, { exact J.mul_mem_right y ((mem_Inf.1 hx) ⟨hJ.left, ⟨hJ.right, h⟩⟩) } }, rw hP at hxy, cases hP'.mem_or_mem hxy with hxy hxy, { exact hxy }, { exact (hPM ⟨submonoid.mem_powers _, hxy⟩).elim } }, refine le_trans _ this, rw [ideal.jacobson, comap_Inf', Inf_eq_infi], refine infi_le_infi_of_subset (λ I hI, ⟨map (algebra_map R S) I, ⟨_, _⟩⟩), { exact ⟨le_trans (le_of_eq ((is_localization.map_comap (powers y) S P').symm)) (map_mono hI.1), is_maximal_of_is_maximal_disjoint y _ hI.2.1 hI.2.2⟩ }, { exact is_localization.comap_map_of_is_prime_disjoint _ S I (is_maximal.is_prime hI.2.1) ((disjoint_powers_iff_not_mem y hI.2.1.is_prime.radical).2 hI.2.2) } end end localization namespace polynomial open polynomial section comm_ring variables {R S : Type*} [comm_ring R] [comm_ring S] [is_domain S] variables {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] /-- If `I` is a prime ideal of `polynomial R` and `pX ∈ I` is a non-constant polynomial, then the map `R →+* R[x]/I` descends to an integral map when localizing at `pX.leading_coeff`. In particular `X` is integral because it satisfies `pX`, and constants are trivially integral, so integrality of the entire extension follows by closure under addition and multiplication. -/ lemma is_integral_is_localization_polynomial_quotient (P : ideal R[X]) (pX : R[X]) (hpX : pX ∈ P) [algebra (R ⧸ P.comap (C : R →+* _)) Rₘ] [is_localization.away (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff Rₘ] [algebra (R[X] ⧸ P) Sₘ] [is_localization ((submonoid.powers (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff).map (quotient_map P C le_rfl) : submonoid (R[X] ⧸ P)) Sₘ] : (is_localization.map Sₘ (quotient_map P C le_rfl) ((submonoid.powers (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff).le_comap_map) : Rₘ →+* _) .is_integral := begin let P' : ideal R := P.comap C, let M : submonoid (R ⧸ P') := submonoid.powers (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff, let M' : submonoid (R[X] ⧸ P) := (submonoid.powers (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff).map (quotient_map P C le_rfl), let φ : R ⧸ P' →+* R[X] ⧸ P := quotient_map P C le_rfl, let φ' : Rₘ →+* Sₘ := is_localization.map Sₘ φ M.le_comap_map, have hφ' : φ.comp (quotient.mk P') = (quotient.mk P).comp C := rfl, intro p, obtain ⟨⟨p', ⟨q, hq⟩⟩, hp⟩ := is_localization.surj M' p, suffices : φ'.is_integral_elem (algebra_map _ _ p'), { obtain ⟨q', hq', rfl⟩ := hq, obtain ⟨q'', hq''⟩ := is_unit_iff_exists_inv'.1 (is_localization.map_units Rₘ (⟨q', hq'⟩ : M)), refine φ'.is_integral_of_is_integral_mul_unit p (algebra_map _ _ (φ q')) q'' _ (hp.symm ▸ this), convert trans (trans (φ'.map_mul _ _).symm (congr_arg φ' hq'')) φ'.map_one using 2, rw [← φ'.comp_apply, is_localization.map_comp, ring_hom.comp_apply, subtype.coe_mk] }, refine is_integral_of_mem_closure'' (((algebra_map _ Sₘ).comp (quotient.mk P)) '' (insert X {p | p.degree ≤ 0})) _ _ _, { rintros x ⟨p, hp, rfl⟩, refine hp.rec_on (λ hy, _) (λ hy, _), { refine hy.symm ▸ (φ.is_integral_elem_localization_at_leading_coeff ((quotient.mk P) X) (pX.map (quotient.mk P')) _ M ⟨1, pow_one _⟩), rwa [eval₂_map, hφ', ← hom_eval₂, quotient.eq_zero_iff_mem, eval₂_C_X] }, { rw [set.mem_set_of_eq, degree_le_zero_iff] at hy, refine hy.symm ▸ ⟨X - C (algebra_map _ _ ((quotient.mk P') (p.coeff 0))), monic_X_sub_C _, _⟩, simp only [eval₂_sub, eval₂_C, eval₂_X], rw [sub_eq_zero, ← φ'.comp_apply, is_localization.map_comp], refl } }, { obtain ⟨p, rfl⟩ := quotient.mk_surjective p', refine polynomial.induction_on p (λ r, subring.subset_closure $ set.mem_image_of_mem _ (or.inr degree_C_le)) (λ _ _ h1 h2, _) (λ n _ hr, _), { convert subring.add_mem _ h1 h2, rw [ring_hom.map_add, ring_hom.map_add] }, { rw [pow_succ X n, mul_comm X, ← mul_assoc, ring_hom.map_mul, ring_hom.map_mul], exact subring.mul_mem _ hr (subring.subset_closure (set.mem_image_of_mem _ (or.inl rfl))) } }, end /-- If `f : R → S` descends to an integral map in the localization at `x`, and `R` is a Jacobson ring, then the intersection of all maximal ideals in `S` is trivial -/ lemma jacobson_bot_of_integral_localization {R : Type*} [comm_ring R] [is_domain R] [is_jacobson R] (Rₘ Sₘ : Type*) [comm_ring Rₘ] [comm_ring Sₘ] (φ : R →+* S) (hφ : function.injective φ) (x : R) (hx : x ≠ 0) [algebra R Rₘ] [is_localization.away x Rₘ] [algebra S Sₘ] [is_localization ((submonoid.powers x).map φ : submonoid S) Sₘ] (hφ' : ring_hom.is_integral (is_localization.map Sₘ φ (submonoid.powers x).le_comap_map : Rₘ →+* Sₘ)) : (⊥ : ideal S).jacobson = (⊥ : ideal S) := begin have hM : ((submonoid.powers x).map φ : submonoid S) ≤ non_zero_divisors S := map_le_non_zero_divisors_of_injective φ hφ (powers_le_non_zero_divisors_of_no_zero_divisors hx), letI : is_domain Sₘ := is_localization.is_domain_of_le_non_zero_divisors _ hM, let φ' : Rₘ →+* Sₘ := is_localization.map _ φ (submonoid.powers x).le_comap_map, suffices : ∀ I : ideal Sₘ, I.is_maximal → (I.comap (algebra_map S Sₘ)).is_maximal, { have hϕ' : comap (algebra_map S Sₘ) (⊥ : ideal Sₘ) = (⊥ : ideal S), { rw [← ring_hom.ker_eq_comap_bot, ← ring_hom.injective_iff_ker_eq_bot], exact is_localization.injective Sₘ hM }, have hSₘ : is_jacobson Sₘ := is_jacobson_of_is_integral' φ' hφ' (is_jacobson_localization x), refine eq_bot_iff.mpr (le_trans _ (le_of_eq hϕ')), rw [← hSₘ.out radical_bot_of_is_domain, comap_jacobson], exact Inf_le_Inf (λ j hj, ⟨bot_le, let ⟨J, hJ⟩ := hj in hJ.2 ▸ this J hJ.1.2⟩) }, introsI I hI, -- Remainder of the proof is pulling and pushing ideals around the square and the quotient square haveI : (I.comap (algebra_map S Sₘ)).is_prime := comap_is_prime _ I, haveI : (I.comap φ').is_prime := comap_is_prime φ' I, haveI : (⊥ : ideal (S ⧸ I.comap (algebra_map S Sₘ))).is_prime := bot_prime, have hcomm: φ'.comp (algebra_map R Rₘ) = (algebra_map S Sₘ).comp φ := is_localization.map_comp _, let f := quotient_map (I.comap (algebra_map S Sₘ)) φ le_rfl, let g := quotient_map I (algebra_map S Sₘ) le_rfl, have := is_maximal_comap_of_is_integral_of_is_maximal' φ' hφ' I hI, have := ((is_maximal_iff_is_maximal_disjoint Rₘ x _).1 this).left, have : ((I.comap (algebra_map S Sₘ)).comap φ).is_maximal, { rwa [comap_comap, hcomm, ← comap_comap] at this }, rw ← bot_quotient_is_maximal_iff at this ⊢, refine is_maximal_of_is_integral_of_is_maximal_comap' f _ ⊥ ((eq_bot_iff.2 (comap_bot_le_of_injective f quotient_map_injective)).symm ▸ this), exact f.is_integral_tower_bot_of_is_integral g quotient_map_injective ((comp_quotient_map_eq_of_comp_eq hcomm I).symm ▸ (ring_hom.is_integral_trans _ _ (ring_hom.is_integral_of_surjective _ (is_localization.surjective_quotient_map_of_maximal_of_localization (submonoid.powers x) Rₘ (by rwa [comap_comap, hcomm, ← bot_quotient_is_maximal_iff]))) (ring_hom.is_integral_quotient_of_is_integral _ hφ'))), end /-- Used to bootstrap the proof of `is_jacobson_polynomial_iff_is_jacobson`. That theorem is more general and should be used instead of this one. -/ private lemma is_jacobson_polynomial_of_domain (R : Type*) [comm_ring R] [is_domain R] [hR : is_jacobson R] (P : ideal R[X]) [is_prime P] (hP : ∀ (x : R), C x ∈ P → x = 0) : P.jacobson = P := begin by_cases Pb : P = ⊥, { exact Pb.symm ▸ jacobson_bot_polynomial_of_jacobson_bot (hR.out radical_bot_of_is_domain) }, { rw jacobson_eq_iff_jacobson_quotient_eq_bot, haveI : (P.comap (C : R →+* R[X])).is_prime := comap_is_prime C P, obtain ⟨p, pP, p0⟩ := exists_nonzero_mem_of_ne_bot Pb hP, let x := (polynomial.map (quotient.mk (comap (C : R →+* _) P)) p).leading_coeff, have hx : x ≠ 0 := by rwa [ne.def, leading_coeff_eq_zero], refine jacobson_bot_of_integral_localization (localization.away x) (localization ((submonoid.powers x).map (P.quotient_map C le_rfl) : submonoid (R[X] ⧸ P))) (quotient_map P C le_rfl) quotient_map_injective x hx _, -- `convert` is noticeably faster than `exact` here: convert is_integral_is_localization_polynomial_quotient P p pP } end lemma is_jacobson_polynomial_of_is_jacobson (hR : is_jacobson R) : is_jacobson R[X] := begin refine is_jacobson_iff_prime_eq.mpr (λ I, _), introI hI, let R' : subring (R[X] ⧸ I) := ((quotient.mk I).comp C).range, let i : R →+* R' := ((quotient.mk I).comp C).range_restrict, have hi : function.surjective (i : R → R') := ((quotient.mk I).comp C).range_restrict_surjective, have hi' : (polynomial.map_ring_hom i : R[X] →+* R'[X]).ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), replace hf := congr_arg (λ (g : polynomial (((quotient.mk I).comp C).range)), g.coeff n) hf, change (polynomial.map ((quotient.mk I).comp C).range_restrict f).coeff n = 0 at hf, rw [coeff_map, subtype.ext_iff] at hf, rwa [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], }, haveI := map_is_prime_of_surjective (show function.surjective (map_ring_hom i), from map_surjective i hi) hi', suffices : (I.map (polynomial.map_ring_hom i)).jacobson = (I.map (polynomial.map_ring_hom i)), { replace this := congr_arg (comap (polynomial.map_ring_hom i)) this, rw [← map_jacobson_of_surjective _ hi', comap_map_of_surjective _ _, comap_map_of_surjective _ _] at this, refine le_antisymm (le_trans (le_sup_of_le_left le_rfl) (le_trans (le_of_eq this) (sup_le le_rfl hi'))) le_jacobson, all_goals {exact polynomial.map_surjective i hi} }, exact @is_jacobson_polynomial_of_domain R' _ _ (is_jacobson_of_surjective ⟨i, hi⟩) (map (map_ring_hom i) I) _ (eq_zero_of_polynomial_mem_map_range I), end theorem is_jacobson_polynomial_iff_is_jacobson : is_jacobson R[X] ↔ is_jacobson R := begin refine ⟨_, is_jacobson_polynomial_of_is_jacobson⟩, introI H, exact is_jacobson_of_surjective ⟨eval₂_ring_hom (ring_hom.id _) 1, λ x, ⟨C x, by simp only [coe_eval₂_ring_hom, ring_hom.id_apply, eval₂_C]⟩⟩, end instance [is_jacobson R] : is_jacobson R[X] := is_jacobson_polynomial_iff_is_jacobson.mpr ‹is_jacobson R› end comm_ring section variables {R : Type*} [comm_ring R] [is_jacobson R] variables (P : ideal R[X]) [hP : P.is_maximal] include P hP lemma is_maximal_comap_C_of_is_maximal [nontrivial R] (hP' : ∀ (x : R), C x ∈ P → x = 0) : is_maximal (comap (C : R →+* R[X]) P : ideal R) := begin haveI hp'_prime : (P.comap (C : R →+* R[X]) : ideal R).is_prime := comap_is_prime C P, obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_of_maximal P polynomial_not_is_field), have : (m : R[X]) ≠ 0, rwa [ne.def, submodule.coe_eq_zero], let φ : R ⧸ P.comap (C : R →+* R[X]) →+* R[X] ⧸ P := quotient_map P (C : R →+* R[X]) le_rfl, let M : submonoid (R ⧸ P.comap C) := submonoid.powers ((m : R[X]).map (quotient.mk (P.comap (C : R →+* R[X]) : ideal R))).leading_coeff, rw ← bot_quotient_is_maximal_iff, have hp0 : ((m : R[X]).map (quotient.mk (P.comap (C : R →+* R[X]) : ideal R))).leading_coeff ≠ 0 := λ hp0', this $ map_injective (quotient.mk (P.comap (C : R →+* R[X]) : ideal R)) ((injective_iff_map_eq_zero (quotient.mk (P.comap (C : R →+* R[X]) : ideal R))).2 (λ x hx, by rwa [quotient.eq_zero_iff_mem, (by rwa eq_bot_iff : (P.comap C : ideal R) = ⊥)] at hx)) (by simpa only [leading_coeff_eq_zero, polynomial.map_zero] using hp0'), have hM : (0 : R ⧸ P.comap C) ∉ M := λ ⟨n, hn⟩, hp0 (pow_eq_zero hn), suffices : (⊥ : ideal (localization M)).is_maximal, { rw ← is_localization.comap_map_of_is_prime_disjoint M (localization M) ⊥ bot_prime (λ x hx, hM (hx.2 ▸ hx.1)), refine ((is_maximal_iff_is_maximal_disjoint (localization M) _ _).mp (by rwa map_bot)).1, swap, exact localization.is_localization }, let M' : submonoid (R[X] ⧸ P) := M.map φ, have hM' : (0 : R[X] ⧸ P) ∉ M' := λ ⟨z, hz⟩, hM (quotient_map_injective (trans hz.2 φ.map_zero.symm) ▸ hz.1), haveI : is_domain (localization M') := is_localization.is_domain_localization (le_non_zero_divisors_of_no_zero_divisors hM'), suffices : (⊥ : ideal (localization M')).is_maximal, { rw le_antisymm bot_le (comap_bot_le_of_injective _ (is_localization.map_injective_of_injective M (localization M) (localization M') quotient_map_injective )), refine is_maximal_comap_of_is_integral_of_is_maximal' _ _ ⊥ this, apply is_integral_is_localization_polynomial_quotient P _ (submodule.coe_mem m) }, rw (map_bot.symm : (⊥ : ideal (localization M')) = map (algebra_map (R[X] ⧸ P) (localization M')) ⊥), let bot_maximal := ((bot_quotient_is_maximal_iff _).mpr hP), refine map.is_maximal (algebra_map _ _) (is_field.localization_map_bijective hM' _) bot_maximal, rwa [← quotient.maximal_ideal_iff_is_field_quotient, ← bot_quotient_is_maximal_iff], end /-- Used to bootstrap the more general `quotient_mk_comp_C_is_integral_of_jacobson` -/ private lemma quotient_mk_comp_C_is_integral_of_jacobson' [nontrivial R] (hR : is_jacobson R) (hP' : ∀ (x : R), C x ∈ P → x = 0) : ((quotient.mk P).comp C : R →+* R[X] ⧸ P).is_integral := begin refine (is_integral_quotient_map_iff _).mp _, let P' : ideal R := P.comap C, obtain ⟨pX, hpX, hp0⟩ := exists_nonzero_mem_of_ne_bot (ne_of_lt (bot_lt_of_maximal P polynomial_not_is_field)).symm hP', let M : submonoid (R ⧸ P') := submonoid.powers (pX.map (quotient.mk P')).leading_coeff, let φ : R ⧸ P' →+* R[X] ⧸ P := quotient_map P C le_rfl, haveI hp'_prime : P'.is_prime := comap_is_prime C P, have hM : (0 : R ⧸ P') ∉ M := λ ⟨n, hn⟩, hp0 $ leading_coeff_eq_zero.mp (pow_eq_zero hn), let M' : submonoid (R[X] ⧸ P) := M.map (quotient_map P C le_rfl), refine ((quotient_map P C le_rfl).is_integral_tower_bot_of_is_integral (algebra_map _ (localization M')) _ _), { refine is_localization.injective (localization M') (show M' ≤ _, from le_non_zero_divisors_of_no_zero_divisors (λ hM', hM _)), exact (let ⟨z, zM, z0⟩ := hM' in (quotient_map_injective (trans z0 φ.map_zero.symm)) ▸ zM) }, { rw ← is_localization.map_comp M.le_comap_map, refine ring_hom.is_integral_trans (algebra_map (R ⧸ P') (localization M)) (is_localization.map (localization M') _ M.le_comap_map) _ _, { exact (algebra_map (R ⧸ P') (localization M)).is_integral_of_surjective (is_field.localization_map_bijective hM ((quotient.maximal_ideal_iff_is_field_quotient _).mp (is_maximal_comap_C_of_is_maximal P hP'))).2 }, { -- `convert` here is faster than `exact`, and this proof is near the time limit. convert is_integral_is_localization_polynomial_quotient P pX hpX } } end /-- If `R` is a Jacobson ring, and `P` is a maximal ideal of `polynomial R`, then `R → R[X]/P` is an integral map. -/ lemma quotient_mk_comp_C_is_integral_of_jacobson : ((quotient.mk P).comp C : R →+* R[X] ⧸ P).is_integral := begin let P' : ideal R := P.comap C, haveI : P'.is_prime := comap_is_prime C P, let f : R[X] →+* polynomial (R ⧸ P') := polynomial.map_ring_hom (quotient.mk P'), have hf : function.surjective f := map_surjective (quotient.mk P') quotient.mk_surjective, have hPJ : P = (P.map f).comap f, { rw comap_map_of_surjective _ hf, refine le_antisymm (le_sup_of_le_left le_rfl) (sup_le le_rfl _), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using (polynomial.ext_iff.mp hp) n }, refine ring_hom.is_integral_tower_bot_of_is_integral _ _ (injective_quotient_le_comap_map P) _, rw ← quotient_mk_maps_eq, refine ring_hom.is_integral_trans _ _ ((quotient.mk P').is_integral_of_surjective quotient.mk_surjective) _, apply quotient_mk_comp_C_is_integral_of_jacobson' _ _ (λ x hx, _), any_goals { exact ideal.is_jacobson_quotient }, { exact or.rec_on (map_eq_top_or_is_maximal_of_surjective f hf hP) (λ h, absurd (trans (h ▸ hPJ : P = comap f ⊤) comap_top : P = ⊤) hP.ne_top) id }, { apply_instance, }, { obtain ⟨z, rfl⟩ := quotient.mk_surjective x, rwa [quotient.eq_zero_iff_mem, mem_comap, hPJ, mem_comap, coe_map_ring_hom, map_C] } end lemma is_maximal_comap_C_of_is_jacobson : (P.comap (C : R →+* R[X])).is_maximal := begin rw [← @mk_ker _ _ P, ring_hom.ker_eq_comap_bot, comap_comap], exact is_maximal_comap_of_is_integral_of_is_maximal' _ (quotient_mk_comp_C_is_integral_of_jacobson P) ⊥ ((bot_quotient_is_maximal_iff _).mpr hP), end omit P hP lemma comp_C_integral_of_surjective_of_jacobson {S : Type*} [field S] (f : R[X] →+* S) (hf : function.surjective f) : (f.comp C).is_integral := begin haveI : (f.ker).is_maximal := ring_hom.ker_is_maximal_of_surjective f hf, let g : R[X] ⧸ f.ker →+* S := ideal.quotient.lift f.ker f (λ _ h, h), have hfg : (g.comp (quotient.mk f.ker)) = f := ring_hom_ext' rfl rfl, rw [← hfg, ring_hom.comp_assoc], refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f.ker) (g.is_integral_of_surjective _), --(quotient.lift_surjective f.ker f _ hf)), rw [← hfg] at hf, exact function.surjective.of_comp hf, end end end polynomial open mv_polynomial ring_hom namespace mv_polynomial lemma is_jacobson_mv_polynomial_fin {R : Type*} [comm_ring R] [H : is_jacobson R] : ∀ (n : ℕ), is_jacobson (mv_polynomial (fin n) R) | 0 := ((is_jacobson_iso ((rename_equiv R (equiv.equiv_pempty (fin 0))).to_ring_equiv.trans (is_empty_ring_equiv R pempty))).mpr H) | (n+1) := (is_jacobson_iso (fin_succ_equiv R n).to_ring_equiv).2 (polynomial.is_jacobson_polynomial_iff_is_jacobson.2 (is_jacobson_mv_polynomial_fin n)) /-- General form of the nullstellensatz for Jacobson rings, since in a Jacobson ring we have `Inf {P maximal | P ≥ I} = Inf {P prime | P ≥ I} = I.radical`. Fields are always Jacobson, and in that special case this is (most of) the classical Nullstellensatz, since `I(V(I))` is the intersection of maximal ideals containing `I`, which is then `I.radical` -/ instance {R : Type*} [comm_ring R] {ι : Type*} [fintype ι] [is_jacobson R] : is_jacobson (mv_polynomial ι R) := begin haveI := classical.dec_eq ι, let e := fintype.equiv_fin ι, rw is_jacobson_iso (rename_equiv R e).to_ring_equiv, exact is_jacobson_mv_polynomial_fin _ end variables {n : ℕ} lemma quotient_mk_comp_C_is_integral_of_jacobson {R : Type*} [comm_ring R] [is_jacobson R] (P : ideal (mv_polynomial (fin n) R)) [P.is_maximal] : ((quotient.mk P).comp mv_polynomial.C : R →+* mv_polynomial _ R ⧸ P).is_integral := begin unfreezingI {induction n with n IH}, { refine ring_hom.is_integral_of_surjective _ (function.surjective.comp quotient.mk_surjective _), exact C_surjective (fin 0) }, { rw [← fin_succ_equiv_comp_C_eq_C, ← ring_hom.comp_assoc, ← ring_hom.comp_assoc, ← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc (polynomial.C), ← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc, ring_hom.comp_assoc, ← quotient_map_comp_mk le_rfl, ← ring_hom.comp_assoc (quotient.mk _)], refine ring_hom.is_integral_trans _ _ _ _, { refine ring_hom.is_integral_trans _ _ (is_integral_of_surjective _ quotient.mk_surjective) _, refine ring_hom.is_integral_trans _ _ _ _, { apply (is_integral_quotient_map_iff _).mpr (IH _), apply polynomial.is_maximal_comap_C_of_is_jacobson _, { exact mv_polynomial.is_jacobson_mv_polynomial_fin n }, { apply comap_is_maximal_of_surjective, exact (fin_succ_equiv R n).symm.surjective } }, { refine (is_integral_quotient_map_iff _).mpr _, rw ← quotient_map_comp_mk le_rfl, refine ring_hom.is_integral_trans _ _ _ ((is_integral_quotient_map_iff _).mpr _), { exact ring_hom.is_integral_of_surjective _ quotient.mk_surjective }, { apply polynomial.quotient_mk_comp_C_is_integral_of_jacobson _, { exact mv_polynomial.is_jacobson_mv_polynomial_fin n }, { exact comap_is_maximal_of_surjective _ (fin_succ_equiv R n).symm.surjective } } } }, { refine (is_integral_quotient_map_iff _).mpr _, refine ring_hom.is_integral_trans _ _ _ (is_integral_of_surjective _ quotient.mk_surjective), exact ring_hom.is_integral_of_surjective _ (fin_succ_equiv R n).symm.surjective } } end lemma comp_C_integral_of_surjective_of_jacobson {R : Type*} [comm_ring R] [is_jacobson R] {σ : Type*} [fintype σ] {S : Type*} [field S] (f : mv_polynomial σ R →+* S) (hf : function.surjective f) : (f.comp C).is_integral := begin have e := (fintype.equiv_fin σ).symm, let f' : mv_polynomial (fin _) R →+* S := f.comp (rename_equiv R e).to_ring_equiv.to_ring_hom, have hf' : function.surjective f' := ((function.surjective.comp hf (rename_equiv R e).surjective)), have : (f'.comp C).is_integral, { haveI : (f'.ker).is_maximal := ker_is_maximal_of_surjective f' hf', let g : mv_polynomial _ R ⧸ f'.ker →+* S := ideal.quotient.lift f'.ker f' (λ _ h, h), have hfg : (g.comp (quotient.mk f'.ker)) = f' := ring_hom_ext (λ r, rfl) (λ i, rfl), rw [← hfg, ring_hom.comp_assoc], refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f'.ker) (g.is_integral_of_surjective _), rw ← hfg at hf', exact function.surjective.of_comp hf' }, rw ring_hom.comp_assoc at this, convert this, refine ring_hom.ext (λ x, _), exact ((rename_equiv R e).commutes' x).symm, end end mv_polynomial end ideal
b6927eb7ca77fa207dc287083397cf67e4be66d6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/free_monoid/basic.lean
224f4956db049b4f7e5d78b9b2e42c9a1c247c7f
[ "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
8,884
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Yury Kudryashov -/ import data.list.big_operators.basic /-! # Free monoid over a given alphabet ## Main definitions * `free_monoid α`: free monoid over alphabet `α`; defined as a synonym for `list α` with multiplication given by `(++)`. * `free_monoid.of`: embedding `α → free_monoid α` sending each element `x` to `[x]`; * `free_monoid.lift`: natural equivalence between `α → M` and `free_monoid α →* M` * `free_monoid.map`: embedding of `α → β` into `free_monoid α →* free_monoid β` given by `list.map`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {M : Type*} [monoid M] {N : Type*} [monoid N] /-- Free monoid over a given alphabet. -/ @[to_additive "Free nonabelian additive monoid over a given alphabet"] def free_monoid (α) := list α namespace free_monoid @[to_additive] instance [decidable_eq α] : decidable_eq (free_monoid α) := list.decidable_eq /-- The identity equivalence between `free_monoid α` and `list α`. -/ @[to_additive "The identity equivalence between `free_add_monoid α` and `list α`."] def to_list : free_monoid α ≃ list α := equiv.refl _ /-- The identity equivalence between `list α` and `free_monoid α`. -/ @[to_additive "The identity equivalence between `list α` and `free_add_monoid α`."] def of_list : list α ≃ free_monoid α := equiv.refl _ @[simp, to_additive] lemma to_list_symm : (@to_list α).symm = of_list := rfl @[simp, to_additive] lemma of_list_symm : (@of_list α).symm = to_list := rfl @[simp, to_additive] lemma to_list_of_list (l : list α) : to_list (of_list l) = l := rfl @[simp, to_additive] lemma of_list_to_list (xs : free_monoid α) : of_list (to_list xs) = xs := rfl @[simp, to_additive] lemma to_list_comp_of_list : @to_list α ∘ of_list = id := rfl @[simp, to_additive] lemma of_list_comp_to_list : @of_list α ∘ to_list = id := rfl @[to_additive] instance : cancel_monoid (free_monoid α) := { one := of_list [], mul := λ x y, of_list (x.to_list ++ y.to_list), mul_one := list.append_nil, one_mul := list.nil_append, mul_assoc := list.append_assoc, mul_left_cancel := λ _ _ _, list.append_left_cancel, mul_right_cancel := λ _ _ _, list.append_right_cancel } @[to_additive] instance : inhabited (free_monoid α) := ⟨1⟩ @[simp, to_additive] lemma to_list_one : (1 : free_monoid α).to_list = [] := rfl @[simp, to_additive] lemma of_list_nil : of_list ([] : list α) = 1 := rfl @[simp, to_additive] lemma to_list_mul (xs ys : free_monoid α) : (xs * ys).to_list = xs.to_list ++ ys.to_list := rfl @[simp, to_additive] lemma of_list_append (xs ys : list α) : of_list (xs ++ ys) = of_list xs * of_list ys := rfl @[simp, to_additive] lemma to_list_prod (xs : list (free_monoid α)) : to_list xs.prod = (xs.map to_list).join := by induction xs; simp [*, list.join] @[simp, to_additive] lemma of_list_join (xs : list (list α)) : of_list xs.join = (xs.map of_list).prod := to_list.injective $ by simp /-- Embeds an element of `α` into `free_monoid α` as a singleton list. -/ @[to_additive "Embeds an element of `α` into `free_add_monoid α` as a singleton list." ] def of (x : α) : free_monoid α := of_list [x] @[simp, to_additive] lemma to_list_of (x : α) : to_list (of x) = [x] := rfl @[to_additive] lemma of_list_singleton (x : α) : of_list [x] = of x := rfl @[simp, to_additive] lemma of_list_cons (x : α) (xs : list α) : of_list (x :: xs) = of x * of_list xs := rfl @[to_additive] lemma to_list_of_mul (x : α) (xs : free_monoid α) : to_list (of x * xs) = x :: xs.to_list := rfl @[to_additive] lemma of_injective : function.injective (@of α) := list.singleton_injective /-- Recursor for `free_monoid` using `1` and `free_monoid.of x * xs` instead of `[]` and `x :: xs`. -/ @[elab_as_eliminator, to_additive "Recursor for `free_add_monoid` using `0` and `free_add_monoid.of x + xs` instead of `[]` and `x :: xs`."] def rec_on {C : free_monoid α → Sort*} (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : C xs := list.rec_on xs h0 ih @[simp, to_additive] lemma rec_on_one {C : free_monoid α → Sort*} (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : @rec_on α C 1 h0 ih = h0 := rfl @[simp, to_additive] lemma rec_on_of_mul {C : free_monoid α → Sort*} (x : α) (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : @rec_on α C (of x * xs) h0 ih = ih x xs (rec_on xs h0 ih) := rfl /-- A version of `list.cases_on` for `free_monoid` using `1` and `free_monoid.of x * xs` instead of `[]` and `x :: xs`. -/ @[elab_as_eliminator, to_additive "A version of `list.cases_on` for `free_add_monoid` using `0` and `free_add_monoid.of x + xs` instead of `[]` and `x :: xs`."] def cases_on {C : free_monoid α → Sort*} (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C (of x * xs)) : C xs := list.cases_on xs h0 ih @[simp, to_additive] lemma cases_on_one {C : free_monoid α → Sort*} (h0 : C 1) (ih : Π x xs, C (of x * xs)) : @cases_on α C 1 h0 ih = h0 := rfl @[simp, to_additive] lemma cases_on_of_mul {C : free_monoid α → Sort*} (x : α) (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C (of x * xs)) : @cases_on α C (of x * xs) h0 ih = ih x xs := rfl @[ext, to_additive] lemma hom_eq ⦃f g : free_monoid α →* M⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := monoid_hom.ext $ λ l, rec_on l (f.map_one.trans g.map_one.symm) $ λ x xs hxs, by simp only [h, hxs, monoid_hom.map_mul] /-- Equivalence between maps `α → M` and monoid homomorphisms `free_monoid α →* M`. -/ @[to_additive "Equivalence between maps `α → A` and additive monoid homomorphisms `free_add_monoid α →+ A`."] def lift : (α → M) ≃ (free_monoid α →* M) := { to_fun := λ f, ⟨λ l, (l.to_list.map f).prod, rfl, λ l₁ l₂, by simp only [to_list_mul, list.map_append, list.prod_append]⟩, inv_fun := λ f x, f (of x), left_inv := λ f, funext $ λ x, one_mul (f x), right_inv := λ f, hom_eq $ λ x, one_mul (f (of x)) } @[simp, to_additive] lemma lift_symm_apply (f : free_monoid α →* M) : lift.symm f = f ∘ of := rfl @[to_additive] lemma lift_apply (f : α → M) (l : free_monoid α) : lift f l = (l.to_list.map f).prod := rfl @[to_additive] lemma lift_comp_of (f : α → M) : lift f ∘ of = f := lift.symm_apply_apply f @[simp, to_additive] lemma lift_eval_of (f : α → M) (x : α) : lift f (of x) = f x := congr_fun (lift_comp_of f) x @[simp, to_additive] lemma lift_restrict (f : free_monoid α →* M) : lift (f ∘ of) = f := lift.apply_symm_apply f @[to_additive] lemma comp_lift (g : M →* N) (f : α → M) : g.comp (lift f) = lift (g ∘ f) := by { ext, simp } @[to_additive] lemma hom_map_lift (g : M →* N) (f : α → M) (x : free_monoid α) : g (lift f x) = lift (g ∘ f) x := monoid_hom.ext_iff.1 (comp_lift g f) x /-- Define a multiplicative action of `free_monoid α` on `β`. -/ @[to_additive "Define an additive action of `free_add_monoid α` on `β`."] def mk_mul_action (f : α → β → β) : mul_action (free_monoid α) β := { smul := λ l b, l.to_list.foldr f b, one_smul := λ x, rfl, mul_smul := λ xs ys b, list.foldr_append _ _ _ _ } @[to_additive] lemma smul_def (f : α → β → β) (l : free_monoid α) (b : β) : (by haveI := mk_mul_action f; exact l • b = l.to_list.foldr f b) := rfl @[to_additive] lemma of_list_smul (f : α → β → β) (l : list α) (b : β) : (by haveI := mk_mul_action f; exact (of_list l) • b = l.foldr f b) := rfl @[simp, to_additive] lemma of_smul (f : α → β → β) (x : α) (y : β) : (by haveI := mk_mul_action f; exact of x • y) = f x y := rfl /-- The unique monoid homomorphism `free_monoid α →* free_monoid β` that sends each `of x` to `of (f x)`. -/ @[to_additive "The unique additive monoid homomorphism `free_add_monoid α →+ free_add_monoid β` that sends each `of x` to `of (f x)`."] def map (f : α → β) : free_monoid α →* free_monoid β := { to_fun := λ l, of_list $ l.to_list.map f, map_one' := rfl, map_mul' := λ l₁ l₂, list.map_append _ _ _ } @[simp, to_additive] lemma map_of (f : α → β) (x : α) : map f (of x) = of (f x) := rfl @[to_additive] lemma to_list_map (f : α → β) (xs : free_monoid α) : (map f xs).to_list = xs.to_list.map f := rfl @[to_additive] lemma of_list_map (f : α → β) (xs : list α) : of_list (xs.map f) = map f (of_list xs) := rfl @[to_additive] lemma lift_of_comp_eq_map (f : α → β) : lift (λ x, of (f x)) = map f := hom_eq $ λ x, rfl @[to_additive] lemma map_comp (g : β → γ) (f : α → β) : map (g ∘ f) = (map g).comp (map f) := hom_eq $ λ x, rfl @[simp, to_additive] lemma map_id : map (@id α) = monoid_hom.id (free_monoid α) := hom_eq $ λ x, rfl end free_monoid
53dd9d4a75139ce21a0806e9c6c5b762440a3257
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/computability/ackermann.lean
37a83d6c913b00cdc4aa99bd6626e90dc13ea129
[ "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
13,501
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import computability.primrec import tactic.linarith /-! # Ackermann function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we define the two-argument Ackermann function `ack`. Despite having a recursive definition, we show that this isn't a primitive recursive function. ## Main results - `exists_lt_ack_of_primrec`: any primitive recursive function is pointwise bounded above by `ack m` for some `m`. - `not_primrec₂_ack`: the two-argument Ackermann function is not primitive recursive. ## Proof approach We very broadly adapt the proof idea from https://www.planetmath.org/ackermannfunctionisnotprimitiverecursive. Namely, we prove that for any primitive recursive `f : ℕ → ℕ`, there exists `m` such that `f n < ack m n` for all `n`. This then implies that `λ n, ack n n` can't be primitive recursive, and so neither can `ack`. We aren't able to use the same bounds as in that proof though, since our approach of using pairing functions differs from their approach of using multivariate functions. The important bounds we show during the main inductive proof (`exists_lt_ack_of_primrec`) are the following. Assuming `∀ n, f n < ack a n` and `∀ n, g n < ack b n`, we have: - `∀ n, nat.mkpair (f n) (g n) < ack (max a b + 3) n`. - `∀ n, g (f n) < ack (max a b + 2) n`. - `∀ n, nat.elim (f n.unpair.1) (λ (y IH : ℕ), g (nat.mkpair n.unpair.1 (nat.mkpair y IH))) n.unpair.2 < ack (max a b + 9) n`. The last one is evidently the hardest. Using `nat.unpair_add_le`, we reduce it to the more manageable - `∀ m n, elim (f m) (λ (y IH : ℕ), g (nat.mkpair m (nat.mkpair y IH))) n < ack (max a b + 9) (m + n)`. We then prove this by induction on `n`. Our proof crucially depends on `ack_mkpair_lt`, which is applied twice, giving us a constant of `4 + 4`. The rest of the proof consists of simpler bounds which bump up our constant to `9`. -/ open nat /-- The two-argument Ackermann function, defined so that - `ack 0 n = n + 1` - `ack (m + 1) 0 = ack m 1` - `ack (m + 1) (n + 1) = ack m (ack (m + 1) n)`. This is of interest as both a fast-growing function, and as an example of a recursive function that isn't primitive recursive. -/ def ack : ℕ → ℕ → ℕ | 0 n := n + 1 | (m + 1) 0 := ack m 1 | (m + 1) (n + 1) := ack m (ack (m + 1) n) @[simp] theorem ack_zero (n : ℕ) : ack 0 n = n + 1 := by rw ack @[simp] theorem ack_succ_zero (m : ℕ) : ack (m + 1) 0 = ack m 1 := by rw ack @[simp] theorem ack_succ_succ (m n : ℕ) : ack (m + 1) (n + 1) = ack m (ack (m + 1) n) := by rw ack @[simp] theorem ack_one (n : ℕ) : ack 1 n = n + 2 := begin induction n with n IH, { simp }, { simp [IH] } end @[simp] theorem ack_two (n : ℕ) : ack 2 n = 2 * n + 3 := begin induction n with n IH, { simp }, { simp [IH, mul_succ] } end private theorem ack_three_aux (n : ℕ) : (ack 3 n : ℤ) = 2 ^ (n + 3) - 3 := begin induction n with n IH, { simp, norm_num }, { simp [IH, pow_succ], rw [mul_sub, sub_add], norm_num } end @[simp] theorem ack_three (n : ℕ) : ack 3 n = 2 ^ (n + 3) - 3 := begin zify, rw cast_sub, { exact_mod_cast ack_three_aux n }, { have H : 3 ≤ 2 ^ 3 := by norm_num, exact H.trans (pow_mono one_le_two $ le_add_left le_rfl) } end theorem ack_pos : ∀ m n, 0 < ack m n | 0 n := by simp | (m + 1) 0 := by { rw ack_succ_zero, apply ack_pos } | (m + 1) (n + 1) := by { rw ack_succ_succ, apply ack_pos } theorem one_lt_ack_succ_left : ∀ m n, 1 < ack (m + 1) n | 0 n := by simp | (m + 1) 0 := by { rw ack_succ_zero, apply one_lt_ack_succ_left } | (m + 1) (n + 1) := by { rw ack_succ_succ, apply one_lt_ack_succ_left } theorem one_lt_ack_succ_right : ∀ m n, 1 < ack m (n + 1) | 0 n := by simp | (m + 1) n := begin rw ack_succ_succ, cases exists_eq_succ_of_ne_zero (ack_pos (m + 1) n).ne', rw h, apply one_lt_ack_succ_right end theorem ack_strict_mono_right : ∀ m, strict_mono (ack m) | 0 n₁ n₂ h := by simpa using h | (m + 1) 0 (n + 1) h := begin rw [ack_succ_zero, ack_succ_succ], exact ack_strict_mono_right _ (one_lt_ack_succ_left m n) end | (m + 1) (n₁ + 1) (n₂ + 1) h := begin rw [ack_succ_succ, ack_succ_succ], apply ack_strict_mono_right _ (ack_strict_mono_right _ _), rwa add_lt_add_iff_right at h end theorem ack_mono_right (m : ℕ) : monotone (ack m) := (ack_strict_mono_right m).monotone theorem ack_injective_right (m : ℕ) : function.injective (ack m) := (ack_strict_mono_right m).injective @[simp] theorem ack_lt_iff_right {m n₁ n₂ : ℕ} : ack m n₁ < ack m n₂ ↔ n₁ < n₂ := (ack_strict_mono_right m).lt_iff_lt @[simp] theorem ack_le_iff_right {m n₁ n₂ : ℕ} : ack m n₁ ≤ ack m n₂ ↔ n₁ ≤ n₂ := (ack_strict_mono_right m).le_iff_le @[simp] theorem ack_inj_right {m n₁ n₂ : ℕ} : ack m n₁ = ack m n₂ ↔ n₁ = n₂ := (ack_injective_right m).eq_iff theorem max_ack_right (m n₁ n₂ : ℕ) : ack m (max n₁ n₂) = max (ack m n₁) (ack m n₂) := (ack_mono_right m).map_max theorem add_lt_ack : ∀ m n, m + n < ack m n | 0 n := by simp | (m + 1) 0 := by simpa using add_lt_ack m 1 | (m + 1) (n + 1) := calc (m + 1) + n + 1 ≤ m + (m + n + 2) : by linarith ... < ack m (m + n + 2) : add_lt_ack _ _ ... ≤ ack m (ack (m + 1) n) : ack_mono_right m $ le_of_eq_of_le (by ring_nf) $ succ_le_of_lt $ add_lt_ack (m + 1) n ... = ack (m + 1) (n + 1) : (ack_succ_succ m n).symm theorem add_add_one_le_ack (m n : ℕ) : m + n + 1 ≤ ack m n := succ_le_of_lt (add_lt_ack m n) theorem lt_ack_left (m n : ℕ) : m < ack m n := (self_le_add_right m n).trans_lt $ add_lt_ack m n theorem lt_ack_right (m n : ℕ) : n < ack m n := (self_le_add_left n m).trans_lt $ add_lt_ack m n -- we reorder the arguments to appease the equation compiler private theorem ack_strict_mono_left' : ∀ {m₁ m₂} n, m₁ < m₂ → ack m₁ n < ack m₂ n | m 0 n := λ h, (nat.not_lt_zero m h).elim | 0 (m + 1) 0 := λ h, by simpa using one_lt_ack_succ_right m 0 | 0 (m + 1) (n + 1) := λ h, begin rw [ack_zero, ack_succ_succ], apply lt_of_le_of_lt (le_trans _ $ add_le_add_left (add_add_one_le_ack _ _) m) (add_lt_ack _ _), linarith end | (m₁ + 1) (m₂ + 1) 0 := λ h, by simpa using ack_strict_mono_left' 1 ((add_lt_add_iff_right 1).1 h) | (m₁ + 1) (m₂ + 1) (n + 1) := λ h, begin rw [ack_succ_succ, ack_succ_succ], exact (ack_strict_mono_left' _ $ (add_lt_add_iff_right 1).1 h).trans (ack_strict_mono_right _ $ ack_strict_mono_left' n h) end theorem ack_strict_mono_left (n : ℕ) : strict_mono (λ m, ack m n) := λ m₁ m₂, ack_strict_mono_left' n theorem ack_mono_left (n : ℕ) : monotone (λ m, ack m n) := (ack_strict_mono_left n).monotone theorem ack_injective_left (n : ℕ) : function.injective (λ m, ack m n) := (ack_strict_mono_left n).injective @[simp] theorem ack_lt_iff_left {m₁ m₂ n : ℕ} : ack m₁ n < ack m₂ n ↔ m₁ < m₂ := (ack_strict_mono_left n).lt_iff_lt @[simp] theorem ack_le_iff_left {m₁ m₂ n : ℕ} : ack m₁ n ≤ ack m₂ n ↔ m₁ ≤ m₂ := (ack_strict_mono_left n).le_iff_le @[simp] theorem ack_inj_left {m₁ m₂ n : ℕ} : ack m₁ n = ack m₂ n ↔ m₁ = m₂ := (ack_injective_left n).eq_iff theorem max_ack_left (m₁ m₂ n : ℕ) : ack (max m₁ m₂) n = max (ack m₁ n) (ack m₂ n) := (ack_mono_left n).map_max theorem ack_le_ack {m₁ m₂ n₁ n₂ : ℕ} (hm : m₁ ≤ m₂) (hn : n₁ ≤ n₂) : ack m₁ n₁ ≤ ack m₂ n₂ := (ack_mono_left n₁ hm).trans $ ack_mono_right m₂ hn theorem ack_succ_right_le_ack_succ_left (m n : ℕ) : ack m (n + 1) ≤ ack (m + 1) n := begin cases n, { simp }, { rw [ack_succ_succ, succ_eq_add_one], apply ack_mono_right m (le_trans _ $ add_add_one_le_ack _ n), linarith } end -- All the inequalities from this point onwards are specific to the main proof. private theorem sq_le_two_pow_add_one_minus_three (n : ℕ) : n ^ 2 ≤ 2 ^ (n + 1) - 3 := begin induction n with k hk, { norm_num }, { cases k, { norm_num }, { rw [succ_eq_add_one, add_sq, pow_succ 2, two_mul (2 ^ _), add_tsub_assoc_of_le, add_comm (2 ^ _), add_assoc], { apply add_le_add hk, norm_num, apply succ_le_of_lt, rw [pow_succ, mul_lt_mul_left (zero_lt_two' ℕ)], apply lt_two_pow }, { rw [pow_succ, pow_succ], linarith [one_le_pow k 2 zero_lt_two] } } } end theorem ack_add_one_sq_lt_ack_add_three : ∀ m n, (ack m n + 1) ^ 2 ≤ ack (m + 3) n | 0 n := by simpa using sq_le_two_pow_add_one_minus_three (n + 2) | (m + 1) 0 := by { rw [ack_succ_zero, ack_succ_zero], apply ack_add_one_sq_lt_ack_add_three } | (m + 1) (n + 1) := begin rw [ack_succ_succ, ack_succ_succ], apply (ack_add_one_sq_lt_ack_add_three _ _).trans (ack_mono_right _ $ ack_mono_left _ _), linarith end theorem ack_ack_lt_ack_max_add_two (m n k : ℕ) : ack m (ack n k) < ack (max m n + 2) k := calc ack m (ack n k) ≤ ack (max m n) (ack n k) : ack_mono_left _ (le_max_left _ _) ... < ack (max m n) (ack (max m n + 1) k) : ack_strict_mono_right _ $ ack_strict_mono_left k $ lt_succ_of_le $ le_max_right m n ... = ack (max m n + 1) (k + 1) : (ack_succ_succ _ _).symm ... ≤ ack (max m n + 2) k : ack_succ_right_le_ack_succ_left _ _ theorem ack_add_one_sq_lt_ack_add_four (m n : ℕ) : ack m ((n + 1) ^ 2) < ack (m + 4) n := calc ack m ((n + 1) ^ 2) < ack m ((ack m n + 1) ^ 2) : ack_strict_mono_right m $ pow_lt_pow_of_lt_left (succ_lt_succ $ lt_ack_right m n) zero_lt_two ... ≤ ack m (ack (m + 3) n) : ack_mono_right m $ ack_add_one_sq_lt_ack_add_three m n ... ≤ ack (m + 2) (ack (m + 3) n) : ack_mono_left _ $ by linarith ... = ack (m + 3) (n + 1) : (ack_succ_succ _ n).symm ... ≤ ack (m + 4) n : ack_succ_right_le_ack_succ_left _ n theorem ack_mkpair_lt (m n k : ℕ) : ack m (mkpair n k) < ack (m + 4) (max n k) := (ack_strict_mono_right m $ mkpair_lt_max_add_one_sq n k).trans $ ack_add_one_sq_lt_ack_add_four _ _ /-- If `f` is primitive recursive, there exists `m` such that `f n < ack m n` for all `n`. -/ theorem exists_lt_ack_of_nat_primrec {f : ℕ → ℕ} (hf : nat.primrec f) : ∃ m, ∀ n, f n < ack m n := begin induction hf with f g hf hg IHf IHg f g hf hg IHf IHg f g hf hg IHf IHg, -- Zero function: { exact ⟨0, ack_pos 0⟩ }, -- Successor function: { refine ⟨1, λ n, _⟩, rw succ_eq_one_add, apply add_lt_ack }, -- Left projection: { refine ⟨0, λ n, _⟩, rw [ack_zero, lt_succ_iff], exact unpair_left_le n }, -- Right projection: { refine ⟨0, λ n, _⟩, rw [ack_zero, lt_succ_iff], exact unpair_right_le n }, all_goals { cases IHf with a ha, cases IHg with b hb }, -- Pairing: { refine ⟨max a b + 3, λ n, (mkpair_lt_max_add_one_sq _ _).trans_le $ (nat.pow_le_pow_of_le_left (add_le_add_right _ _) 2).trans $ ack_add_one_sq_lt_ack_add_three _ _⟩, rw max_ack_left, exact max_le_max (ha n).le (hb n).le }, -- Composition: { exact ⟨max a b + 2, λ n, (ha _).trans $ (ack_strict_mono_right a $ hb n).trans $ ack_ack_lt_ack_max_add_two a b n⟩ }, -- Primitive recursion operator: { -- We prove this simpler inequality first. have : ∀ {m n}, elim (f m) (λ y IH, g $ mkpair m $ mkpair y IH) n < ack (max a b + 9) (m + n), { intros m n, -- We induct on n. induction n with n IH, -- The base case is easy. { apply (ha m).trans (ack_strict_mono_left m $ (le_max_left a b).trans_lt _), linarith }, { -- We get rid of the first `mkpair`. rw elim_succ, apply (hb _).trans ((ack_mkpair_lt _ _ _).trans_le _), -- If m is the maximum, we get a very weak inequality. cases lt_or_le _ m with h₁ h₁, { rw max_eq_left h₁.le, exact ack_le_ack (add_le_add (le_max_right a b) $ by norm_num) (self_le_add_right m _) }, rw max_eq_right h₁, -- We get rid of the second `mkpair`. apply (ack_mkpair_lt _ _ _).le.trans, -- If n is the maximum, we get a very weak inequality. cases lt_or_le _ n with h₂ h₂, { rw [max_eq_left h₂.le, add_assoc], exact ack_le_ack (add_le_add (le_max_right a b) $ by norm_num) ((le_succ n).trans $ self_le_add_left _ _) }, rw max_eq_right h₂, -- We now use the inductive hypothesis, and some simple algebraic manipulation. apply (ack_strict_mono_right _ IH).le.trans, rw [add_succ m, add_succ _ 8, ack_succ_succ (_ + 8), add_assoc], exact ack_mono_left _ (add_le_add (le_max_right a b) le_rfl) } }, -- The proof is now simple. exact ⟨max a b + 9, λ n, this.trans_le $ ack_mono_right _ $ unpair_add_le n⟩ } end theorem not_nat_primrec_ack_self : ¬ nat.primrec (λ n, ack n n) := λ h, by { cases exists_lt_ack_of_nat_primrec h with m hm, exact (hm m).false } theorem not_primrec_ack_self : ¬ _root_.primrec (λ n, ack n n) := by { rw primrec.nat_iff, exact not_nat_primrec_ack_self } /-- The Ackermann function is not primitive recursive. -/ theorem not_primrec₂_ack : ¬ primrec₂ ack := λ h, not_primrec_ack_self $ h.comp primrec.id primrec.id
72cecc6ccf542876ece587717a6777b5078a9334
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/jordan_holder.lean
81b4c25040e921bafdda3e67d014539f1183a647
[ "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
31,025
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import order.lattice import data.list.sort import logic.equiv.fin import logic.equiv.functor import data.fintype.card /-! # Jordan-Hölder Theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves the Jordan Hölder theorem for a `jordan_holder_lattice`, a class also defined in this file. Examples of `jordan_holder_lattice` include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. Using this approach the theorem need not be proved seperately for both groups and modules, the proof in this file can be applied to both. ## Main definitions The main definitions in this file are `jordan_holder_lattice` and `composition_series`, and the relation `equivalent` on `composition_series` A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. A `composition_series X` is a finite nonempty series of elements of the lattice `X` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i, s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` ## Main theorems The main theorem is `composition_series.jordan_holder`, which says that if two composition series have the same least element and the same largest element, then they are `equivalent`. ## TODO Provide instances of `jordan_holder_lattice` for both submodules and subgroups, and potentially for modular lattices. It is not entirely clear how this should be done. Possibly there should be no global instances of `jordan_holder_lattice`, and the instances should only be defined locally in order to prove the Jordan-Hölder theorem for modules/groups and the API should be transferred because many of the theorems in this file will have stronger versions for modules. There will also need to be an API for mapping composition series across homomorphisms. It is also probably possible to provide an instance of `jordan_holder_lattice` for any `modular_lattice`, and in this case the Jordan-Hölder theorem will say that there is a well defined notion of length of a modular lattice. However an instance of `jordan_holder_lattice` for a modular lattice will not be able to contain the correct notion of isomorphism for modules, so a separate instance for modules will still be required and this will clash with the instance for modular lattices, and so at least one of these instances should not be a global instance. -/ universe u open set /-- A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. Examples include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. -/ class jordan_holder_lattice (X : Type u) [lattice X] := (is_maximal : X → X → Prop) (lt_of_is_maximal : ∀ {x y}, is_maximal x y → x < y) (sup_eq_of_is_maximal : ∀ {x y z}, is_maximal x z → is_maximal y z → x ≠ y → x ⊔ y = z) (is_maximal_inf_left_of_is_maximal_sup : ∀ {x y}, is_maximal x (x ⊔ y) → is_maximal y (x ⊔ y) → is_maximal (x ⊓ y) x) (iso : (X × X) → (X × X) → Prop) (iso_symm : ∀ {x y}, iso x y → iso y x) (iso_trans : ∀ {x y z}, iso x y → iso y z → iso x z) (second_iso : ∀ {x y}, is_maximal x (x ⊔ y) → iso (x, x ⊔ y) (x ⊓ y, y)) namespace jordan_holder_lattice variables {X : Type u} [lattice X] [jordan_holder_lattice X] lemma is_maximal_inf_right_of_is_maximal_sup {x y : X} (hxz : is_maximal x (x ⊔ y)) (hyz : is_maximal y (x ⊔ y)) : is_maximal (x ⊓ y) y := begin rw [inf_comm], rw [sup_comm] at hxz hyz, exact is_maximal_inf_left_of_is_maximal_sup hyz hxz end lemma is_maximal_of_eq_inf (x b : X) {a y : X} (ha : x ⊓ y = a) (hxy : x ≠ y) (hxb : is_maximal x b) (hyb : is_maximal y b) : is_maximal a y := begin have hb : x ⊔ y = b, from sup_eq_of_is_maximal hxb hyb hxy, substs a b, exact is_maximal_inf_right_of_is_maximal_sup hxb hyb end lemma second_iso_of_eq {x y a b : X} (hm : is_maximal x a) (ha : x ⊔ y = a) (hb : x ⊓ y = b) : iso (x, a) (b, y) := by substs a b; exact second_iso hm lemma is_maximal.iso_refl {x y : X} (h : is_maximal x y) : iso (x, y) (x, y) := second_iso_of_eq h (sup_eq_right.2 (le_of_lt (lt_of_is_maximal h))) (inf_eq_left.2 (le_of_lt (lt_of_is_maximal h))) end jordan_holder_lattice open jordan_holder_lattice attribute [symm] iso_symm attribute [trans] iso_trans /-- A `composition_series X` is a finite nonempty series of elements of a `jordan_holder_lattice` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. -/ structure composition_series (X : Type u) [lattice X] [jordan_holder_lattice X] : Type u := (length : ℕ) (series : fin (length + 1) → X) (step' : ∀ i : fin length, is_maximal (series i.cast_succ) (series i.succ)) namespace composition_series variables {X : Type u} [lattice X] [jordan_holder_lattice X] instance : has_coe_to_fun (composition_series X) (λ x, fin (x.length + 1) → X) := { coe := composition_series.series } instance [inhabited X] : inhabited (composition_series X) := ⟨{ length := 0, series := default, step' := λ x, x.elim0 }⟩ variables {X} lemma step (s : composition_series X) : ∀ i : fin s.length, is_maximal (s i.cast_succ) (s i.succ) := s.step' @[simp] lemma coe_fn_mk (length : ℕ) (series step) : (@composition_series.mk X _ _ length series step : fin length.succ → X) = series := rfl theorem lt_succ (s : composition_series X) (i : fin s.length) : s i.cast_succ < s i.succ := lt_of_is_maximal (s.step _) protected theorem strict_mono (s : composition_series X) : strict_mono s := fin.strict_mono_iff_lt_succ.2 s.lt_succ protected theorem injective (s : composition_series X) : function.injective s := s.strict_mono.injective @[simp] protected theorem inj (s : composition_series X) {i j : fin s.length.succ} : s i = s j ↔ i = j := s.injective.eq_iff instance : has_mem X (composition_series X) := ⟨λ x s, x ∈ set.range s⟩ lemma mem_def {x : X} {s : composition_series X} : x ∈ s ↔ x ∈ set.range s := iff.rfl lemma total {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) : x ≤ y ∨ y ≤ x := begin rcases set.mem_range.1 hx with ⟨i, rfl⟩, rcases set.mem_range.1 hy with ⟨j, rfl⟩, rw [s.strict_mono.le_iff_le, s.strict_mono.le_iff_le], exact le_total i j end /-- The ordered `list X` of elements of a `composition_series X`. -/ def to_list (s : composition_series X) : list X := list.of_fn s /-- Two `composition_series` are equal if they are the same length and have the same `i`th element for every `i` -/ lemma ext_fun {s₁ s₂ : composition_series X} (hl : s₁.length = s₂.length) (h : ∀ i, s₁ i = s₂ (fin.cast (congr_arg nat.succ hl) i)) : s₁ = s₂ := begin cases s₁, cases s₂, dsimp at *, subst hl, simpa [function.funext_iff] using h end @[simp] lemma length_to_list (s : composition_series X) : s.to_list.length = s.length + 1 := by rw [to_list, list.length_of_fn] lemma to_list_ne_nil (s : composition_series X) : s.to_list ≠ [] := by rw [← list.length_pos_iff_ne_nil, length_to_list]; exact nat.succ_pos _ lemma to_list_injective : function.injective (@composition_series.to_list X _ _) := λ s₁ s₂ (h : list.of_fn s₁ = list.of_fn s₂), have h₁ : s₁.length = s₂.length, from nat.succ_injective ((list.length_of_fn s₁).symm.trans $ (congr_arg list.length h).trans $ list.length_of_fn s₂), have h₂ : ∀ i : fin s₁.length.succ, (s₁ i) = s₂ (fin.cast (congr_arg nat.succ h₁) i), begin assume i, rw [← list.nth_le_of_fn s₁ i, ← list.nth_le_of_fn s₂], simp [h] end, begin cases s₁, cases s₂, dsimp at *, subst h₁, simp only [heq_iff_eq, eq_self_iff_true, true_and], simp only [fin.cast_refl] at h₂, exact funext h₂ end lemma chain'_to_list (s : composition_series X) : list.chain' is_maximal s.to_list := list.chain'_iff_nth_le.2 begin assume i hi, simp only [to_list, list.nth_le_of_fn'], rw [length_to_list] at hi, exact s.step ⟨i, hi⟩ end lemma to_list_sorted (s : composition_series X) : s.to_list.sorted (<) := list.pairwise_iff_nth_le.2 (λ i j hi hij, begin dsimp [to_list], rw [list.nth_le_of_fn', list.nth_le_of_fn'], exact s.strict_mono hij end) lemma to_list_nodup (s : composition_series X) : s.to_list.nodup := s.to_list_sorted.nodup @[simp] lemma mem_to_list {s : composition_series X} {x : X} : x ∈ s.to_list ↔ x ∈ s := by rw [to_list, list.mem_of_fn, mem_def] /-- Make a `composition_series X` from the ordered list of its elements. -/ def of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : composition_series X := { length := l.length - 1, series := λ i, l.nth_le i begin conv_rhs { rw ← tsub_add_cancel_of_le (nat.succ_le_of_lt (list.length_pos_of_ne_nil hl)) }, exact i.2 end, step' := λ ⟨i, hi⟩, list.chain'_iff_nth_le.1 hc i hi } lemma length_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : (of_list l hl hc).length = l.length - 1 := rfl lemma of_list_to_list (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := begin refine ext_fun _ _, { rw [length_of_list, length_to_list, nat.succ_sub_one] }, { rintros ⟨i, hi⟩, dsimp [of_list, to_list], rw [list.nth_le_of_fn'] } end @[simp] lemma of_list_to_list' (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := of_list_to_list s @[simp] lemma to_list_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : to_list (of_list l hl hc) = l := begin refine list.ext_le _ _, { rw [length_to_list, length_of_list, tsub_add_cancel_of_le (nat.succ_le_of_lt $ list.length_pos_of_ne_nil hl)] }, { assume i hi hi', dsimp [of_list, to_list], rw [list.nth_le_of_fn'], refl } end /-- Two `composition_series` are equal if they have the same elements. See also `ext_fun`. -/ @[ext] lemma ext {s₁ s₂ : composition_series X} (h : ∀ x, x ∈ s₁ ↔ x ∈ s₂) : s₁ = s₂ := to_list_injective $ list.eq_of_perm_of_sorted (by classical; exact list.perm_of_nodup_nodup_to_finset_eq s₁.to_list_nodup s₂.to_list_nodup (finset.ext $ by simp *)) s₁.to_list_sorted s₂.to_list_sorted /-- The largest element of a `composition_series` -/ def top (s : composition_series X) : X := s (fin.last _) lemma top_mem (s : composition_series X) : s.top ∈ s := mem_def.2 (set.mem_range.2 ⟨fin.last _, rfl⟩) @[simp] lemma le_top {s : composition_series X} (i : fin (s.length + 1)) : s i ≤ s.top := s.strict_mono.monotone (fin.le_last _) lemma le_top_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : x ≤ s.top := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ le_top _ /-- The smallest element of a `composition_series` -/ def bot (s : composition_series X) : X := s 0 lemma bot_mem (s : composition_series X) : s.bot ∈ s := mem_def.2 (set.mem_range.2 ⟨0, rfl⟩) @[simp] lemma bot_le {s : composition_series X} (i : fin (s.length + 1)) : s.bot ≤ s i := s.strict_mono.monotone (fin.zero_le _) lemma bot_le_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : s.bot ≤ x := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ bot_le _ lemma length_pos_of_mem_ne {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : 0 < s.length := let ⟨i, hi⟩ := hx, ⟨j, hj⟩ := hy in have hij : i ≠ j, from mt s.inj.2 $ λ h, hxy (hi ▸ hj ▸ h), hij.lt_or_lt.elim (λ hij, (lt_of_le_of_lt (zero_le i) (lt_of_lt_of_le hij (nat.le_of_lt_succ j.2)))) (λ hji, (lt_of_le_of_lt (zero_le j) (lt_of_lt_of_le hji (nat.le_of_lt_succ i.2)))) lemma forall_mem_eq_of_length_eq_zero {s : composition_series X} (hs : s.length = 0) {x y} (hx : x ∈ s) (hy : y ∈ s) : x = y := by_contradiction (λ hxy, pos_iff_ne_zero.1 (length_pos_of_mem_ne hx hy hxy) hs) /-- Remove the largest element from a `composition_series`. If the series `s` has length zero, then `s.erase_top = s` -/ @[simps] def erase_top (s : composition_series X) : composition_series X := { length := s.length - 1, series := λ i, s ⟨i, lt_of_lt_of_le i.2 (nat.succ_le_succ tsub_le_self)⟩, step' := λ i, begin have := s.step ⟨i, lt_of_lt_of_le i.2 tsub_le_self⟩, cases i, exact this end } lemma top_erase_top (s : composition_series X) : s.erase_top.top = s ⟨s.length - 1, lt_of_le_of_lt tsub_le_self (nat.lt_succ_self _)⟩ := show s _ = s _, from congr_arg s begin ext, simp only [erase_top_length, fin.coe_last, fin.coe_cast_succ, fin.coe_of_nat_eq_mod, fin.coe_mk, coe_coe] end lemma erase_top_top_le (s : composition_series X) : s.erase_top.top ≤ s.top := by simp [erase_top, top, s.strict_mono.le_iff_le, fin.le_iff_coe_le_coe, tsub_le_self] @[simp] lemma bot_erase_top (s : composition_series X) : s.erase_top.bot = s.bot := rfl lemma mem_erase_top_of_ne_of_mem {s : composition_series X} {x : X} (hx : x ≠ s.top) (hxs : x ∈ s) : x ∈ s.erase_top := begin rcases hxs with ⟨i, rfl⟩, have hi : (i : ℕ) < (s.length - 1).succ, { conv_rhs { rw [← nat.succ_sub (length_pos_of_mem_ne ⟨i, rfl⟩ s.top_mem hx), nat.succ_sub_one] }, exact lt_of_le_of_ne (nat.le_of_lt_succ i.2) (by simpa [top, s.inj, fin.ext_iff] using hx) }, refine ⟨i.cast_succ, _⟩, simp [fin.ext_iff, nat.mod_eq_of_lt hi] end lemma mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) : x ∈ s.erase_top ↔ x ≠ s.top ∧ x ∈ s := begin simp only [mem_def], dsimp only [erase_top, coe_fn_mk], split, { rintros ⟨i, rfl⟩, have hi : (i : ℕ) < s.length, { conv_rhs { rw [← nat.succ_sub_one s.length, nat.succ_sub h] }, exact i.2 }, simp [top, fin.ext_iff, (ne_of_lt hi)] }, { intro h, exact mem_erase_top_of_ne_of_mem h.1 h.2 } end lemma lt_top_of_mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) (hx : x ∈ s.erase_top) : x < s.top := lt_of_le_of_ne (le_top_of_mem ((mem_erase_top h).1 hx).2) ((mem_erase_top h).1 hx).1 lemma is_maximal_erase_top_top {s : composition_series X} (h : 0 < s.length) : is_maximal s.erase_top.top s.top := have s.length - 1 + 1 = s.length, by conv_rhs { rw [← nat.succ_sub_one s.length] }; rw nat.succ_sub h, begin rw [top_erase_top, top], convert s.step ⟨s.length - 1, nat.sub_lt h zero_lt_one⟩; ext; simp [this] end section fin_lemmas -- TODO: move these to `vec_notation` and rename them to better describe their statement variables {α : Type*} {m n : ℕ} (a : fin m.succ → α) (b : fin n.succ → α) lemma append_cast_add_aux (i : fin m) : matrix.vec_append (nat.add_succ _ _).symm (a ∘ fin.cast_succ) b (fin.cast_add n i).cast_succ = a i.cast_succ := by { cases i, simp [matrix.vec_append_eq_ite, *] } lemma append_succ_cast_add_aux (i : fin m) (h : a (fin.last _) = b 0) : matrix.vec_append (nat.add_succ _ _).symm (a ∘ fin.cast_succ) b (fin.cast_add n i).succ = a i.succ := begin cases i with i hi, simp only [matrix.vec_append_eq_ite, hi, fin.succ_mk, function.comp_app, fin.cast_succ_mk, fin.coe_mk, fin.cast_add_mk], split_ifs, { refl }, { have : i + 1 = m, from le_antisymm hi (le_of_not_gt h_1), calc b ⟨i + 1 - m, by simp [this]⟩ = b 0 : congr_arg b (by simp [fin.ext_iff, this]) ... = a (fin.last _) : h.symm ... = _ : congr_arg a (by simp [fin.ext_iff, this]) } end lemma append_nat_add_aux (i : fin n) : matrix.vec_append (nat.add_succ _ _).symm (a ∘ fin.cast_succ) b (fin.nat_add m i).cast_succ = b i.cast_succ := begin cases i, simp only [matrix.vec_append_eq_ite, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, add_tsub_cancel_left, dif_neg, fin.cast_succ_mk, not_false_iff, fin.coe_mk] end lemma append_succ_nat_add_aux (i : fin n) : matrix.vec_append (nat.add_succ _ _).symm (a ∘ fin.cast_succ) b (fin.nat_add m i).succ = b i.succ := begin cases i with i hi, simp only [matrix.vec_append_eq_ite, add_assoc, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, add_tsub_cancel_left, fin.succ_mk, dif_neg, not_false_iff, fin.coe_mk] end end fin_lemmas /-- Append two composition series `s₁` and `s₂` such that the least element of `s₁` is the maximum element of `s₂`. -/ @[simps length] def append (s₁ s₂ : composition_series X) (h : s₁.top = s₂.bot) : composition_series X := { length := s₁.length + s₂.length, series := matrix.vec_append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂, step' := λ i, begin refine fin.add_cases _ _ i, { intro i, rw [append_succ_cast_add_aux _ _ _ h, append_cast_add_aux], exact s₁.step i }, { intro i, rw [append_nat_add_aux, append_succ_nat_add_aux], exact s₂.step i } end } lemma coe_append (s₁ s₂ : composition_series X) (h) : ⇑(s₁.append s₂ h) = matrix.vec_append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ := rfl @[simp] lemma append_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := by rw [coe_append, append_cast_add_aux _ _ i] @[simp] lemma append_succ_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).succ = s₁ i.succ := by rw [coe_append, append_succ_cast_add_aux _ _ _ h] @[simp] lemma append_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := by rw [coe_append, append_nat_add_aux _ _ i] @[simp] lemma append_succ_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).succ = s₂ i.succ := by rw [coe_append, append_succ_nat_add_aux _ _ i] /-- Add an element to the top of a `composition_series` -/ @[simps length] def snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : composition_series X := { length := s.length + 1, series := fin.snoc s x, step' := λ i, begin refine fin.last_cases _ _ i, { rwa [fin.snoc_cast_succ, fin.succ_last, fin.snoc_last, ← top] }, { intro i, rw [fin.snoc_cast_succ, ← fin.cast_succ_fin_succ, fin.snoc_cast_succ], exact s.step _ } end } @[simp] lemma top_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).top = x := fin.snoc_last _ _ @[simp] lemma snoc_last (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : snoc s x hsat (fin.last (s.length + 1)) = x := fin.snoc_last _ _ @[simp] lemma snoc_cast_succ (s : composition_series X) (x : X) (hsat : is_maximal s.top x) (i : fin (s.length + 1)) : snoc s x hsat (i.cast_succ) = s i := fin.snoc_cast_succ _ _ _ @[simp] lemma bot_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).bot = s.bot := by rw [bot, bot, ← snoc_cast_succ s _ _ 0, fin.cast_succ_zero] lemma mem_snoc {s : composition_series X} {x y: X} {hsat : is_maximal s.top x} : y ∈ snoc s x hsat ↔ y ∈ s ∨ y = x := begin simp only [snoc, mem_def], split, { rintros ⟨i, rfl⟩, refine fin.last_cases _ (λ i, _) i, { right, simp }, { left, simp } }, { intro h, rcases h with ⟨i, rfl⟩ | rfl, { use i.cast_succ, simp }, { use (fin.last _), simp } } end lemma eq_snoc_erase_top {s : composition_series X} (h : 0 < s.length) : s = snoc (erase_top s) s.top (is_maximal_erase_top_top h) := begin ext x, simp [mem_snoc, mem_erase_top h], by_cases h : x = s.top; simp [*, s.top_mem] end @[simp] lemma snoc_erase_top_top {s : composition_series X} (h : is_maximal s.erase_top.top s.top) : s.erase_top.snoc s.top h = s := have h : 0 < s.length, from nat.pos_of_ne_zero begin assume hs, refine ne_of_gt (lt_of_is_maximal h) _, simp [top, fin.ext_iff, hs] end, (eq_snoc_erase_top h).symm /-- Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i) (s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` -/ def equivalent (s₁ s₂ : composition_series X) : Prop := ∃ f : fin s₁.length ≃ fin s₂.length, ∀ i : fin s₁.length, iso (s₁ i.cast_succ, s₁ i.succ) (s₂ (f i).cast_succ, s₂ (f i).succ) namespace equivalent @[refl] lemma refl (s : composition_series X) : equivalent s s := ⟨equiv.refl _, λ _, (s.step _).iso_refl⟩ @[symm] lemma symm {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : equivalent s₂ s₁ := ⟨h.some.symm, λ i, iso_symm (by simpa using h.some_spec (h.some.symm i))⟩ @[trans] lemma trans {s₁ s₂ s₃ : composition_series X} (h₁ : equivalent s₁ s₂) (h₂ : equivalent s₂ s₃) : equivalent s₁ s₃ := ⟨h₁.some.trans h₂.some, λ i, iso_trans (h₁.some_spec i) (h₂.some_spec (h₁.some i))⟩ lemma append {s₁ s₂ t₁ t₂ : composition_series X} (hs : s₁.top = s₂.bot) (ht : t₁.top = t₂.bot) (h₁ : equivalent s₁ t₁) (h₂ : equivalent s₂ t₂) : equivalent (append s₁ s₂ hs) (append t₁ t₂ ht) := let e : fin (s₁.length + s₂.length) ≃ fin (t₁.length + t₂.length) := calc fin (s₁.length + s₂.length) ≃ fin s₁.length ⊕ fin s₂.length : fin_sum_fin_equiv.symm ... ≃ fin t₁.length ⊕ fin t₂.length : equiv.sum_congr h₁.some h₂.some ... ≃ fin (t₁.length + t₂.length) : fin_sum_fin_equiv in ⟨e, begin assume i, refine fin.add_cases _ _ i, { assume i, simpa [top, bot] using h₁.some_spec i }, { assume i, simpa [top, bot] using h₂.some_spec i } end⟩ protected lemma snoc {s₁ s₂ : composition_series X} {x₁ x₂ : X} {hsat₁ : is_maximal s₁.top x₁} {hsat₂ : is_maximal s₂.top x₂} (hequiv : equivalent s₁ s₂) (htop : iso (s₁.top, x₁) (s₂.top, x₂)) : equivalent (s₁.snoc x₁ hsat₁) (s₂.snoc x₂ hsat₂) := let e : fin s₁.length.succ ≃ fin s₂.length.succ := calc fin (s₁.length + 1) ≃ option (fin s₁.length) : fin_succ_equiv_last ... ≃ option (fin s₂.length) : functor.map_equiv option hequiv.some ... ≃ fin (s₂.length + 1) : fin_succ_equiv_last.symm in ⟨e, λ i, begin refine fin.last_cases _ _ i, { simpa [top] using htop }, { assume i, simpa [fin.succ_cast_succ] using hequiv.some_spec i } end⟩ lemma length_eq {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : s₁.length = s₂.length := by simpa using fintype.card_congr h.some lemma snoc_snoc_swap {s : composition_series X} {x₁ x₂ y₁ y₂ : X} {hsat₁ : is_maximal s.top x₁} {hsat₂ : is_maximal s.top x₂} {hsaty₁ : is_maximal (snoc s x₁ hsat₁).top y₁} {hsaty₂ : is_maximal (snoc s x₂ hsat₂).top y₂} (hr₁ : iso (s.top, x₁) (x₂, y₂)) (hr₂ : iso (x₁, y₁) (s.top, x₂)) : equivalent (snoc (snoc s x₁ hsat₁) y₁ hsaty₁) (snoc (snoc s x₂ hsat₂) y₂ hsaty₂) := let e : fin (s.length + 1 + 1) ≃ fin (s.length + 1 + 1) := equiv.swap (fin.last _) (fin.cast_succ (fin.last _)) in have h1 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _).cast_succ, from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), have h2 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _), from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), ⟨e, begin intro i, dsimp only [e], refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_left, snoc_cast_succ, snoc_last, fin.succ_last, snoc_last, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last], exact hr₂ }, { refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_right, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last, snoc_last, fin.succ_last, snoc_last], exact hr₁ }, { erw [equiv.swap_apply_of_ne_of_ne h2 h1, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ], exact (s.step i).iso_refl } } end⟩ end equivalent lemma length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁ : s₁.length = 0) : s₂.length = 0 := begin have : s₁.bot = s₁.top, from congr_arg s₁ (fin.ext (by simp [hs₁])), have : (fin.last s₂.length) = (0 : fin s₂.length.succ), from s₂.injective (hb.symm.trans (this.trans ht)).symm, simpa [fin.ext_iff] end lemma length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : 0 < s₁.length → 0 < s₂.length := not_imp_not.1 begin simp only [pos_iff_ne_zero, ne.def, not_iff_not, not_not], exact length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb.symm ht.symm end lemma eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁0 : s₁.length = 0) : s₁ = s₂ := have ∀ x, x ∈ s₁ ↔ x = s₁.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero hs₁0 hx s₁.top_mem, λ hx, hx.symm ▸ s₁.top_mem⟩, have ∀ x, x ∈ s₂ ↔ x = s₂.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero (length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hs₁0) hx s₂.top_mem, λ hx, hx.symm ▸ s₂.top_mem⟩, by { ext, simp * } /-- Given a `composition_series`, `s`, and an element `x` such that `x` is maximal inside `s.top` there is a series, `t`, such that `t.top = x`, `t.bot = s.bot` and `snoc t s.top _` is equivalent to `s`. -/ lemma exists_top_eq_snoc_equivalant (s : composition_series X) (x : X) (hm : is_maximal x s.top) (hb : s.bot ≤ x) : ∃ t : composition_series X, t.bot = s.bot ∧ t.length + 1 = s.length ∧ ∃ htx : t.top = x, equivalent s (snoc t s.top (htx.symm ▸ hm)) := begin induction hn : s.length with n ih generalizing s x, { exact (ne_of_gt (lt_of_le_of_lt hb (lt_of_is_maximal hm)) (forall_mem_eq_of_length_eq_zero hn s.top_mem s.bot_mem)).elim }, { have h0s : 0 < s.length, from hn.symm ▸ nat.succ_pos _, by_cases hetx : s.erase_top.top = x, { use s.erase_top, simp [← hetx, hn] }, { have imxs : is_maximal (x ⊓ s.erase_top.top) s.erase_top.top, from is_maximal_of_eq_inf x s.top rfl (ne.symm hetx) hm (is_maximal_erase_top_top h0s), have := ih _ _ imxs (le_inf (by simpa) (le_top_of_mem s.erase_top.bot_mem)) (by simp [hn]), rcases this with ⟨t, htb, htl, htt, hteqv⟩, have hmtx : is_maximal t.top x, from is_maximal_of_eq_inf s.erase_top.top s.top (by rw [inf_comm, htt]) hetx (is_maximal_erase_top_top h0s) hm, use snoc t x hmtx, refine ⟨by simp [htb], by simp [htl], by simp, _⟩, have : s.equivalent ((snoc t s.erase_top.top (htt.symm ▸ imxs)).snoc s.top (by simpa using is_maximal_erase_top_top h0s)), { conv_lhs { rw eq_snoc_erase_top h0s }, exact equivalent.snoc hteqv (by simpa using (is_maximal_erase_top_top h0s).iso_refl) }, refine this.trans _, refine equivalent.snoc_snoc_swap _ _, { exact iso_symm (second_iso_of_eq hm (sup_eq_of_is_maximal hm (is_maximal_erase_top_top h0s) (ne.symm hetx)) htt.symm) }, { exact second_iso_of_eq (is_maximal_erase_top_top h0s) (sup_eq_of_is_maximal (is_maximal_erase_top_top h0s) hm hetx) (by rw [inf_comm, htt]) } } } end /-- The **Jordan-Hölder** theorem, stated for any `jordan_holder_lattice`. If two composition series start and finish at the same place, they are equivalent. -/ theorem jordan_holder (s₁ s₂ : composition_series X) (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : equivalent s₁ s₂ := begin induction hle : s₁.length with n ih generalizing s₁ s₂, { rw [eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hle] }, { have h0s₂ : 0 < s₂.length, from length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos hb ht (hle.symm ▸ nat.succ_pos _), rcases exists_top_eq_snoc_equivalant s₁ s₂.erase_top.top (ht.symm ▸ is_maximal_erase_top_top h0s₂) (hb.symm ▸ s₂.bot_erase_top ▸ bot_le_of_mem (top_mem _)) with ⟨t, htb, htl, htt, hteq⟩, have := ih t s₂.erase_top (by simp [htb, ← hb]) htt (nat.succ_inj'.1 (htl.trans hle)), refine hteq.trans _, conv_rhs { rw [eq_snoc_erase_top h0s₂] }, simp only [ht], exact equivalent.snoc this (by simp [htt, (is_maximal_erase_top_top h0s₂).iso_refl]) } end end composition_series
bcd8c6ba0414a69f7f19cc07ed7d5f1fc7f4227b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/reduce1.lean
ec7131a38cd9d70b7dfc475fd1e5378972838251
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,288
lean
partial def fact : Nat → Nat | 0 => 1 | (n+1) => (n+1)*fact n #eval fact 10 #eval fact 100 theorem tst1 : fact 10 = 3628800 := by native_decide theorem tst2 : fact 100 = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 := by native_decide theorem tst3 : decide (10000000000000000 < 200000000000000000000) = true := by native_decide theorem tst4 : 10000000000000000 < 200000000000000000000 := by decide theorem tst5 : 10000000000000000 < 200000000000000000000 := by native_decide theorem tst6 : 10000000000000000 < 200000000000000000000 := let h₁ : 10000000000000000 < 10000000000000010 := by native_decide let h₂ : 10000000000000010 < 200000000000000000000 := by native_decide Nat.lt_trans h₁ h₂ theorem tst7 : 10000000000000000 < 200000000000000000000 := by decide theorem tst8 : 10000000000000000 < 200000000000000000000 := let h₁ : 10000000000000000 < 10000000000000010 := by decide let h₂ : 10000000000000010 < 200000000000000000000 := by decide Nat.lt_trans h₁ h₂ theorem tst9 : 10000000000000000 < 200000000000000000000 := by decide theorem tst10 : 10000000000000000 < 200000000000000000000 := by native_decide
6b91971af045ddbd51dce6dc42fc7cd319efbfe8
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/decomposition/signed_hahn.lean
25a9760d1e74570d1ce83da5b98b2a2c5e0942ca
[ "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
21,616
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.measure.vector_measure import order.symm_diff /-! # Hahn decomposition This file proves the Hahn decomposition theorem (signed version). The Hahn decomposition theorem states that, given a signed measure `s`, there exist complementary, measurable sets `i` and `j`, such that `i` is positive and `j` is negative with respect to `s`; that is, `s` restricted on `i` is non-negative and `s` restricted on `j` is non-positive. The Hahn decomposition theorem leads to many other results in measure theory, most notably, the Jordan decomposition theorem, the Lebesgue decomposition theorem and the Radon-Nikodym theorem. ## Main results * `measure_theory.signed_measure.exists_is_compl_positive_negative` : the Hahn decomposition theorem. * `measure_theory.signed_measure.exists_subset_restrict_nonpos` : A measurable set of negative measure contains a negative subset. ## Notation We use the notations `0 ≤[i] s` and `s ≤[i] 0` to denote the usual definitions of a set `i` being positive/negative with respect to the signed measure `s`. ## Tags Hahn decomposition theorem -/ noncomputable theory open_locale classical big_operators nnreal ennreal measure_theory variables {α β : Type*} [measurable_space α] variables {M : Type*} [add_comm_monoid M] [topological_space M] [ordered_add_comm_monoid M] namespace measure_theory namespace signed_measure open filter vector_measure variables {s : signed_measure α} {i j : set α} section exists_subset_restrict_nonpos /-! ### exists_subset_restrict_nonpos In this section we will prove that a set `i` whose measure is negative contains a negative subset `j` with respect to the signed measure `s` (i.e. `s ≤[j] 0`), whose measure is negative. This lemma is used to prove the Hahn decomposition theorem. To prove this lemma, we will construct a sequence of measurable sets $(A_n)_{n \in \mathbb{N}}$, such that, for all $n$, $s(A_{n + 1})$ is close to maximal among subsets of $i \setminus \bigcup_{k \le n} A_k$. This sequence of sets does not necessarily exist. However, if this sequence terminates; that is, there does not exists any sets satisfying the property, the last $A_n$ will be a negative subset of negative measure, hence proving our claim. In the case that the sequence does not terminate, it is easy to see that $i \setminus \bigcup_{k = 0}^\infty A_k$ is the required negative set. To implement this in Lean, we define several auxilary definitions. - given the sets `i` and the natural number `n`, `exists_one_div_lt s i n` is the property that there exists a measurable set `k ⊆ i` such that `1 / (n + 1) < s k`. - given the sets `i` and that `i` is not negative, `find_exists_one_div_lt s i` is the least natural number `n` such that `exists_one_div_lt s i n`. - given the sets `i` and that `i` is not negative, `some_exists_one_div_lt` chooses the set `k` from `exists_one_div_lt s i (find_exists_one_div_lt s i)`. - lastly, given the set `i`, `restrict_nonpos_seq s i` is the sequence of sets defined inductively where `restrict_nonpos_seq s i 0 = some_exists_one_div_lt s (i \ ∅)` and `restrict_nonpos_seq s i (n + 1) = some_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq k)`. This definition represents the sequence $(A_n)$ in the proof as described above. With these definitions, we are able consider the case where the sequence terminates separately, allowing us to prove `exists_subset_restrict_nonpos`. -/ /-- Given the set `i` and the natural number `n`, `exists_one_div_lt s i j` is the property that there exists a measurable set `k ⊆ i` such that `1 / (n + 1) < s k`. -/ private def exists_one_div_lt (s : signed_measure α) (i : set α) (n : ℕ) : Prop := ∃ k : set α, k ⊆ i ∧ measurable_set k ∧ (1 / (n + 1) : ℝ) < s k private lemma exists_nat_one_div_lt_measure_of_not_negative (hi : ¬ s ≤[i] 0) : ∃ (n : ℕ), exists_one_div_lt s i n := let ⟨k, hj₁, hj₂, hj⟩ := exists_pos_measure_of_not_restrict_le_zero s hi in let ⟨n, hn⟩ := exists_nat_one_div_lt hj in ⟨n, k, hj₂, hj₁, hn⟩ /-- Given the set `i`, if `i` is not negative, `find_exists_one_div_lt s i` is the least natural number `n` such that `exists_one_div_lt s i n`, otherwise, it returns 0. -/ private def find_exists_one_div_lt (s : signed_measure α) (i : set α) : ℕ := if hi : ¬ s ≤[i] 0 then nat.find (exists_nat_one_div_lt_measure_of_not_negative hi) else 0 private lemma find_exists_one_div_lt_spec (hi : ¬ s ≤[i] 0) : exists_one_div_lt s i (find_exists_one_div_lt s i) := begin rw [find_exists_one_div_lt, dif_pos hi], convert nat.find_spec _, end private lemma find_exists_one_div_lt_min (hi : ¬ s ≤[i] 0) {m : ℕ} (hm : m < find_exists_one_div_lt s i) : ¬ exists_one_div_lt s i m := begin rw [find_exists_one_div_lt, dif_pos hi] at hm, exact nat.find_min _ hm end /-- Given the set `i`, if `i` is not negative, `some_exists_one_div_lt` chooses the set `k` from `exists_one_div_lt s i (find_exists_one_div_lt s i)`, otherwise, it returns the empty set. -/ private def some_exists_one_div_lt (s : signed_measure α) (i : set α) : set α := if hi : ¬ s ≤[i] 0 then classical.some (find_exists_one_div_lt_spec hi) else ∅ private lemma some_exists_one_div_lt_spec (hi : ¬ s ≤[i] 0) : (some_exists_one_div_lt s i) ⊆ i ∧ measurable_set (some_exists_one_div_lt s i) ∧ (1 / (find_exists_one_div_lt s i + 1) : ℝ) < s (some_exists_one_div_lt s i) := begin rw [some_exists_one_div_lt, dif_pos hi], exact classical.some_spec (find_exists_one_div_lt_spec hi), end private lemma some_exists_one_div_lt_subset : some_exists_one_div_lt s i ⊆ i := begin by_cases hi : ¬ s ≤[i] 0, { exact let ⟨h, _⟩ := some_exists_one_div_lt_spec hi in h }, { rw [some_exists_one_div_lt, dif_neg hi], exact set.empty_subset _ }, end private lemma some_exists_one_div_lt_subset' : some_exists_one_div_lt s (i \ j) ⊆ i := set.subset.trans some_exists_one_div_lt_subset (set.diff_subset _ _) private lemma some_exists_one_div_lt_measurable_set : measurable_set (some_exists_one_div_lt s i) := begin by_cases hi : ¬ s ≤[i] 0, { exact let ⟨_, h, _⟩ := some_exists_one_div_lt_spec hi in h }, { rw [some_exists_one_div_lt, dif_neg hi], exact measurable_set.empty } end private lemma some_exists_one_div_lt_lt (hi : ¬ s ≤[i] 0) : (1 / (find_exists_one_div_lt s i + 1) : ℝ) < s (some_exists_one_div_lt s i) := let ⟨_, _, h⟩ := some_exists_one_div_lt_spec hi in h /-- Given the set `i`, `restrict_nonpos_seq s i` is the sequence of sets defined inductively where `restrict_nonpos_seq s i 0 = some_exists_one_div_lt s (i \ ∅)` and `restrict_nonpos_seq s i (n + 1) = some_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq k)`. For each `n : ℕ`,`s (restrict_nonpos_seq s i n)` is close to maximal among all subsets of `i \ ⋃ k ≤ n, restrict_nonpos_seq s i k`. -/ private def restrict_nonpos_seq (s : signed_measure α) (i : set α) : ℕ → set α | 0 := some_exists_one_div_lt s (i \ ∅) -- I used `i \ ∅` instead of `i` to simplify some proofs | (n + 1) := some_exists_one_div_lt s (i \ ⋃ k ≤ n, have k < n + 1 := nat.lt_succ_iff.mpr H, restrict_nonpos_seq k) private lemma restrict_nonpos_seq_succ (n : ℕ) : restrict_nonpos_seq s i n.succ = some_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq s i k) := by rw restrict_nonpos_seq private lemma restrict_nonpos_seq_subset (n : ℕ) : restrict_nonpos_seq s i n ⊆ i := begin cases n; { rw restrict_nonpos_seq, exact some_exists_one_div_lt_subset' } end private lemma restrict_nonpos_seq_lt (n : ℕ) (hn : ¬ s ≤[i \ ⋃ k ≤ n, restrict_nonpos_seq s i k] 0) : (1 / (find_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq s i k) + 1) : ℝ) < s (restrict_nonpos_seq s i n.succ) := begin rw restrict_nonpos_seq_succ, apply some_exists_one_div_lt_lt hn, end private lemma measure_of_restrict_nonpos_seq (hi₂ : ¬ s ≤[i] 0) (n : ℕ) (hn : ¬ s ≤[i \ ⋃ k < n, restrict_nonpos_seq s i k] 0) : 0 < s (restrict_nonpos_seq s i n) := begin cases n, { rw restrict_nonpos_seq, rw ← @set.diff_empty _ i at hi₂, rcases some_exists_one_div_lt_spec hi₂ with ⟨_, _, h⟩, exact (lt_trans nat.one_div_pos_of_nat h) }, { rw restrict_nonpos_seq_succ, have h₁ : ¬ s ≤[i \ ⋃ (k : ℕ) (H : k ≤ n), restrict_nonpos_seq s i k] 0, { refine mt (restrict_le_zero_subset _ _ (by simp [nat.lt_succ_iff])) hn, convert measurable_of_not_restrict_le_zero _ hn, exact funext (λ x, by rw nat.lt_succ_iff) }, rcases some_exists_one_div_lt_spec h₁ with ⟨_, _, h⟩, exact (lt_trans nat.one_div_pos_of_nat h) } end private lemma restrict_nonpos_seq_measurable_set (n : ℕ) : measurable_set (restrict_nonpos_seq s i n) := begin cases n; { rw restrict_nonpos_seq, exact some_exists_one_div_lt_measurable_set }, end private lemma restrict_nonpos_seq_disjoint' {n m : ℕ} (h : n < m) : restrict_nonpos_seq s i n ∩ restrict_nonpos_seq s i m = ∅ := begin rw set.eq_empty_iff_forall_not_mem, rintro x ⟨hx₁, hx₂⟩, cases m, { linarith }, { rw restrict_nonpos_seq at hx₂, exact (some_exists_one_div_lt_subset hx₂).2 (set.mem_Union.2 ⟨n, set.mem_Union.2 ⟨nat.lt_succ_iff.mp h, hx₁⟩⟩) } end private lemma restrict_nonpos_seq_disjoint : pairwise (disjoint on (restrict_nonpos_seq s i)) := begin intros n m h, rw [function.on_fun, set.disjoint_iff_inter_eq_empty], rcases lt_or_gt_of_ne h with (h | h), { rw [restrict_nonpos_seq_disjoint' h] }, { rw [set.inter_comm, restrict_nonpos_seq_disjoint' h] } end private lemma exists_subset_restrict_nonpos' (hi₁ : measurable_set i) (hi₂ : s i < 0) (hn : ¬ ∀ n : ℕ, ¬ s ≤[i \ ⋃ l < n, restrict_nonpos_seq s i l] 0) : ∃ j : set α, measurable_set j ∧ j ⊆ i ∧ s ≤[j] 0 ∧ s j < 0 := begin by_cases s ≤[i] 0, { exact ⟨i, hi₁, set.subset.refl _, h, hi₂⟩ }, push_neg at hn, set k := nat.find hn with hk₁, have hk₂ : s ≤[i \ ⋃ l < k, restrict_nonpos_seq s i l] 0 := nat.find_spec hn, have hmeas : measurable_set (⋃ (l : ℕ) (H : l < k), restrict_nonpos_seq s i l) := (measurable_set.Union $ λ _, measurable_set.Union (λ _, restrict_nonpos_seq_measurable_set _)), refine ⟨i \ ⋃ l < k, restrict_nonpos_seq s i l, hi₁.diff hmeas, set.diff_subset _ _, hk₂, _⟩, rw [of_diff hmeas hi₁, s.of_disjoint_Union_nat], { have h₁ : ∀ l < k, 0 ≤ s (restrict_nonpos_seq s i l), { intros l hl, refine le_of_lt (measure_of_restrict_nonpos_seq h _ _), refine mt (restrict_le_zero_subset _ (hi₁.diff _) (set.subset.refl _)) (nat.find_min hn hl), exact (measurable_set.Union $ λ _, measurable_set.Union (λ _, restrict_nonpos_seq_measurable_set _)) }, suffices : 0 ≤ ∑' (l : ℕ), s (⋃ (H : l < k), restrict_nonpos_seq s i l), { rw sub_neg, exact lt_of_lt_of_le hi₂ this }, refine tsum_nonneg _, intro l, by_cases l < k, { convert h₁ _ h, ext x, rw [set.mem_Union, exists_prop, and_iff_right_iff_imp], exact λ _, h }, { convert le_of_eq s.empty.symm, ext, simp only [exists_prop, set.mem_empty_iff_false, set.mem_Union, not_and, iff_false], exact λ h', false.elim (h h') } }, { intro, exact measurable_set.Union (λ _, restrict_nonpos_seq_measurable_set _) }, { intros a b hab, refine set.disjoint_Union_left.mpr (λ ha, _), refine set.disjoint_Union_right.mpr (λ hb, _), exact restrict_nonpos_seq_disjoint hab }, { apply set.Union_subset, intros a x, simp only [and_imp, exists_prop, set.mem_Union], intros _ hx, exact restrict_nonpos_seq_subset _ hx }, { apply_instance } end /-- A measurable set of negative measure has a negative subset of negative measure. -/ theorem exists_subset_restrict_nonpos (hi : s i < 0) : ∃ j : set α, measurable_set j ∧ j ⊆ i ∧ s ≤[j] 0 ∧ s j < 0 := begin have hi₁ : measurable_set i := classical.by_contradiction (λ h, ne_of_lt hi $ s.not_measurable h), by_cases s ≤[i] 0, { exact ⟨i, hi₁, set.subset.refl _, h, hi⟩ }, by_cases hn : ∀ n : ℕ, ¬ s ≤[i \ ⋃ l < n, restrict_nonpos_seq s i l] 0, swap, { exact exists_subset_restrict_nonpos' hi₁ hi hn }, set A := i \ ⋃ l, restrict_nonpos_seq s i l with hA, set bdd : ℕ → ℕ := λ n, find_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq s i k) with hbdd, have hn' : ∀ n : ℕ, ¬ s ≤[i \ ⋃ l ≤ n, restrict_nonpos_seq s i l] 0, { intro n, convert hn (n + 1); { ext l, simp only [exists_prop, set.mem_Union, and.congr_left_iff], exact λ _, nat.lt_succ_iff.symm } }, have h₁ : s i = s A + ∑' l, s (restrict_nonpos_seq s i l), { rw [hA, ← s.of_disjoint_Union_nat, add_comm, of_add_of_diff], exact measurable_set.Union (λ _, restrict_nonpos_seq_measurable_set _), exacts [hi₁, set.Union_subset (λ _, restrict_nonpos_seq_subset _), λ _, restrict_nonpos_seq_measurable_set _, restrict_nonpos_seq_disjoint] }, have h₂ : s A ≤ s i, { rw h₁, apply le_add_of_nonneg_right, exact tsum_nonneg (λ n, le_of_lt (measure_of_restrict_nonpos_seq h _ (hn n))) }, have h₃' : summable (λ n, (1 / (bdd n + 1) : ℝ)), { have : summable (λ l, s (restrict_nonpos_seq s i l)) := has_sum.summable (s.m_Union (λ _, restrict_nonpos_seq_measurable_set _) restrict_nonpos_seq_disjoint), refine summable_of_nonneg_of_le (λ n, _) (λ n, _) (summable.comp_injective this nat.succ_injective), { exact le_of_lt nat.one_div_pos_of_nat }, { exact le_of_lt (restrict_nonpos_seq_lt n (hn' n)) } }, have h₃ : tendsto (λ n, (bdd n : ℝ) + 1) at_top at_top, { simp only [one_div] at h₃', exact summable.tendsto_top_of_pos h₃' (λ n, nat.cast_add_one_pos (bdd n)) }, have h₄ : tendsto (λ n, (bdd n : ℝ)) at_top at_top, { convert at_top.tendsto_at_top_add_const_right (-1) h₃, simp }, have A_meas : measurable_set A := hi₁.diff (measurable_set.Union (λ _, restrict_nonpos_seq_measurable_set _)), refine ⟨A, A_meas, set.diff_subset _ _, _, h₂.trans_lt hi⟩, by_contra hnn, rw restrict_le_restrict_iff _ _ A_meas at hnn, push_neg at hnn, obtain ⟨E, hE₁, hE₂, hE₃⟩ := hnn, have : ∃ k, 1 ≤ bdd k ∧ 1 / (bdd k : ℝ) < s E, { rw tendsto_at_top_at_top at h₄, obtain ⟨k, hk⟩ := h₄ (max (1 / s E + 1) 1), refine ⟨k, _, _⟩, { have hle := le_of_max_le_right (hk k le_rfl), norm_cast at hle, exact hle }, { have : 1 / s E < bdd k, { linarith [le_of_max_le_left (hk k le_rfl)] {restrict_type := ℝ} }, rw one_div at this ⊢, rwa inv_lt (lt_trans (inv_pos.2 hE₃) this) hE₃ } }, obtain ⟨k, hk₁, hk₂⟩ := this, have hA' : A ⊆ i \ ⋃ l ≤ k, restrict_nonpos_seq s i l, { apply set.diff_subset_diff_right, intro x, simp only [set.mem_Union], rintro ⟨n, _, hn₂⟩, exact ⟨n, hn₂⟩ }, refine find_exists_one_div_lt_min (hn' k) (buffer.lt_aux_2 hk₁) ⟨E, set.subset.trans hE₂ hA', hE₁, _⟩, convert hk₂, norm_cast, exact tsub_add_cancel_of_le hk₁ end end exists_subset_restrict_nonpos /-- The set of measures of the set of measurable negative sets. -/ def measure_of_negatives (s : signed_measure α) : set ℝ := s '' { B | measurable_set B ∧ s ≤[B] 0 } lemma zero_mem_measure_of_negatives : (0 : ℝ) ∈ s.measure_of_negatives := ⟨∅, ⟨measurable_set.empty, le_restrict_empty _ _⟩, s.empty⟩ lemma bdd_below_measure_of_negatives : bdd_below s.measure_of_negatives := begin simp_rw [bdd_below, set.nonempty, mem_lower_bounds], by_contra' h, have h' : ∀ n : ℕ, ∃ y : ℝ, y ∈ s.measure_of_negatives ∧ y < -n := λ n, h (-n), choose f hf using h', have hf' : ∀ n : ℕ, ∃ B, measurable_set B ∧ s ≤[B] 0 ∧ s B < -n, { intro n, rcases hf n with ⟨⟨B, ⟨hB₁, hBr⟩, hB₂⟩, hlt⟩, exact ⟨B, hB₁, hBr, hB₂.symm ▸ hlt⟩ }, choose B hmeas hr h_lt using hf', set A := ⋃ n, B n with hA, have hfalse : ∀ n : ℕ, s A ≤ -n, { intro n, refine le_trans _ (le_of_lt (h_lt _)), rw [hA, ← set.diff_union_of_subset (set.subset_Union _ n), of_union set.disjoint_sdiff_left _ (hmeas n)], { refine add_le_of_nonpos_left _, have : s ≤[A] 0 := restrict_le_restrict_Union _ _ hmeas hr, refine nonpos_of_restrict_le_zero _ (restrict_le_zero_subset _ _ (set.diff_subset _ _) this), exact measurable_set.Union hmeas }, { apply_instance }, { exact (measurable_set.Union hmeas).diff (hmeas n) } }, rcases exists_nat_gt (-(s A)) with ⟨n, hn⟩, exact lt_irrefl _ ((neg_lt.1 hn).trans_le (hfalse n)), end /-- Alternative formulation of `measure_theory.signed_measure.exists_is_compl_positive_negative` (the Hahn decomposition theorem) using set complements. -/ lemma exists_compl_positive_negative (s : signed_measure α) : ∃ i : set α, measurable_set i ∧ 0 ≤[i] s ∧ s ≤[iᶜ] 0 := begin obtain ⟨f, _, hf₂, hf₁⟩ := exists_seq_tendsto_Inf ⟨0, @zero_mem_measure_of_negatives _ _ s⟩ bdd_below_measure_of_negatives, choose B hB using hf₁, have hB₁ : ∀ n, measurable_set (B n) := λ n, (hB n).1.1, have hB₂ : ∀ n, s ≤[B n] 0 := λ n, (hB n).1.2, set A := ⋃ n, B n with hA, have hA₁ : measurable_set A := measurable_set.Union hB₁, have hA₂ : s ≤[A] 0 := restrict_le_restrict_Union _ _ hB₁ hB₂, have hA₃ : s A = Inf s.measure_of_negatives, { apply le_antisymm, { refine le_of_tendsto_of_tendsto tendsto_const_nhds hf₂ (eventually_of_forall (λ n, _)), rw [← (hB n).2, hA, ← set.diff_union_of_subset (set.subset_Union _ n), of_union set.disjoint_sdiff_left _ (hB₁ n)], { refine add_le_of_nonpos_left _, have : s ≤[A] 0 := restrict_le_restrict_Union _ _ hB₁ (λ m, let ⟨_, h⟩ := (hB m).1 in h), refine nonpos_of_restrict_le_zero _ (restrict_le_zero_subset _ _ (set.diff_subset _ _) this), exact measurable_set.Union hB₁ }, { apply_instance }, { exact (measurable_set.Union hB₁).diff (hB₁ n) } }, { exact cInf_le bdd_below_measure_of_negatives ⟨A, ⟨hA₁, hA₂⟩, rfl⟩ } }, refine ⟨Aᶜ, hA₁.compl, _, (compl_compl A).symm ▸ hA₂⟩, rw restrict_le_restrict_iff _ _ hA₁.compl, intros C hC hC₁, by_contra' hC₂, rcases exists_subset_restrict_nonpos hC₂ with ⟨D, hD₁, hD, hD₂, hD₃⟩, have : s (A ∪ D) < Inf s.measure_of_negatives, { rw [← hA₃, of_union (set.disjoint_of_subset_right (set.subset.trans hD hC₁) disjoint_compl_right) hA₁ hD₁], linarith, apply_instance }, refine not_le.2 this _, refine cInf_le bdd_below_measure_of_negatives ⟨A ∪ D, ⟨_, _⟩, rfl⟩, { exact hA₁.union hD₁ }, { exact restrict_le_restrict_union _ _ hA₁ hA₂ hD₁ hD₂ }, end /-- **The Hahn decomposition thoerem**: Given a signed measure `s`, there exist complement measurable sets `i` and `j` such that `i` is positive, `j` is negative. -/ theorem exists_is_compl_positive_negative (s : signed_measure α) : ∃ i j : set α, measurable_set i ∧ 0 ≤[i] s ∧ measurable_set j ∧ s ≤[j] 0 ∧ is_compl i j := let ⟨i, hi₁, hi₂, hi₃⟩ := exists_compl_positive_negative s in ⟨i, iᶜ, hi₁, hi₂, hi₁.compl, hi₃, is_compl_compl⟩ /-- The symmetric difference of two Hahn decompositions has measure zero. -/ lemma of_symm_diff_compl_positive_negative {s : signed_measure α} {i j : set α} (hi : measurable_set i) (hj : measurable_set j) (hi' : 0 ≤[i] s ∧ s ≤[iᶜ] 0) (hj' : 0 ≤[j] s ∧ s ≤[jᶜ] 0) : s (i ∆ j) = 0 ∧ s (iᶜ ∆ jᶜ) = 0 := begin rw [restrict_le_restrict_iff s 0, restrict_le_restrict_iff 0 s] at hi' hj', split, { rw [symm_diff_def, set.diff_eq_compl_inter, set.diff_eq_compl_inter, set.sup_eq_union, of_union, le_antisymm (hi'.2 (hi.compl.inter hj) (set.inter_subset_left _ _)) (hj'.1 (hi.compl.inter hj) (set.inter_subset_right _ _)), le_antisymm (hj'.2 (hj.compl.inter hi) (set.inter_subset_left _ _)) (hi'.1 (hj.compl.inter hi) (set.inter_subset_right _ _)), zero_apply, zero_apply, zero_add], { exact set.disjoint_of_subset_left (set.inter_subset_left _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) (disjoint.comm.1 (is_compl.disjoint is_compl_compl))) }, { exact hj.compl.inter hi }, { exact hi.compl.inter hj } }, { rw [symm_diff_def, set.diff_eq_compl_inter, set.diff_eq_compl_inter, compl_compl, compl_compl, set.sup_eq_union, of_union, le_antisymm (hi'.2 (hj.inter hi.compl) (set.inter_subset_right _ _)) (hj'.1 (hj.inter hi.compl) (set.inter_subset_left _ _)), le_antisymm (hj'.2 (hi.inter hj.compl) (set.inter_subset_right _ _)) (hi'.1 (hi.inter hj.compl) (set.inter_subset_left _ _)), zero_apply, zero_apply, zero_add], { exact set.disjoint_of_subset_left (set.inter_subset_left _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) (is_compl.disjoint is_compl_compl)) }, { exact hj.inter hi.compl }, { exact hi.inter hj.compl } }, all_goals { measurability }, end end signed_measure end measure_theory
6728bac8071a5d85b2a2a5d3828500dde7ab70cc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/fintype/option.lean
30ba9cda385530068dab51831394f0e909673f03
[ "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,856
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.card import data.finset.option /-! # fintype instances for option > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open function open_locale nat universes u v variables {α β γ : Type*} open finset function instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ lemma univ_option (α : Type*) [fintype α] : (univ : finset (option α)) = insert_none univ := rfl @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (finset.card_cons _).trans $ congr_arg2 _ (card_map _) rfl /-- If `option α` is a `fintype` then so is `α` -/ def fintype_of_option {α : Type*} [fintype (option α)] : fintype α := ⟨finset.erase_none (fintype.elems (option α)), λ x, mem_erase_none.mpr (fintype.complete (some x))⟩ /-- A type is a `fintype` if its successor (using `option`) is a `fintype`. -/ def fintype_of_option_equiv [fintype α] (f : α ≃ option β) : fintype β := by { haveI := fintype.of_equiv _ f, exact fintype_of_option } namespace fintype /-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ def trunc_rec_empty_option {P : Type u → Sort v} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α)) (α : Type u) [fintype α] [decidable_eq α] : trunc (P α) := begin suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)), { apply trunc.bind (this (fintype.card α)), intro h, apply trunc.map _ (fintype.trunc_equiv_fin α), intro e, exact of_equiv (equiv.ulift.trans e.symm) h }, intro n, induction n with n ih, { have : card pempty = card (ulift (fin 0)), { simp only [card_fin, card_pempty, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.mk, refine of_equiv e h_empty, }, { have : card (option (ulift (fin n))) = card (ulift (fin n.succ)), { simp only [card_fin, card_option, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.map _ ih, intro ih, refine of_equiv e (h_option ih), }, end /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ @[elab_as_eliminator] lemma induction_empty_option {P : Π (α : Type u) [fintype α], Prop} (of_equiv : ∀ α β [fintype β] (e : α ≃ β), @P α (@fintype.of_equiv α β ‹_› e.symm) → @P β ‹_›) (h_empty : P pempty) (h_option : ∀ α [fintype α], by exactI P α → P (option α)) (α : Type u) [fintype α] : P α := begin obtain ⟨p⟩ := @trunc_rec_empty_option (λ α, ∀ h, @P α h) (λ α β e hα hβ, @of_equiv α β hβ e (hα _)) (λ _i, by convert h_empty) _ α _ (classical.dec_eq α), { exact p _ }, { rintro α hα - Pα hα', resetI, convert h_option α (Pα _) } end end fintype /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ lemma finite.induction_empty_option {P : Type u → Prop} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α], P α → P (option α)) (α : Type u) [finite α] : P α := begin casesI nonempty_fintype α, refine fintype.induction_empty_option _ _ _ α, exacts [λ α β _, of_equiv, h_empty, @h_option] end
3eeccf06841f2691abf8a86139e7331748e2afa1
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/walking.lean
b45abc96a88cc7b8cb2ea443a23f3a7e4c7fbea6
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
3,905
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 import category_theory.functor import data.fintype import category_theory.util.Two open category_theory namespace category_theory.walking universes u₁ v₁ u₂ v₂ section @[derive decidable_eq] inductive WalkingPair : Type u₁ | _1 | _2 open WalkingPair section open tactic @[tidy] private meta def induction_WalkingPair : tactic unit := do l ← local_context, r ← l.reverse.mmap (λ h, do t ← infer_type h, match t with | `(WalkingPair) := cases h >> skip | _ := failed end), when (r.empty) failed end attribute [tidy] induction_WalkingPair -- instance fintype_WalkingPair : fintype WalkingPair := { -- elems := [_1, _2].to_finset, -- complete := by obviously -- } open tactic private meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed local attribute [tidy] case_bash @[reducible] def WalkingPair.hom : WalkingPair → WalkingPair → Type u₁ | _1 _1 := punit | _2 _2 := punit | _ _ := pempty attribute [reducible] WalkingPair.hom._main instance WalkingPair_category : small_category WalkingPair := { hom := WalkingPair.hom, id := by tidy, comp := by tidy } local attribute [back] category.id variable {C : Type u₁} variable [𝒞 : category.{u₁ v₁} C] include 𝒞 @[reducible] def Pair_functor.onObjects (α β : C) : WalkingPair → C | _1 := α | _2 := β attribute [reducible] Pair_functor.onObjects._main @[reducible] def Pair_functor.onMorphisms (α β : C) (X Y : WalkingPair) (f : X ⟶ Y) : (Pair_functor.onObjects α β X) ⟶ (Pair_functor.onObjects α β Y) := match X, Y, f with | _1, _1, _ := 𝟙 α | _2, _2, _ := 𝟙 β end attribute [reducible] Pair_functor.onMorphisms._match_1 def Pair_functor (α β : C) : WalkingPair.{v₁} ⥤ C := { obj := Pair_functor.onObjects α β, map' := Pair_functor.onMorphisms α β, } def Pair_functor' (α β : C) : WalkingPair.{v₁} ⥤ C := { obj := λ X, match X with | _1 := α | _2 := β end, map' := λ X Y f, match X, Y, f with | _1, _1, _ := 𝟙 α | _2, _2, _ := 𝟙 β end, } end section inductive WalkingParallelPair : Type u₁ | _1 | _2 open WalkingParallelPair section open tactic private meta def induction_WalkingParallelPair : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, do t ← infer_type h, match t with | `(WalkingParallelPair) := cases h >> skip | _ := failed end)), when (r.empty) failed attribute [tidy] induction_WalkingParallelPair end local attribute [tidy] case_bash instance : small_category WalkingParallelPair := { hom := λ X Y, match X, Y with | _1, _1 := punit | _2, _2 := punit | _1, _2 := Two | _2, _1 := pempty end, id := by tidy, comp := λ X Y Z f g, match X, Y, Z, f, g with | _1, _1, _1, _, _ := punit.star | _2, _2, _2, _, _ := punit.star | _1, _1, _2, _, h := h | _1, _2, _2, h, _ := h end } variable {C : Type u₁} variable [category.{u₁ v₁} C] def ParallelPair_functor {α β : C} (f g : α ⟶ β) : WalkingParallelPair.{v₁} ⥤ C := { obj := λ X, match X with | _1 := α | _2 := β end, map' := λ X Y h, match X, Y, h with | _1, _1, _ := 𝟙 α | _2, _2, _ := 𝟙 β | _1, _2, Two._0 := f | _1, _2, Two._1 := g end, } end end category_theory.walking
e047716c7559586cd51ce01048961bcc8bf532c1
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/archimedean.lean
27d5bdbf8835f527cbfd96b7c06b5ce1b90bcb8f
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
10,096
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Archimedean groups and fields. -/ import algebra.group_power algebra.field_power algebra.floor import data.rat tactic.linarith variables {α : Type*} open_locale add_monoid class archimedean (α) [ordered_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) theorem exists_nat_gt [linear_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← add_monoid.smul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := have hy0 : 0 < y - 1 := sub_pos_of_lt hy1, -- TODO `by linarith` fails to prove hy1' have hy1' : (-1:α) ≤ y, from le_trans (neg_le_self zero_le_one) (le_of_lt hy1), let ⟨n, h⟩ := archimedean.arch x hy0 in ⟨n, calc x ≤ n • (y - 1) : h ... < 1 + n • (y - 1) : lt_one_add _ ... ≤ y ^ n : one_add_sub_mul_le_pow hy1' n⟩ /-- Every x greater than 1 is between two successive natural-number powers of another y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 < x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from nat.pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_lt_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring section linear_ordered_field /-- Every positive x is between two successive integer powers of another y greater than one. This is the same as `exists_int_pow_near'`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near [discrete_linear_ordered_field α] [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by rw [(fpow_neg y (↑N)), one_div_eq_inv]; exact (inv_lt hx (lt_trans (inv_pos hx) hN)).1 hN)⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (fpow_le_of_le (le_of_lt hy) (le_of_lt hlt)) (lt_of_le_of_lt hm hM))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive x is between two successive integer powers of another y greater than one. This is the same as `exists_int_pow_near`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near' [discrete_linear_ordered_field α] [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) := let ⟨m, hle, hlt⟩ := exists_int_pow_near (inv_pos hx) hy in have hyp : 0 < y, from lt_trans (discrete_linear_ordered_field.zero_lt_one α) hy, ⟨-(m+1), by rwa [fpow_neg, one_div_eq_inv, inv_lt (fpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, fpow_neg, one_div_eq_inv, le_inv hx (fpow_pos_of_pos hyp _)]⟩ variables [linear_ordered_field α] [floor_ring α] lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) : 0 ≤ x - ⌊x / y⌋ * y := begin conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← sub_mul, exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy) end lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) : x - ⌊x / y⌋ * y < y := sub_lt_iff_lt_add.2 begin conv in y {rw ← one_mul y}, conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← add_mul, exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _), end end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.smul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [add_monoid.smul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← add_monoid.smul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨nat_ceil q, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0 := nat.cast_pos.1 (lt_trans (inv_pos (sub_pos.2 h)) nh), have n0' := (@nat.cast_pos α _ _).2 n0, rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div_eq_inv], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases archimedean_iff_nat_lt.1 (by apply_instance) (1/ε) with n hn, existsi n, apply div_lt_of_mul_lt_of_pos, { simp, apply add_pos_of_pos_of_nonneg zero_lt_one, apply nat.cast_nonneg }, { apply (div_lt_iff' hε).1, transitivity, { exact hn }, { simp [zero_lt_one] }} end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 include α @[simp] theorem rat.cast_floor (x : ℚ) : by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ := begin haveI := archimedean.floor_ring α, apply le_antisymm, { rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int], apply floor_le }, { rw [le_floor, ← rat.cast_coe_int, rat.cast_le], apply floor_le } end end linear_ordered_field section variables [discrete_linear_ordered_field α] /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round [floor_ring α] (x : α) : ℤ := ⌊x + 1 / 2⌋ lemma abs_sub_round [floor_ring α] (x : α) : abs (x - round x) ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end variable [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ @[simp] theorem rat.cast_round (x : ℚ) : by haveI := archimedean.floor_ring α; exact round (x:α) = round x := have ((x + (1 : ℚ) / (2 : ℚ) : ℚ) : α) = x + 1 / 2, by simp, by rw [round, round, ← this, rat.cast_floor] end
9250d936d150dd9365fd1d2722646feffa16ea70
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Tactic/SplitIf.lean
c0bd689707aa84b42c8458d8b7953b72c6d5a2a2
[ "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
4,497
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.LazyInitExtension import Lean.Meta.Tactic.Cases import Lean.Meta.Tactic.Simp.Main namespace Lean.Meta namespace SplitIf builtin_initialize ext : LazyInitExtension MetaM Simp.Context ← registerLazyInitExtension do let mut s : SimpLemmas := {} s ← s.addConst ``if_pos s ← s.addConst ``if_neg s ← s.addConst ``dif_pos s ← s.addConst ``dif_neg return { simpLemmas := s congrLemmas := (← getCongrLemmas) config.zeta := false config.beta := false config.eta := false config.iota := false config.proj := false config.decide := false } /-- Default `Simp.Context` for `simpIf` methods. It contains all congruence lemmas, but just the rewriting rules for reducing `if` expressions. -/ def getSimpContext : MetaM Simp.Context := ext.get /-- Default `discharge?` function for `simpIf` methods. It only uses hypotheses from the local context. It is effective after a case-split. -/ def discharge? (useDecide := false) : Simp.Discharge := fun prop => do let prop ← instantiateMVars prop trace[Meta.Tactic.splitIf] "discharge? {prop}, {prop.notNot?}" if useDecide then let prop ← instantiateMVars prop if !prop.hasFVar && !prop.hasMVar then let d ← mkDecide prop let r ← withDefault <| whnf d if r.isConstOf ``true then return some <| mkApp3 (mkConst ``of_decide_eq_true) prop d.appArg! (← mkEqRefl (mkConst ``true)) (← getLCtx).findDeclRevM? fun localDecl => do if localDecl.isAuxDecl then return none else if (← isDefEq prop localDecl.type) then return some localDecl.toExpr else match prop.notNot? with | none => return none | some arg => if (← isDefEq arg localDecl.type) then return some (mkApp2 (mkConst ``not_not_intro) arg localDecl.toExpr) else return none /-- Return the condition of an `if` expression to case split. -/ partial def findIfToSplit? (e : Expr) : Option Expr := if let some iteApp := e.find? fun e => (e.isIte || e.isDIte) && !(e.getArg! 1 5).hasLooseBVars then let cond := iteApp.getArg! 1 5 -- Try to find a nested `if` in `cond` findIfToSplit? cond |>.getD cond else none def splitIfAt? (mvarId : MVarId) (e : Expr) (hName? : Option Name) : MetaM (Option (ByCasesSubgoal × ByCasesSubgoal)) := do if let some cond := findIfToSplit? e then let hName ← match hName? with | none => mkFreshUserName `h | some hName => pure hName trace[Meta.Tactic.splitIf] "splitting on {cond}" return some (← byCases mvarId cond hName) else return none end SplitIf open SplitIf def simpIfTarget (mvarId : MVarId) (useDecide := false) : MetaM MVarId := do let mut ctx ← getSimpContext if let some mvarId' ← simpTarget mvarId ctx (discharge? useDecide) then return mvarId' else unreachable! def simpIfLocalDecl (mvarId : MVarId) (fvarId : FVarId) : MetaM MVarId := do let mut ctx ← getSimpContext if let some (_, mvarId') ← simpLocalDecl mvarId fvarId ctx discharge? then return mvarId' else unreachable! def splitIfTarget? (mvarId : MVarId) (hName? : Option Name := none) : MetaM (Option (ByCasesSubgoal × ByCasesSubgoal)) := commitWhenSome? do if let some (s₁, s₂) ← splitIfAt? mvarId (← getMVarType mvarId) hName? then let mvarId₁ ← simpIfTarget s₁.mvarId let mvarId₂ ← simpIfTarget s₂.mvarId if s₁.mvarId == mvarId₁ && s₂.mvarId == mvarId₂ then return none else return some ({ s₁ with mvarId := mvarId₁ }, { s₂ with mvarId := mvarId₂ }) else return none def splitIfLocalDecl? (mvarId : MVarId) (fvarId : FVarId) (hName? : Option Name := none) : MetaM (Option (MVarId × MVarId)) := commitWhenSome? do withMVarContext mvarId do if let some (s₁, s₂) ← splitIfAt? mvarId (← inferType (mkFVar fvarId)) hName? then let mvarId₁ ← simpIfLocalDecl s₁.mvarId fvarId let mvarId₂ ← simpIfLocalDecl s₂.mvarId fvarId if s₁.mvarId == mvarId₁ && s₂.mvarId == mvarId₂ then return none else return some (mvarId₁, mvarId₂) else return none builtin_initialize registerTraceClass `Meta.Tactic.splitIf end Lean.Meta
298327259c382244c4cedbbc24f1721710964d92
2fbe653e4bc441efde5e5d250566e65538709888
/src/topology/order.lean
516d71e19f9eac7e8ae2b885e3e29323558783d3
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
27,298
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.basic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `α` are ordered, by reverse inclusion. That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂` if every set open in `t₂` is also open in `t₁`. (One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.) Any function `f : α → β` induces `induced f : topological_space β → topological_space α` and `coinduced f : topological_space α → topological_space β`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂. * A map f : (α, t) → (β, u) is continuous iff t ≤ induced f u (`continuous_iff_le_induced`) iff coinduced f t ≤ u (`continuous_iff_coinduced_le`). Topologies on α form a complete lattice, with ⊥ the discrete topology and ⊤ the indiscrete topology. For a function f : α → β, (coinduced f, induced f) is a Galois connection between topologies on α and topologies on β. ## Implementation notes There is a Galois insertion between topologies on α (with the inclusion ordering) and all collections of sets in α. The complete lattice structure on topologies on α is defined as the reverse of the one obtained via this Galois insertion. ## Tags finer, coarser, induced topology, coinduced topology -/ open set filter lattice classical open_locale classical topological_space universes u v w namespace topological_space variables {α : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ g, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) := by rw nhds_def; exact le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, begin revert as, clear_, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat ... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) /-- Construct a topology on α given the filter of neighborhoods of each point of α. -/ protected def mk_of_nhds (n : α → filter α) : topological_space α := { is_open := λs, ∀a∈s, s ∈ n a, is_open_univ := assume x h, univ_mem_sets, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : α → filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') : @nhds α (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb, have h₁ : {b | s ∈ n b} ∈ 𝓝 a, { refine mem_nhds_sets (assume b (hb : s ∈ n b), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_sets_of_superset ht h }, exact mem_sets_of_superset h₁ h₀ }, { rcases (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {α : Type u} {β : Type v} /-- The inclusion ordering on topologies on α. We use it to get a complete lattice instance via the Galois insertion method, but the partial order that we will eventually impose on `topological_space α` is the reverse one. -/ def tmp_order : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } local attribute [instance] tmp_order /- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/ private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ _, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm /-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part sends a collection of subsets of α to the topology they generate, and whose upper part sends a topology to its collection of open subsets. -/ def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) : topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ := (gi_generate_from _).gc.monotone_l h /-- The complete lattice of topological spaces, but built on the inclusion ordering. -/ def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice /-- The ordering on topologies on the type `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (topological_space α) := { le := λ t s, s.is_open ≤ t.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, le_trans h₂ h₁ } lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} : t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} := generate_from_le_iff_subset_is_open /-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremem is the topology whose open sets are those sets open in every member of the collection. -/ instance : complete_lattice (topological_space α) := @order_dual.lattice.complete_lattice _ tmp_complete_lattice /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `⊥`. -/ class discrete_topology (α : Type*) [t : topological_space α] : Prop := (eq_bot : t = ⊥) @[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) : is_open s := (discrete_topology.eq_bot α).symm ▸ trivial lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f := λs hs, is_open_discrete _ lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure := begin refine le_antisymm _ (@pure_le_nhds α ⊥), assume a s hs, exact @mem_nhds_sets α ⊥ a s trivial hs end lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure := (discrete_topology.eq_bot α).symm ▸ nhds_bot α lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) : t₁ ≤ t₂ := assume s, show @is_open α t₂ s → @is_open α t₁ s, by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha } lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ := bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x) end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s, is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩, is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩; exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩, exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) := ⟨assume ⟨t, ht, heq⟩, ⟨-t, is_closed_compl_iff.2 ht, by simp only [preimage_compl, heq, lattice.neg_neg]⟩, assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp only [preimage_compl, heq.symm]⟩⟩ /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} : @is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.rfl variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma coinduced_le_iff_le_induced {f : α → β } {tα : topological_space α} {tβ : topological_space β} : tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f := iff.intro (assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht) (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) lemma gc_coinduced_induced (f : α → β) : galois_connection (topological_space.coinduced f) (topological_space.induced f) := assume f g, coinduced_le_iff_le_induced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_coinduced_induced g).monotone_u h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ := (gc_coinduced_induced g).u_top @[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g := (gc_coinduced_induced g).u_inf @[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).induced g = (⨅i, (t i).induced g) := (gc_coinduced_induced g).u_infi @[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ := (gc_coinduced_induced f).l_bot @[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f := (gc_coinduced_induced f).l_sup @[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) := (gc_coinduced_induced f).l_supr lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ instance : topological_space empty := ⊥ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space unit := ⊥ instance : discrete_topology unit := ⟨rfl⟩ instance : topological_space bool := ⊥ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space ℕ := ⊥ instance : discrete_topology ℕ := ⟨rfl⟩ instance : topological_space ℤ := ⊥ instance : discrete_topology ℤ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : t ≤ generate_from g := le_generate_from_iff_subset_is_open.2 h lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} : (generate_from b).induced f = topological_space.generate_from (preimage f '' b) := le_antisymm (le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs, generate_open.basic _ $ mem_image_of_mem _ hs) /-- This construction is left adjoint to the operation sending a topology on `α` to its neighborhood filter at a fixed point `a : α`. -/ protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : galois_connection (topological_space.nhds_adjoint a) (λt, @nhds α t a) := assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ } lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi lemma nhds_Inf {s : set (topological_space α)} {a : α} : @nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {γ : Type*} {f : α → β} {ι : Sort*} lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ := iff.rfl lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ := iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_coinduced_le.2 $ le_generate_from h lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := assume s h, ⟨_, h, rfl⟩ lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := assume s ⟨t, ht, s_eq⟩, s_eq ▸ h t ht lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := assume s h, h lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := assume s hs, h s hs lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := assume s h, h₁ _ (h₂ s h) lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := assume s h, h₂ s (h₁ s h) lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f := assume s h, ⟨h₁ s h, h₂ s h⟩ lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_left lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f := continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f := continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f := continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f := continuous_Sup_rng ⟨i, rfl⟩ h lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f := continuous_iff_coinduced_le.2 $ le_inf (continuous_iff_coinduced_le.1 h₁) (continuous_iff_coinduced_le.1 h₂) lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_left lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) : cont t t₂ f → cont (Inf t₁) t₂ f := continuous_le_dom $ Inf_le h₁ lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} (h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f := continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} : cont (t₁ i) t₂ f → cont (infi t₁) t₂ f := continuous_le_dom $ infi_le _ _ lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} (h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i lemma continuous_bot {t : tspace β} : cont ⊥ t f := continuous_iff_le_induced.2 $ bot_le lemma continuous_top {t : tspace α} : cont t ⊤ f := continuous_iff_coinduced_le.2 $ le_top /- 𝓝 in the induced topology -/ theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) : s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s := begin simp only [nhds_sets, is_open_induced_iff, exists_prop, set.mem_set_of_eq], split, { rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩, exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ }, rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩, exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ end theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) : @nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) := filter_eq $ by ext s; rw mem_nhds_induced; rw mem_comap_sets lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) : tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) := ⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩ theorem map_nhds_induced_of_surjective [T : topological_space α] {f : β → α} (hf : function.surjective f) (a : β) : map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end constructions section induced open topological_space variables {α : Type*} {β : Type*} variables [t : topological_space β] {f : α → β} theorem is_open_induced_eq {s : set α} : @_root_.is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} := iff.rfl theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma map_nhds_induced_eq {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap h] lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} (hf : ∀x y, f x = f y → x = y) : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := have comap f (𝓝 (f a) ⊓ principal (f '' s)) ≠ ⊥ ↔ 𝓝 (f a) ⊓ principal (f '' s) ≠ ⊥, from ⟨assume h₁ h₂, h₁ $ h₂.symm ▸ comap_bot, assume h, forall_sets_nonempty_iff_ne_bot.mp $ assume s₁ ⟨s₂, hs₂, (hs : f ⁻¹' s₂ ⊆ s₁)⟩, have f '' s ∈ 𝓝 (f a) ⊓ principal (f '' s), from mem_inf_sets_of_right $ by simp [subset.refl], have s₂ ∩ f '' s ∈ 𝓝 (f a) ⊓ principal (f '' s), from inter_mem_sets hs₂ this, let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := nonempty_of_mem_sets h this in ⟨_, hs $ by rwa [←ha₂] at hb₁⟩⟩, calc a ∈ @closure α (topological_space.induced f t) s ↔ (@nhds α (topological_space.induced f t) a) ⊓ principal s ≠ ⊥ : by rw [closure_eq_nhds]; refl ... ↔ comap f (𝓝 (f a)) ⊓ principal (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced, preimage_image_eq _ hf] ... ↔ comap f (𝓝 (f a) ⊓ principal (f '' s)) ≠ ⊥ : by rw [comap_inf, ←comap_principal] ... ↔ _ : by rwa [closure_eq_nhds] end induced section sierpinski variables {α : Type*} [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from h _ is_open_singleton_true, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ end sierpinski section infi variables {α : Type u} {ι : Type v} {t : ι → topological_space α} lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s := begin -- s defines a map from α to Prop, which is continuous iff s is open. suffices : @continuous _ _ (⨆ i, t i) _ s ↔ ∀ i, @continuous _ _ (t i) _ s, { simpa only [continuous_Prop] using this }, simp only [continuous_iff_le_induced, supr_le_iff] end lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s := is_open_supr_iff end infi
f30c004cfa1a9d5ade3973f9afc0a917581e4633
39c5aa4cf3be4a2dfd294cd2becd0848ff4cad97
/src/Parser.lean
778c23b4551b6cbfa5c462d4a054d644617a996a
[]
no_license
anfelor/coc-lean
70d489ae1d34932d33bcf211b4ef8d1fe557e1d3
fdd967d2b7bc349202a1deabbbce155eed4db73a
refs/heads/master
1,617,867,588,097
1,587,224,804,000
1,587,224,804,000
248,754,643
5
0
null
null
null
null
UTF-8
Lean
false
false
6,515
lean
import data.list import data.pfun /-! A simple parser combinator library Similar to http://dev.stephendiehl.com/fun/002_parsers.html -/ universes u v structure Parser (a : Type u) := mk :: (parse : string -> list (a × string)) def runParser {a} (m : Parser a) (s : string) : a ⊕ string := match m.parse s with | [(res, "")] := sum.inl res | [(_, rs)] := sum.inr "Parser did not consume entire stream." | [] := sum.inr "No matches." | _ := sum.inr "Ambiguous." end instance parser_has_pure : has_pure Parser := { pure := λ α a, Parser.mk (λ s, [(a, s)]) } instance parser_has_bind : has_bind Parser := { bind := λ α β p f, Parser.mk (λ s, (p.parse s) >>= λ ⟨a, s'⟩, (f a).parse s') } instance parser_functor : functor Parser := { map := λ α β f p, p >>= (pure ∘ f) } instance parser_has_seq : has_seq Parser := { seq := λ α β p q, p >>= λ f, f <$> q } instance parser_applicative : applicative Parser := {} instance parser_monad : monad Parser := {} def mplus {a} (p : Parser a) (q : Parser a) : Parser a := Parser.mk $ λ s, p.parse s ++ q.parse s instance parser_has_orelse : has_orelse Parser := { orelse := λ _ p q, Parser.mk $ λ s, match p.parse s with | [] := q.parse s | res := res end } instance parser_alternative : alternative Parser := { failure := λ _, Parser.mk $ λ _, [] } /-- Some higher order parsers like many, many1, .. only terminate for some argument parsers. Therefore we factor the termination out into a type class. -/ def parser_rel {a} (p : Parser a) : string -> string -> Prop := λ s1 s2, s1 ∈ (λ x : (a × string), x.2) <$> (p.parse s2) class productive {a} (p : Parser a) := (produces : well_founded (parser_rel p)) def list_bind_contains {a b} : Π (ls : list a) (f : Π x, x ∈ ls -> list b), list b | [] f := [] | (l::ls) f := f l (by simp) ++ list_bind_contains ls (λ x h, f x (by simp [h])) -- (::) <$> v <*> (many1 v <|> pure []) def many1_rec {a} (v : Parser a) : Π s, (Π y, parser_rel v y s -> list (list a × string)) -> list (list a × string) := λ s, λ rec, list_bind_contains (v.parse s) $ λ ⟨a', s'⟩ h, let h2 : parser_rel v s' s := by { simp [parser_rel], exact ⟨a', h⟩, } in match (rec s' h2) with | [] := [⟨[a'], s'⟩] | res := (λ x : (list a × string), ⟨a' :: x.1, x.2⟩) <$> res end def many1 {a} (v : Parser a) [d : productive v] : Parser (list a) := Parser.mk $ λ s, @well_founded.fix _ _ _ d.produces (many1_rec v) s def many {a} (v : Parser a) [productive v] : Parser (list a) := many1 v <|> pure [] def item : Parser char := Parser.mk $ λ s, match string.to_list s with | [] := [] | (c::cs) := [(c, list.as_string cs)] end lemma list_string_id {x} : list.as_string (string.to_list x) = x := begin cases x, rw [string.to_list, list.as_string], end lemma string_list_id {x} : string.to_list (list.as_string x) = x := begin cases x, repeat { simp [list.as_string, string.to_list], }, end lemma item_productive_acc : ∀ l, acc (parser_rel item) (list.as_string l) | [] := acc.intro _ (λ y h, begin simp [parser_rel, item, (<$>), string_list_id] at h, from false.elim h end) | (l::ls) := acc.intro _ (λ y h, begin simp [parser_rel, item, string_list_id, (<$>)] at h, let h2 := item_productive_acc ls, rwa [h.symm] at h2, end) instance item_productive : productive item := { produces := begin apply well_founded.intro, intro s, from eq.mp (by simp [list_string_id]) (item_productive_acc (string.to_list s)) end } def transform {a} (p : char -> option a) : Parser a := item >>= λ c, match p c with | some r := pure r | none := Parser.mk (λ _, []) end lemma transform_productive_acc {a f} : ∀ l, acc (parser_rel (@transform a f)) (list.as_string l) | [] := acc.intro _ (λ y h, begin simp [parser_rel, transform, (>>=), item, string_list_id, (<$>)] at h, from false.elim h end) | (l::ls) := acc.intro _ (λ y h, begin simp [parser_rel, transform, (>>=), item, string_list_id, parser_has_bind] at h, cases f l, { simp [transform] at h, from false.elim h }, simp [transform, pure] at h, let h2 := transform_productive_acc ls, rwa [h.symm] at h2, end) instance transform_productive {a f} : productive (@transform a f) := { produces := begin apply well_founded.intro, intro s, from eq.mp (by simp [list_string_id]) (transform_productive_acc (string.to_list s)) end } def satisfy (p : char -> bool) : Parser char := transform (λ c, if p c then some c else none) instance satisfy_productive {f} : productive (satisfy f) := { produces := begin simp [satisfy], from transform_productive.produces, end } def oneOf (ls : list char) : Parser char := satisfy (λ c, c ∈ ls) instance oneOf_productive {ls} : productive (oneOf ls) := { produces := begin simp [oneOf], from satisfy_productive.produces, end } def spaces : Parser (list char) := many (oneOf [' ', '\t', '\n']) /-- The 'char' parser. -/ def character (c : char) : Parser char := satisfy (λ d, c = d) def asDigit : char -> option nat | '0' := some 0 | '1' := some 1 | '2' := some 2 | '3' := some 3 | '4' := some 4 | '5' := some 5 | '6' := some 6 | '7' := some 7 | '8' := some 8 | '9' := some 9 | _ := none def isDigit (c : char) : bool := option.is_some (asDigit c) def digit : Parser char := satisfy isDigit def token {a} (p : Parser a) : Parser a := p >>= λ a, spaces >> pure a /-- The 'string' parser. -/ def charlist : list char -> Parser (list char) | [] := pure [] | (c::cs) := character c >> charlist cs >> pure (c :: cs) def reserved (s : string) : Parser string := token (charlist (string.to_list s)) >> pure s def parens {a} (p : Parser a) : Parser a := reserved "(" >> p >>= λ r, reserved ")" >> pure r def combineNum : Π (ls : list nat), nat | [] := 0 | (l::ls) := l * (10 ^ ls.length) + combineNum ls def natural : Parser nat := combineNum <$> many1 (transform asDigit) def integer : Parser int := (character '-' <|> pure '+') >>= λ c, (λ n : nat, if c = '-' then -n else n) <$> natural -- chainl :: Parser a -> Parser (a -> a -> a) -> a -> Parser a -- chainl p op a = (p `chainl1` op) <|> return a -- chainl1 :: Parser a -> Parser (a -> a -> a) -> Parser a -- p `chainl1` op = do {a <- p; rest a} -- where rest a = (do f <- op -- b <- p -- rest (f a b)) -- <|> return a
1046973c097df96a6b3c6c022d0f7d85e9848c45
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/compactly_generated.lean
79ad5b3cdeb25ee9b82e2889c17b6782c51dd7bf
[ "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
23,092
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import order.atoms import order.order_iso_nat import order.rel_iso.set import order.sup_indep import order.zorn import data.finset.order import data.set.intervals.order_iso import data.finite.set import tactic.tfae /-! # Compactness properties for complete lattices For complete lattices, there are numerous equivalent ways to express the fact that the relation `>` is well-founded. In this file we define three especially-useful characterisations and provide proofs that they are indeed equivalent to well-foundedness. ## Main definitions * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `complete_lattice.is_compact_element` * `complete_lattice.is_compactly_generated` ## Main results The main result is that the following four conditions are equivalent for a complete lattice: * `well_founded (>)` * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `∀ k, complete_lattice.is_compact_element k` This is demonstrated by means of the following four lemmas: * `complete_lattice.well_founded.is_Sup_finite_compact` * `complete_lattice.is_Sup_finite_compact.is_sup_closed_compact` * `complete_lattice.is_sup_closed_compact.well_founded` * `complete_lattice.is_Sup_finite_compact_iff_all_elements_compact` We also show well-founded lattices are compactly generated (`complete_lattice.compactly_generated_of_well_founded`). ## References - [G. Călugăreanu, *Lattice Concepts of Module Theory*][calugareanu] ## Tags complete lattice, well-founded, compact -/ variables {α : Type*} [complete_lattice α] namespace complete_lattice variables (α) /-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset contains its `Sup`. -/ def is_sup_closed_compact : Prop := ∀ (s : set α) (h : s.nonempty), (∀ a b ∈ s, a ⊔ b ∈ s) → (Sup s) ∈ s /-- A compactness property for a complete lattice is that any subset has a finite subset with the same `Sup`. -/ def is_Sup_finite_compact : Prop := ∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id /-- An element `k` of a complete lattice is said to be compact if any set with `Sup` above `k` has a finite subset with `Sup` above `k`. Such an element is also called "finite" or "S-compact". -/ def is_compact_element {α : Type*} [complete_lattice α] (k : α) := ∀ s : set α, k ≤ Sup s → ∃ t : finset α, ↑t ⊆ s ∧ k ≤ t.sup id lemma {u} is_compact_element_iff {α : Type u} [complete_lattice α] (k : α) : complete_lattice.is_compact_element k ↔ ∀ (ι : Type u) (s : ι → α), k ≤ supr s → ∃ t : finset ι, k ≤ t.sup s := begin classical, split, { intros H ι s hs, obtain ⟨t, ht, ht'⟩ := H (set.range s) hs, have : ∀ x : t, ∃ i, s i = x := λ x, ht x.prop, choose f hf using this, refine ⟨finset.univ.image f, ht'.trans _⟩, { rw finset.sup_le_iff, intros b hb, rw ← (show s (f ⟨b, hb⟩) = id b, from hf _), exact finset.le_sup (finset.mem_image_of_mem f $ finset.mem_univ ⟨b, hb⟩) } }, { intros H s hs, obtain ⟨t, ht⟩ := H s coe (by { delta supr, rwa subtype.range_coe }), refine ⟨t.image coe, by simp, ht.trans _⟩, rw finset.sup_le_iff, exact λ x hx, @finset.le_sup _ _ _ _ _ id _ (finset.mem_image_of_mem coe hx) } end /-- An element `k` is compact if and only if any directed set with `Sup` above `k` already got above `k` at some point in the set. -/ theorem is_compact_element_iff_le_of_directed_Sup_le (k : α) : is_compact_element k ↔ ∀ s : set α, s.nonempty → directed_on (≤) s → k ≤ Sup s → ∃ x : α, x ∈ s ∧ k ≤ x := begin classical, split, { intros hk s hne hdir hsup, obtain ⟨t, ht⟩ := hk s hsup, -- certainly every element of t is below something in s, since ↑t ⊆ s. have t_below_s : ∀ x ∈ t, ∃ y ∈ s, x ≤ y, from λ x hxt, ⟨x, ht.left hxt, le_rfl⟩, obtain ⟨x, ⟨hxs, hsupx⟩⟩ := finset.sup_le_of_le_directed s hne hdir t t_below_s, exact ⟨x, ⟨hxs, le_trans ht.right hsupx⟩⟩, }, { intros hk s hsup, -- Consider the set of finite joins of elements of the (plain) set s. let S : set α := { x | ∃ t : finset α, ↑t ⊆ s ∧ x = t.sup id }, -- S is directed, nonempty, and still has sup above k. have dir_US : directed_on (≤) S, { rintros x ⟨c, hc⟩ y ⟨d, hd⟩, use x ⊔ y, split, { use c ∪ d, split, { simp only [hc.left, hd.left, set.union_subset_iff, finset.coe_union, and_self], }, { simp only [hc.right, hd.right, finset.sup_union], }, }, simp only [and_self, le_sup_left, le_sup_right], }, have sup_S : Sup s ≤ Sup S, { apply Sup_le_Sup, intros x hx, use {x}, simpa only [and_true, id.def, finset.coe_singleton, eq_self_iff_true, finset.sup_singleton, set.singleton_subset_iff], }, have Sne : S.nonempty, { suffices : ⊥ ∈ S, from set.nonempty_of_mem this, use ∅, simp only [set.empty_subset, finset.coe_empty, finset.sup_empty, eq_self_iff_true, and_self], }, -- Now apply the defn of compact and finish. obtain ⟨j, ⟨hjS, hjk⟩⟩ := hk S Sne dir_US (le_trans hsup sup_S), obtain ⟨t, ⟨htS, htsup⟩⟩ := hjS, use t, exact ⟨htS, by rwa ←htsup⟩, }, end lemma is_compact_element.exists_finset_of_le_supr {k : α} (hk : is_compact_element k) {ι : Type*} (f : ι → α) (h : k ≤ ⨆ i, f i) : ∃ s : finset ι, k ≤ ⨆ i ∈ s, f i := begin classical, let g : finset ι → α := λ s, ⨆ i ∈ s, f i, have h1 : directed_on (≤) (set.range g), { rintros - ⟨s, rfl⟩ - ⟨t, rfl⟩, exact ⟨g (s ∪ t), ⟨s ∪ t, rfl⟩, supr_le_supr_of_subset (finset.subset_union_left s t), supr_le_supr_of_subset (finset.subset_union_right s t)⟩ }, have h2 : k ≤ Sup (set.range g), { exact h.trans (supr_le (λ i, le_Sup_of_le ⟨{i}, rfl⟩ (le_supr_of_le i (le_supr_of_le (finset.mem_singleton_self i) le_rfl)))) }, obtain ⟨-, ⟨s, rfl⟩, hs⟩ := (is_compact_element_iff_le_of_directed_Sup_le α k).mp hk (set.range g) (set.range_nonempty g) h1 h2, exact ⟨s, hs⟩, end /-- A compact element `k` has the property that any directed set lying strictly below `k` has its Sup strictly below `k`. -/ lemma is_compact_element.directed_Sup_lt_of_lt {α : Type*} [complete_lattice α] {k : α} (hk : is_compact_element k) {s : set α} (hemp : s.nonempty) (hdir : directed_on (≤) s) (hbelow : ∀ x ∈ s, x < k) : Sup s < k := begin rw is_compact_element_iff_le_of_directed_Sup_le at hk, by_contradiction, have sSup : Sup s ≤ k, from Sup_le (λ s hs, (hbelow s hs).le), replace sSup : Sup s = k := eq_iff_le_not_lt.mpr ⟨sSup, h⟩, obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le, obtain hxk := hbelow x hxs, exact hxk.ne (hxk.le.antisymm hkx), end lemma finset_sup_compact_of_compact {α β : Type*} [complete_lattice α] {f : β → α} (s : finset β) (h : ∀ x ∈ s, is_compact_element (f x)) : is_compact_element (s.sup f) := begin classical, rw is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, change f with id ∘ f, rw ←finset.sup_finset_image, apply finset.sup_le_of_le_directed d hemp hdir, rintros x hx, obtain ⟨p, ⟨hps, rfl⟩⟩ := finset.mem_image.mp hx, specialize h p hps, rw is_compact_element_iff_le_of_directed_Sup_le at h, specialize h d hemp hdir (le_trans (finset.le_sup hps) hsup), simpa only [exists_prop], end lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) : is_Sup_finite_compact α := begin intros s, let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x }, have hp : p.nonempty, { use [⊥, ∅], simp, }, obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp, use t, simp only [ht₁, ht₂, true_and], apply le_antisymm, { apply Sup_le, intros y hy, classical, have hy' : (insert y t).sup id ∈ p, { use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, }, have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), }, rw ← hm _ hy' hm', simp, }, { rw [← ht₂, finset.sup_id_eq_Sup], exact Sup_le_Sup ht₁, }, end lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) : is_sup_closed_compact α := begin intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h, cases t.eq_empty_or_nonempty with h h, { subst h, rw finset.sup_empty at ht₂, rw ht₂, simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], }, { rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, }, end lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) : well_founded ((>) : α → α → Prop) := begin refine rel_embedding.well_founded_iff_no_descending_seq.mpr ⟨λ a, _⟩, suffices : Sup (set.range a) ∈ set.range a, { obtain ⟨n, hn⟩ := set.mem_range.mp this, have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], }, apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, }, apply h (set.range a), { use a 37, apply set.mem_range_self, }, { rintros x ⟨m, hm⟩ y ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply rel_hom_class.map_sup a, }, end lemma is_Sup_finite_compact_iff_all_elements_compact : is_Sup_finite_compact α ↔ (∀ k : α, is_compact_element k) := begin refine ⟨λ h k s hs, _, λ h s, _⟩, { obtain ⟨t, ⟨hts, htsup⟩⟩ := h s, use [t, hts], rwa ←htsup, }, { obtain ⟨t, ⟨hts, htsup⟩⟩ := h (Sup s) s (by refl), have : Sup s = t.sup id, { suffices : t.sup id ≤ Sup s, by { apply le_antisymm; assumption }, simp only [id.def, finset.sup_le_iff], intros x hx, exact le_Sup (hts hx) }, use [t, hts, this] }, end lemma well_founded_characterisations : tfae [well_founded ((>) : α → α → Prop), is_Sup_finite_compact α, is_sup_closed_compact α, ∀ k : α, is_compact_element k] := begin tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, }, tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, }, tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, }, tfae_have : 2 ↔ 4, by { exact is_Sup_finite_compact_iff_all_elements_compact α }, tfae_finish, end lemma well_founded_iff_is_Sup_finite_compact : well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α := (well_founded_characterisations α).out 0 1 lemma is_Sup_finite_compact_iff_is_sup_closed_compact : is_Sup_finite_compact α ↔ is_sup_closed_compact α := (well_founded_characterisations α).out 1 2 lemma is_sup_closed_compact_iff_well_founded : is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) := (well_founded_characterisations α).out 2 0 alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔ _ is_sup_closed_compact.is_Sup_finite_compact alias is_sup_closed_compact_iff_well_founded ↔ _ _root_.well_founded.is_sup_closed_compact variables {α} lemma well_founded.finite_of_set_independent (h : well_founded ((>) : α → α → Prop)) {s : set α} (hs : set_independent s) : s.finite := begin classical, refine set.not_infinite.mp (λ contra, _), obtain ⟨t, ht₁, ht₂⟩ := well_founded.is_Sup_finite_compact α h s, replace contra : ∃ (x : α), x ∈ s ∧ x ≠ ⊥ ∧ x ∉ t, { have : (s \ (insert ⊥ t : finset α)).infinite := contra.diff (finset.finite_to_set _), obtain ⟨x, hx₁, hx₂⟩ := this.nonempty, exact ⟨x, hx₁, by simpa [not_or_distrib] using hx₂⟩, }, obtain ⟨x, hx₀, hx₁, hx₂⟩ := contra, replace hs : x ⊓ Sup s = ⊥, { have := hs.mono (by simp [ht₁, hx₀, -set.union_singleton] : ↑t ∪ {x} ≤ s) (by simp : x ∈ _), simpa [disjoint, hx₂, ← t.sup_id_eq_Sup, ← ht₂] using this.eq_bot, }, apply hx₁, rw [← hs, eq_comm, inf_eq_left], exact le_Sup hx₀, end lemma well_founded.finite_of_independent (hwf : well_founded ((>) : α → α → Prop)) {ι : Type*} {t : ι → α} (ht : independent t) (h_ne_bot : ∀ i, t i ≠ ⊥) : finite ι := begin haveI := (well_founded.finite_of_set_independent hwf ht.set_independent_range).to_subtype, exact finite.of_injective_finite_range (ht.injective h_ne_bot), end end complete_lattice /-- A complete lattice is said to be compactly generated if any element is the `Sup` of compact elements. -/ class is_compactly_generated (α : Type*) [complete_lattice α] : Prop := (exists_Sup_eq : ∀ (x : α), ∃ (s : set α), (∀ x ∈ s, complete_lattice.is_compact_element x) ∧ Sup s = x) section variables {α} [is_compactly_generated α] {a b : α} {s : set α} @[simp] lemma Sup_compact_le_eq (b) : Sup {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} = b := begin rcases is_compactly_generated.exists_Sup_eq b with ⟨s, hs, rfl⟩, exact le_antisymm (Sup_le (λ c hc, hc.2)) (Sup_le_Sup (λ c cs, ⟨hs c cs, le_Sup cs⟩)), end @[simp] theorem Sup_compact_eq_top : Sup {a : α | complete_lattice.is_compact_element a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_compact_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_compact_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, complete_lattice.is_compact_element c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_compact_le_eq a, ← Sup_compact_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ /-- This property is sometimes referred to as `α` being upper continuous. -/ theorem inf_Sup_eq_of_directed_on (h : directed_on (≤) s): a ⊓ Sup s = ⨆ b ∈ s, a ⊓ b := le_antisymm (begin rw le_iff_compact_le_imp, by_cases hs : s.nonempty, { intros c hc hcinf, rw le_inf_iff at hcinf, rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le at hc, rcases hc s hs h hcinf.2 with ⟨d, ds, cd⟩, exact (le_inf hcinf.1 cd).trans (le_supr₂ d ds) }, { rw set.not_nonempty_iff_eq_empty at hs, simp [hs] } end) supr_inf_le_inf_Sup /-- This property is equivalent to `α` being upper continuous. -/ theorem inf_Sup_eq_supr_inf_sup_finset : a ⊓ Sup s = ⨆ (t : finset α) (H : ↑t ⊆ s), a ⊓ (t.sup id) := le_antisymm (begin rw le_iff_compact_le_imp, intros c hc hcinf, rw le_inf_iff at hcinf, rcases hc s hcinf.2 with ⟨t, ht1, ht2⟩, exact (le_inf hcinf.1 ht2).trans (le_supr₂ t ht1), end) (supr_le $ λ t, supr_le $ λ h, inf_le_inf_left _ ((finset.sup_id_eq_Sup t).symm ▸ (Sup_le_Sup h))) theorem complete_lattice.set_independent_iff_finite {s : set α} : complete_lattice.set_independent s ↔ ∀ t : finset α, ↑t ⊆ s → complete_lattice.set_independent (↑t : set α) := ⟨λ hs t ht, hs.mono ht, λ h a ha, begin rw [disjoint_iff, inf_Sup_eq_supr_inf_sup_finset, supr_eq_bot], intro t, rw [supr_eq_bot, finset.sup_id_eq_Sup], intro ht, classical, have h' := (h (insert a t) _ (t.mem_insert_self a)).eq_bot, { rwa [finset.coe_insert, set.insert_diff_self_of_not_mem] at h', exact λ con, ((set.mem_diff a).1 (ht con)).2 (set.mem_singleton a) }, { rw [finset.coe_insert, set.insert_subset], exact ⟨ha, set.subset.trans ht (set.diff_subset _ _)⟩ } end⟩ lemma complete_lattice.set_independent_Union_of_directed {η : Type*} {s : η → set α} (hs : directed (⊆) s) (h : ∀ i, complete_lattice.set_independent (s i)) : complete_lattice.set_independent (⋃ i, s i) := begin by_cases hη : nonempty η, { resetI, rw complete_lattice.set_independent_iff_finite, intros t ht, obtain ⟨I, fi, hI⟩ := set.finite_subset_Union t.finite_to_set ht, obtain ⟨i, hi⟩ := hs.finset_le fi.to_finset, exact (h i).mono (set.subset.trans hI $ set.Union₂_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { rintros a ⟨_, ⟨i, _⟩, _⟩, exfalso, exact hη ⟨i⟩, }, end lemma complete_lattice.independent_sUnion_of_directed {s : set (set α)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, complete_lattice.set_independent a) : complete_lattice.set_independent (⋃₀ s) := by rw set.sUnion_eq_Union; exact complete_lattice.set_independent_Union_of_directed hs.directed_coe (by simpa using h) end namespace complete_lattice lemma compactly_generated_of_well_founded (h : well_founded ((>) : α → α → Prop)) : is_compactly_generated α := begin rw [well_founded_iff_is_Sup_finite_compact, is_Sup_finite_compact_iff_all_elements_compact] at h, -- x is the join of the set of compact elements {x} exact ⟨λ x, ⟨{x}, ⟨λ x _, h x, Sup_singleton⟩⟩⟩, end /-- A compact element `k` has the property that any `b < k` lies below a "maximal element below `k`", which is to say `[⊥, k]` is coatomic. -/ theorem Iic_coatomic_of_compact_element {k : α} (h : is_compact_element k) : is_coatomic (set.Iic k) := ⟨λ ⟨b, hbk⟩, begin by_cases htriv : b = k, { left, ext, simp only [htriv, set.Iic.coe_top, subtype.coe_mk], }, right, obtain ⟨a, a₀, ba, h⟩ := zorn_nonempty_partial_order₀ (set.Iio k) _ b (lt_of_le_of_ne hbk htriv), { refine ⟨⟨a, le_of_lt a₀⟩, ⟨ne_of_lt a₀, λ c hck, by_contradiction $ λ c₀, _⟩, ba⟩, cases h c.1 (lt_of_le_of_ne c.2 (λ con, c₀ (subtype.ext con))) hck.le, exact lt_irrefl _ hck, }, { intros S SC cC I IS, by_cases hS : S.nonempty, { exact ⟨Sup S, h.directed_Sup_lt_of_lt hS cC.directed_on SC, λ _, le_Sup⟩, }, exact ⟨b, lt_of_le_of_ne hbk htriv, by simp only [set.not_nonempty_iff_eq_empty.mp hS, set.mem_empty_iff_false, forall_const, forall_prop_of_false, not_false_iff]⟩, }, end⟩ lemma coatomic_of_top_compact (h : is_compact_element (⊤ : α)) : is_coatomic α := (@order_iso.Iic_top α _ _).is_coatomic_iff.mp (Iic_coatomic_of_compact_element h) end complete_lattice section variables [is_modular_lattice α] [is_compactly_generated α] @[priority 100] instance is_atomic_of_complemented_lattice [complemented_lattice α] : is_atomic α := ⟨λ b, begin by_cases h : {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} ⊆ {⊥}, { left, rw [← Sup_compact_le_eq b, Sup_eq_bot], exact h }, { rcases set.not_subset.1 h with ⟨c, ⟨hc, hcb⟩, hcbot⟩, right, have hc' := complete_lattice.Iic_coatomic_of_compact_element hc, rw ← is_atomic_iff_is_coatomic at hc', haveI := hc', obtain con | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le (⟨c, le_refl c⟩ : set.Iic c), { exfalso, apply hcbot, simp only [subtype.ext_iff, set.Iic.coe_bot, subtype.coe_mk] at con, exact con }, rw [← subtype.coe_le_coe, subtype.coe_mk] at hac, exact ⟨a, ha.of_is_atom_coe_Iic, hac.trans hcb⟩ }, end⟩ /-- See Lemma 5.1, Călugăreanu -/ @[priority 100] instance is_atomistic_of_complemented_lattice [complemented_lattice α] : is_atomistic α := ⟨λ b, ⟨{a | is_atom a ∧ a ≤ b}, begin symmetry, have hle : Sup {a : α | is_atom a ∧ a ≤ b} ≤ b := (Sup_le $ λ _, and.right), apply (lt_or_eq_of_le hle).resolve_left (λ con, _), obtain ⟨c, hc⟩ := exists_is_compl (⟨Sup {a : α | is_atom a ∧ a ≤ b}, hle⟩ : set.Iic b), obtain rfl | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le c, { exact ne_of_lt con (subtype.ext_iff.1 (eq_top_of_is_compl_bot hc)) }, { apply ha.1, rw eq_bot_iff, apply le_trans (le_inf _ hac) hc.disjoint.le_bot, rw [← subtype.coe_le_coe, subtype.coe_mk], exact le_Sup ⟨ha.of_is_atom_coe_Iic, a.2⟩ } end, λ _, and.left⟩⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem complemented_lattice_of_Sup_atoms_eq_top (h : Sup {a : α | is_atom a} = ⊤) : complemented_lattice α := ⟨λ b, begin obtain ⟨s, ⟨s_ind, b_inf_Sup_s, s_atoms⟩, s_max⟩ := zorn_subset {s : set α | complete_lattice.set_independent s ∧ b ⊓ Sup s = ⊥ ∧ ∀ a ∈ s, is_atom a} _, { refine ⟨Sup s, disjoint_iff.mpr b_inf_Sup_s, codisjoint_iff_le_sup.mpr $ h.symm.trans_le $ Sup_le_iff.2 $ λ a ha, _⟩, rw ← inf_eq_left, refine (ha.le_iff.mp inf_le_left).resolve_left (λ con, ha.1 _), rw [eq_bot_iff, ← con], refine le_inf (le_refl a) ((le_Sup _).trans le_sup_right), rw ← disjoint_iff at *, have a_dis_Sup_s : disjoint a (Sup s) := con.mono_right le_sup_right, rw ← s_max (s ∪ {a}) ⟨λ x hx, _, ⟨_, λ x hx, _⟩⟩ (set.subset_union_left _ _), { exact set.mem_union_right _ (set.mem_singleton _) }, { rw [set.mem_union, set.mem_singleton_iff] at hx, by_cases xa : x = a, { simp only [xa, set.mem_singleton, set.insert_diff_of_mem, set.union_singleton], exact con.mono_right (le_trans (Sup_le_Sup (set.diff_subset s {a})) le_sup_right) }, { have h : (s ∪ {a}) \ {x} = (s \ {x}) ∪ {a}, { simp only [set.union_singleton], rw set.insert_diff_of_not_mem, rw set.mem_singleton_iff, exact ne.symm xa }, rw [h, Sup_union, Sup_singleton], apply (s_ind (hx.resolve_right xa)).disjoint_sup_right_of_disjoint_sup_left (a_dis_Sup_s.mono_right _).symm, rw [← Sup_insert, set.insert_diff_singleton, set.insert_eq_of_mem (hx.resolve_right xa)] } }, { rw [Sup_union, Sup_singleton, ← disjoint_iff], exact b_inf_Sup_s.disjoint_sup_right_of_disjoint_sup_left con.symm }, { rw [set.mem_union, set.mem_singleton_iff] at hx, cases hx, { exact s_atoms x hx }, { rw hx, exact ha } } }, { intros c hc1 hc2, refine ⟨⋃₀ c, ⟨complete_lattice.independent_sUnion_of_directed hc2.directed_on (λ s hs, (hc1 hs).1), _, λ a ha, _⟩, λ _, set.subset_sUnion_of_mem⟩, { rw [Sup_sUnion, ← Sup_image, inf_Sup_eq_of_directed_on, supr_eq_bot], { intro i, rw supr_eq_bot, intro hi, obtain ⟨x, xc, rfl⟩ := (set.mem_image _ _ _).1 hi, exact (hc1 xc).2.1 }, { rw directed_on_image, refine hc2.directed_on.mono (λ s t, Sup_le_Sup) } }, { rcases set.mem_sUnion.1 ha with ⟨s, sc, as⟩, exact (hc1 sc).2.2 a as } } end⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem complemented_lattice_of_is_atomistic [is_atomistic α] : complemented_lattice α := complemented_lattice_of_Sup_atoms_eq_top Sup_atoms_eq_top theorem complemented_lattice_iff_is_atomistic : complemented_lattice α ↔ is_atomistic α := begin split; introsI, { exact is_atomistic_of_complemented_lattice }, { exact complemented_lattice_of_is_atomistic } end end
3323e647a03fd2e6ebcd3b4ec8ba81974e1d5f58
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/algebra/classes.lean
bb00f6202878646f5c3faf0d30aad3afaaba7608
[]
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
12,155
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.logic import Mathlib.Lean3Lib.init.data.ordering.basic universes u v l namespace Mathlib class is_symm_op (α : Type u) (β : outParam (Type v)) (op : α → α → β) where symm_op : ∀ (a b : α), op a b = op b a class is_commutative (α : Type u) (op : α → α → α) where comm : ∀ (a b : α), op a b = op b a protected instance is_symm_op_of_is_commutative (α : Type u) (op : α → α → α) [is_commutative α op] : is_symm_op α α op := is_symm_op.mk is_commutative.comm class is_associative (α : Type u) (op : α → α → α) where assoc : ∀ (a b c : α), op (op a b) c = op a (op b c) class is_left_id (α : Type u) (op : α → α → α) (o : outParam α) where left_id : ∀ (a : α), op o a = a class is_right_id (α : Type u) (op : α → α → α) (o : outParam α) where right_id : ∀ (a : α), op a o = a class is_left_null (α : Type u) (op : α → α → α) (o : outParam α) where left_null : ∀ (a : α), op o a = o class is_right_null (α : Type u) (op : α → α → α) (o : outParam α) where right_null : ∀ (a : α), op a o = o class is_left_cancel (α : Type u) (op : α → α → α) where left_cancel : ∀ (a b c : α), op a b = op a c → b = c class is_right_cancel (α : Type u) (op : α → α → α) where right_cancel : ∀ (a b c : α), op a b = op c b → a = c class is_idempotent (α : Type u) (op : α → α → α) where idempotent : ∀ (a : α), op a a = a class is_left_distrib (α : Type u) (op₁ : α → α → α) (op₂ : outParam (α → α → α)) where left_distrib : ∀ (a b c : α), op₁ a (op₂ b c) = op₂ (op₁ a b) (op₁ a c) class is_right_distrib (α : Type u) (op₁ : α → α → α) (op₂ : outParam (α → α → α)) where right_distrib : ∀ (a b c : α), op₁ (op₂ a b) c = op₂ (op₁ a c) (op₁ b c) class is_left_inv (α : Type u) (op : α → α → α) (inv : outParam (α → α)) (o : outParam α) where left_inv : ∀ (a : α), op (inv a) a = o class is_right_inv (α : Type u) (op : α → α → α) (inv : outParam (α → α)) (o : outParam α) where right_inv : ∀ (a : α), op a (inv a) = o class is_cond_left_inv (α : Type u) (op : α → α → α) (inv : outParam (α → α)) (o : outParam α) (p : outParam (α → Prop)) where left_inv : ∀ (a : α), p a → op (inv a) a = o class is_cond_right_inv (α : Type u) (op : α → α → α) (inv : outParam (α → α)) (o : outParam α) (p : outParam (α → Prop)) where right_inv : ∀ (a : α), p a → op a (inv a) = o class is_distinct (α : Type u) (a : α) (b : α) where distinct : a ≠ b /- -- The following type class doesn't seem very useful, a regular simp lemma should work for this. -- The following type class doesn't seem very useful, a regular simp lemma should work for this. class is_inv (α : Type u) (β : Type v) (f : α → β) (g : out β → α) : Prop := (inv : ∀ a, g (f a) = a) -- The following one can also be handled using a regular simp lemma -- The following one can also be handled using a regular simp lemma class is_idempotent (α : Type u) (f : α → α) : Prop := (idempotent : ∀ a, f (f a) = f a) -/ /-- `is_irrefl X r` means the binary relation `r` on `X` is irreflexive (that is, `r x x` never holds). -/ class is_irrefl (α : Type u) (r : α → α → Prop) where irrefl : ∀ (a : α), ¬r a a /-- `is_refl X r` means the binary relation `r` on `X` is reflexive. -/ class is_refl (α : Type u) (r : α → α → Prop) where refl : ∀ (a : α), r a a /-- `is_symm X r` means the binary relation `r` on `X` is symmetric. -/ class is_symm (α : Type u) (r : α → α → Prop) where symm : ∀ (a b : α), r a b → r b a /-- The opposite of a symmetric relation is symmetric. -/ protected instance is_symm_op_of_is_symm (α : Type u) (r : α → α → Prop) [is_symm α r] : is_symm_op α Prop r := is_symm_op.mk fun (a b : α) => propext { mp := is_symm.symm a b, mpr := is_symm.symm b a } /-- `is_asymm X r` means that the binary relation `r` on `X` is asymmetric, that is, `r a b → ¬ r b a`. -/ class is_asymm (α : Type u) (r : α → α → Prop) where asymm : ∀ (a b : α), r a b → ¬r b a /-- `is_antisymm X r` means the binary relation `r` on `X` is antisymmetric. -/ class is_antisymm (α : Type u) (r : α → α → Prop) where antisymm : ∀ (a b : α), r a b → r b a → a = b /-- `is_trans X r` means the binary relation `r` on `X` is transitive. -/ class is_trans (α : Type u) (r : α → α → Prop) where trans : ∀ (a b c : α), r a b → r b c → r a c /-- `is_total X r` means that the binary relation `r` on `X` is total, that is, that for any `x y : X` we have `r x y` or `r y x`.-/ class is_total (α : Type u) (r : α → α → Prop) where total : ∀ (a b : α), r a b ∨ r b a /-- `is_preorder X r` means that the binary relation `r` on `X` is a pre-order, that is, reflexive and transitive. -/ class is_preorder (α : Type u) (r : α → α → Prop) extends is_refl α r, is_trans α r where /-- `is_total_preorder X r` means that the binary relation `r` on `X` is total and a preorder. -/ class is_total_preorder (α : Type u) (r : α → α → Prop) extends is_trans α r, is_total α r where /-- Every total pre-order is a pre-order. -/ protected instance is_total_preorder_is_preorder (α : Type u) (r : α → α → Prop) [s : is_total_preorder α r] : is_preorder α r := is_preorder.mk class is_partial_order (α : Type u) (r : α → α → Prop) extends is_antisymm α r, is_preorder α r where class is_linear_order (α : Type u) (r : α → α → Prop) extends is_total α r, is_partial_order α r where class is_equiv (α : Type u) (r : α → α → Prop) extends is_symm α r, is_preorder α r where class is_per (α : Type u) (r : α → α → Prop) extends is_symm α r, is_trans α r where class is_strict_order (α : Type u) (r : α → α → Prop) extends is_trans α r, is_irrefl α r where class is_incomp_trans (α : Type u) (lt : α → α → Prop) where incomp_trans : ∀ (a b c : α), ¬lt a b ∧ ¬lt b a → ¬lt b c ∧ ¬lt c b → ¬lt a c ∧ ¬lt c a class is_strict_weak_order (α : Type u) (lt : α → α → Prop) extends is_incomp_trans α lt, is_strict_order α lt where class is_trichotomous (α : Type u) (lt : α → α → Prop) where trichotomous : ∀ (a b : α), lt a b ∨ a = b ∨ lt b a class is_strict_total_order (α : Type u) (lt : α → α → Prop) extends is_strict_weak_order α lt, is_trichotomous α lt where protected instance eq_is_equiv (α : Type u) : is_equiv α Eq := is_equiv.mk theorem irrefl {α : Type u} {r : α → α → Prop} [is_irrefl α r] (a : α) : ¬r a a := is_irrefl.irrefl a theorem refl {α : Type u} {r : α → α → Prop} [is_refl α r] (a : α) : r a a := is_refl.refl a theorem trans {α : Type u} {r : α → α → Prop} [is_trans α r] {a : α} {b : α} {c : α} : r a b → r b c → r a c := is_trans.trans a b c theorem symm {α : Type u} {r : α → α → Prop} [is_symm α r] {a : α} {b : α} : r a b → r b a := is_symm.symm a b theorem antisymm {α : Type u} {r : α → α → Prop} [is_antisymm α r] {a : α} {b : α} : r a b → r b a → a = b := is_antisymm.antisymm a b theorem asymm {α : Type u} {r : α → α → Prop} [is_asymm α r] {a : α} {b : α} : r a b → ¬r b a := is_asymm.asymm a b theorem trichotomous {α : Type u} {r : α → α → Prop} [is_trichotomous α r] (a : α) (b : α) : r a b ∨ a = b ∨ r b a := is_trichotomous.trichotomous theorem incomp_trans {α : Type u} {r : α → α → Prop} [is_incomp_trans α r] {a : α} {b : α} {c : α} : ¬r a b ∧ ¬r b a → ¬r b c ∧ ¬r c b → ¬r a c ∧ ¬r c a := is_incomp_trans.incomp_trans a b c protected instance is_asymm_of_is_trans_of_is_irrefl {α : Type u} {r : α → α → Prop} [is_trans α r] [is_irrefl α r] : is_asymm α r := is_asymm.mk fun (a b : α) (h₁ : r a b) (h₂ : r b a) => absurd (trans h₁ h₂) (irrefl a) theorem irrefl_of {α : Type u} (r : α → α → Prop) [is_irrefl α r] (a : α) : ¬r a a := irrefl a theorem refl_of {α : Type u} (r : α → α → Prop) [is_refl α r] (a : α) : r a a := refl a theorem trans_of {α : Type u} (r : α → α → Prop) [is_trans α r] {a : α} {b : α} {c : α} : r a b → r b c → r a c := trans theorem symm_of {α : Type u} (r : α → α → Prop) [is_symm α r] {a : α} {b : α} : r a b → r b a := symm theorem asymm_of {α : Type u} (r : α → α → Prop) [is_asymm α r] {a : α} {b : α} : r a b → ¬r b a := asymm theorem total_of {α : Type u} (r : α → α → Prop) [is_total α r] (a : α) (b : α) : r a b ∨ r b a := is_total.total a b theorem trichotomous_of {α : Type u} (r : α → α → Prop) [is_trichotomous α r] (a : α) (b : α) : r a b ∨ a = b ∨ r b a := trichotomous theorem incomp_trans_of {α : Type u} (r : α → α → Prop) [is_incomp_trans α r] {a : α} {b : α} {c : α} : ¬r a b ∧ ¬r b a → ¬r b c ∧ ¬r c b → ¬r a c ∧ ¬r c a := incomp_trans namespace strict_weak_order def equiv {α : Type u} {r : α → α → Prop} (a : α) (b : α) := ¬r a b ∧ ¬r b a theorem erefl {α : Type u} {r : α → α → Prop} [is_strict_weak_order α r] (a : α) : equiv a a := { left := irrefl a, right := irrefl a } theorem esymm {α : Type u} {r : α → α → Prop} [is_strict_weak_order α r] {a : α} {b : α} : equiv a b → equiv b a := sorry theorem etrans {α : Type u} {r : α → α → Prop} [is_strict_weak_order α r] {a : α} {b : α} {c : α} : equiv a b → equiv b c → equiv a c := incomp_trans theorem not_lt_of_equiv {α : Type u} {r : α → α → Prop} [is_strict_weak_order α r] {a : α} {b : α} : equiv a b → ¬r a b := fun (h : equiv a b) => and.left h theorem not_lt_of_equiv' {α : Type u} {r : α → α → Prop} [is_strict_weak_order α r] {a : α} {b : α} : equiv a b → ¬r b a := fun (h : equiv a b) => and.right h protected instance is_equiv {α : Type u} {r : α → α → Prop} [is_strict_weak_order α r] : is_equiv α equiv := is_equiv.mk /- Notation for the equivalence relation induced by lt -/ end strict_weak_order theorem is_strict_weak_order_of_is_total_preorder {α : Type u} {le : α → α → Prop} {lt : α → α → Prop} [DecidableRel le] [s : is_total_preorder α le] (h : ∀ (a b : α), lt a b ↔ ¬le b a) : is_strict_weak_order α lt := is_strict_weak_order.mk theorem lt_of_lt_of_incomp {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [DecidableRel lt] {a : α} {b : α} {c : α} : lt a b → ¬lt b c ∧ ¬lt c b → lt a c := sorry theorem lt_of_incomp_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [DecidableRel lt] {a : α} {b : α} {c : α} : ¬lt a b ∧ ¬lt b a → lt b c → lt a c := sorry theorem eq_of_incomp {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a : α} {b : α} : ¬lt a b ∧ ¬lt b a → a = b := sorry theorem eq_of_eqv_lt {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a : α} {b : α} : strict_weak_order.equiv a b → a = b := eq_of_incomp theorem incomp_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a : α) (b : α) : ¬lt a b ∧ ¬lt b a ↔ a = b := { mp := eq_of_incomp, mpr := fun (hab : a = b) => hab ▸ { left := irrefl_of lt a, right := irrefl_of lt a } } theorem eqv_lt_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a : α) (b : α) : strict_weak_order.equiv a b ↔ a = b := incomp_iff_eq a b theorem not_lt_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_order α lt] {a : α} {b : α} : lt a b → ¬lt b a := fun (h₁ : lt a b) (h₂ : lt b a) => absurd (trans_of lt h₁ h₂) (irrefl_of lt a)
9f8dfa7f81fdc146c4224ef83964fdfe71a26e7c
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/one2.lean
340c5985f5b3d179d93aafe2a4d7b1e8e9c1b2ad
[ "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
404
lean
import data.num inductive one.{l} : Type.{l} := unit : one inductive pone : Type.{0} := unit : pone inductive two.{l} : Type.{max 1 l} := | o : two | u : two inductive wrap.{l} : Type.{max 1 l} := mk : true → wrap inductive wrap2.{l} (A : Type.{l}) : Type.{max 1 l} := mk : A → wrap2 A set_option pp.universes true check @one.rec check @pone.rec check @two.rec check @wrap.rec check @wrap2.rec
aff08cec5c25de5e366bea076a0bd203b753003a
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/analysis/convex/cone.lean
36d637411aeba6e7d7661a9a117428493a6bf971
[ "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
23,832
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Frédéric Dupuis -/ import linear_algebra.linear_pmap import analysis.convex.basic import order.zorn /-! # Convex cones In a vector space `E` over `ℝ`, we define a convex cone as a subset `s` such that `a • x + b • y ∈ s` whenever `x, y ∈ s` and `a, b > 0`. We prove that convex cones form a `complete_lattice`, and define their images (`convex_cone.map`) and preimages (`convex_cone.comap`) under linear maps. We define pointed, blunt, flat and salient cones, and prove the correspondence between convex cones and ordered semimodules. We also define `convex.to_cone` to be the minimal cone that includes a given convex set. ## Main statements We prove two extension theorems: * `riesz_extension`: [M. Riesz extension theorem](https://en.wikipedia.org/wiki/M._Riesz_extension_theorem) says that if `s` is a convex cone in a real vector space `E`, `p` is a submodule of `E` such that `p + s = E`, and `f` is a linear function `p → ℝ` which is nonnegative on `p ∩ s`, then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. * `exists_extension_of_le_sublinear`: Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`, then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x` for all `x` ## Implementation notes While `convex` is a predicate on sets, `convex_cone` is a bundled convex cone. ## References * https://en.wikipedia.org/wiki/Convex_cone ## TODO * Define the dual cone. -/ universes u v open set linear_map open_locale classical variables (E : Type*) [add_comm_group E] [vector_space ℝ E] {F : Type*} [add_comm_group F] [vector_space ℝ F] {G : Type*} [add_comm_group G] [vector_space ℝ G] /-! ### Definition of `convex_cone` and basic properties -/ /-- A convex cone is a subset `s` of a vector space over `ℝ` such that `a • x + b • y ∈ s` whenever `a, b > 0` and `x, y ∈ s`. -/ structure convex_cone := (carrier : set E) (smul_mem' : ∀ ⦃c : ℝ⦄, 0 < c → ∀ ⦃x : E⦄, x ∈ carrier → c • x ∈ carrier) (add_mem' : ∀ ⦃x⦄ (hx : x ∈ carrier) ⦃y⦄ (hy : y ∈ carrier), x + y ∈ carrier) variable {E} namespace convex_cone variables (S T : convex_cone E) instance : has_coe (convex_cone E) (set E) := ⟨convex_cone.carrier⟩ instance : has_mem E (convex_cone E) := ⟨λ m S, m ∈ S.carrier⟩ instance : has_le (convex_cone E) := ⟨λ S T, S.carrier ⊆ T.carrier⟩ instance : has_lt (convex_cone E) := ⟨λ S T, S.carrier ⊂ T.carrier⟩ @[simp, norm_cast] lemma mem_coe {x : E} : x ∈ (S : set E) ↔ x ∈ S := iff.rfl @[simp] lemma mem_mk {s : set E} {h₁ h₂ x} : x ∈ mk s h₁ h₂ ↔ x ∈ s := iff.rfl /-- Two `convex_cone`s are equal if the underlying subsets are equal. -/ theorem ext' {S T : convex_cone E} (h : (S : set E) = T) : S = T := by cases S; cases T; congr' /-- Two `convex_cone`s are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {S T : convex_cone E} : (S : set E) = T ↔ S = T := ⟨ext', λ h, h ▸ rfl⟩ /-- Two `convex_cone`s are equal if they have the same elements. -/ @[ext] theorem ext {S T : convex_cone E} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h lemma smul_mem {c : ℝ} {x : E} (hc : 0 < c) (hx : x ∈ S) : c • x ∈ S := S.smul_mem' hc hx lemma add_mem ⦃x⦄ (hx : x ∈ S) ⦃y⦄ (hy : y ∈ S) : x + y ∈ S := S.add_mem' hx hy lemma smul_mem_iff {c : ℝ} (hc : 0 < c) {x : E} : c • x ∈ S ↔ x ∈ S := ⟨λ h, by simpa only [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul] using S.smul_mem (inv_pos.2 hc) h, λ h, S.smul_mem hc h⟩ lemma convex : convex (S : set E) := convex_iff_forall_pos.2 $ λ x y hx hy a b ha hb hab, S.add_mem (S.smul_mem ha hx) (S.smul_mem hb hy) instance : has_inf (convex_cone E) := ⟨λ S T, ⟨S ∩ T, λ c hc x hx, ⟨S.smul_mem hc hx.1, T.smul_mem hc hx.2⟩, λ x hx y hy, ⟨S.add_mem hx.1 hy.1, T.add_mem hx.2 hy.2⟩⟩⟩ lemma coe_inf : ((S ⊓ T : convex_cone E) : set E) = ↑S ∩ ↑T := rfl lemma mem_inf {x} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl instance : has_Inf (convex_cone E) := ⟨λ S, ⟨⋂ s ∈ S, ↑s, λ c hc x hx, mem_bInter $ λ s hs, s.smul_mem hc $ by apply mem_bInter_iff.1 hx s hs, λ x hx y hy, mem_bInter $ λ s hs, s.add_mem (by apply mem_bInter_iff.1 hx s hs) (by apply mem_bInter_iff.1 hy s hs)⟩⟩ lemma mem_Inf {x : E} {S : set (convex_cone E)} : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := mem_bInter_iff instance : has_bot (convex_cone E) := ⟨⟨∅, λ c hc x, false.elim, λ x, false.elim⟩⟩ lemma mem_bot (x : E) : x ∈ (⊥ : convex_cone E) = false := rfl instance : has_top (convex_cone E) := ⟨⟨univ, λ c hc x hx, mem_univ _, λ x hx y hy, mem_univ _⟩⟩ lemma mem_top (x : E) : x ∈ (⊤ : convex_cone E) := mem_univ x instance : complete_lattice (convex_cone E) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x, false.elim, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, Sup := λ s, Inf {T | ∀ S ∈ s, S ≤ T}, le_sup_left := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.1 hx, le_sup_right := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.2 hx, sup_le := λ a b c ha hb x hx, mem_Inf.1 hx c ⟨ha, hb⟩, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, le_Sup := λ s p hs x hx, mem_Inf.2 $ λ t ht, ht p hs hx, Sup_le := λ s p hs x hx, mem_Inf.1 hx p hs, le_Inf := λ s a ha x hx, mem_Inf.2 $ λ t ht, ha t ht hx, Inf_le := λ s a ha x hx, mem_Inf.1 hx _ ha, .. partial_order.lift (coe : convex_cone E → set E) (λ a b, ext') } instance : inhabited (convex_cone E) := ⟨⊥⟩ /-- The image of a convex cone under an `ℝ`-linear map is a convex cone. -/ def map (f : E →ₗ[ℝ] F) (S : convex_cone E) : convex_cone F := { carrier := f '' S, smul_mem' := λ c hc y ⟨x, hx, hy⟩, hy ▸ f.map_smul c x ▸ mem_image_of_mem f (S.smul_mem hc hx), add_mem' := λ y₁ ⟨x₁, hx₁, hy₁⟩ y₂ ⟨x₂, hx₂, hy₂⟩, hy₁ ▸ hy₂ ▸ f.map_add x₁ x₂ ▸ mem_image_of_mem f (S.add_mem hx₁ hx₂) } lemma map_map (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone E) : (S.map f).map g = S.map (g.comp f) := ext' $ image_image g f S @[simp] lemma map_id : S.map linear_map.id = S := ext' $ image_id _ /-- The preimage of a convex cone under an `ℝ`-linear map is a convex cone. -/ def comap (f : E →ₗ[ℝ] F) (S : convex_cone F) : convex_cone E := { carrier := f ⁻¹' S, smul_mem' := λ c hc x hx, by { rw [mem_preimage, f.map_smul c], exact S.smul_mem hc hx }, add_mem' := λ x hx y hy, by { rw [mem_preimage, f.map_add], exact S.add_mem hx hy } } @[simp] lemma comap_id : S.comap linear_map.id = S := ext' preimage_id lemma comap_comap (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone G) : (S.comap g).comap f = S.comap (g.comp f) := ext' $ preimage_comp.symm @[simp] lemma mem_comap {f : E →ₗ[ℝ] F} {S : convex_cone F} {x : E} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl /-- Constructs an ordered semimodule given an `ordered_add_comm_group`, a cone, and a proof that the order relation is the one defined by the cone. -/ def to_ordered_semimodule {M : Type*} [ordered_add_comm_group M] [semimodule ℝ M] (S : convex_cone M) (h : ∀ x y : M, x ≤ y ↔ y - x ∈ S) : ordered_semimodule ℝ M := { smul_lt_smul_of_pos := begin intros x y z xy hz, refine lt_of_le_of_ne _ _, { rw [h (z • x) (z • y), ←smul_sub z y x], exact smul_mem S hz ((h x y).mp (le_of_lt xy)) }, { intro H, have H' := congr_arg (λ r, (1/z) • r) H, refine (ne_of_lt xy) _, field_simp [smul_smul, div_self ((ne_of_lt hz).symm)] at H', exact H' }, end, lt_of_smul_lt_smul_of_nonneg := begin intros x y z hxy hz, refine lt_of_le_of_ne _ _, { rw [h x y], have hz' : 0 < z, { refine lt_of_le_of_ne hz _, rintro rfl, rw [zero_smul, zero_smul] at hxy, exact lt_irrefl 0 hxy }, have hz'' : 0 < 1/z := div_pos (by linarith) hz', have hxy' := (h (z • x) (z • y)).mp (le_of_lt hxy), rw [←smul_sub z y x] at hxy', have hxy'' := smul_mem S hz'' hxy', field_simp [smul_smul, div_self ((ne_of_lt hz').symm)] at hxy'', exact hxy'' }, { rintro rfl, exact lt_irrefl (z • x) hxy } end, } /-! ### Convex cones with extra properties -/ /-- A convex cone is pointed if it includes 0. -/ def pointed (S : convex_cone E) : Prop := (0 : E) ∈ S /-- A convex cone is blunt if it doesn't include 0. -/ def blunt (S : convex_cone E) : Prop := (0 : E) ∉ S /-- A convex cone is flat if it contains some nonzero vector `x` and its opposite `-x`. -/ def flat (S : convex_cone E) : Prop := ∃ x ∈ S, x ≠ (0 : E) ∧ -x ∈ S /-- A convex cone is salient if it doesn't include `x` and `-x` for any nonzero `x`. -/ def salient (S : convex_cone E) : Prop := ∀ x ∈ S, x ≠ (0 : E) → -x ∉ S lemma pointed_iff_not_blunt (S : convex_cone E) : pointed S ↔ ¬blunt S := ⟨λ h₁ h₂, h₂ h₁, λ h, not_not.mp h⟩ lemma salient_iff_not_flat (S : convex_cone E) : salient S ↔ ¬flat S := begin split, { rintros h₁ ⟨x, xs, H₁, H₂⟩, exact h₁ x xs H₁ H₂ }, { intro h, unfold flat at h, push_neg at h, exact h } end /-- A blunt cone (one not containing 0) is always salient. -/ lemma salient_of_blunt (S : convex_cone E) : blunt S → salient S := begin intro h₁, rw [salient_iff_not_flat], intro h₂, obtain ⟨x, xs, H₁, H₂⟩ := h₂, have hkey : (0 : E) ∈ S := by rw [(show 0 = x + (-x), by simp)]; exact add_mem S xs H₂, exact h₁ hkey, end /-- A pointed convex cone defines a preorder. -/ def to_preorder (S : convex_cone E) (h₁ : pointed S) : preorder E := { le := λ x y, y - x ∈ S, le_refl := λ x, by change x - x ∈ S; rw [sub_self x]; exact h₁, le_trans := λ x y z xy zy, by simp [(show z - x = z - y + (y - x), by abel), add_mem S zy xy] } /-- A pointed and salient cone defines a partial order. -/ def to_partial_order (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) : partial_order E := { le_antisymm := begin intros a b ab ba, by_contradiction h, have h' : b - a ≠ 0 := λ h'', h (eq_of_sub_eq_zero h'').symm, have H := h₂ (b-a) ab h', rw [neg_sub b a] at H, exact H ba, end, ..to_preorder S h₁ } /-- A pointed and salient cone defines an `ordered_add_comm_group`. -/ def to_ordered_add_comm_group (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) : ordered_add_comm_group E := { add_le_add_left := begin intros a b hab c, change c + b - (c + a) ∈ S, rw [add_sub_add_left_eq_sub], exact hab, end, ..to_partial_order S h₁ h₂, ..show add_comm_group E, by apply_instance } /-! ### Positive cone of an ordered semimodule -/ section positive_cone variables (M : Type*) [ordered_add_comm_group M] [ordered_semimodule ℝ M] /-- The positive cone is the convex cone formed by the set of nonnegative elements in an ordered semimodule. -/ def positive_cone : convex_cone M := { carrier := {x | 0 ≤ x}, smul_mem' := begin intros c hc x hx, have := smul_le_smul_of_nonneg (show 0 ≤ x, by exact hx) (le_of_lt hc), have h' : c • (0 : M) = 0, { simp only [smul_zero] }, rwa [h'] at this end, add_mem' := λ x hx y hy, add_nonneg (show 0 ≤ x, by exact hx) (show 0 ≤ y, by exact hy) } /-- The positive cone of an ordered semimodule is always salient. -/ lemma salient_of_positive_cone : salient (positive_cone M) := begin intros x xs hx hx', have := calc 0 < x : lt_of_le_of_ne xs hx.symm ... ≤ x + (-x) : (le_add_iff_nonneg_right x).mpr hx' ... = 0 : by rw [tactic.ring.add_neg_eq_sub x x]; exact sub_self x, exact lt_irrefl 0 this, end /-- The positive cone of an ordered semimodule is always pointed. -/ lemma pointed_of_positive_cone : pointed (positive_cone M) := le_refl 0 end positive_cone end convex_cone /-! ### Cone over a convex set -/ namespace convex /-- The set of vectors proportional to those in a convex set forms a convex cone. -/ def to_cone (s : set E) (hs : convex s) : convex_cone E := begin apply convex_cone.mk (⋃ c > 0, (c : ℝ) • s); simp only [mem_Union, mem_smul_set], { rintros c c_pos _ ⟨c', c'_pos, x, hx, rfl⟩, exact ⟨c * c', mul_pos c_pos c'_pos, x, hx, (smul_smul _ _ _).symm⟩ }, { rintros _ ⟨cx, cx_pos, x, hx, rfl⟩ _ ⟨cy, cy_pos, y, hy, rfl⟩, have : 0 < cx + cy, from add_pos cx_pos cy_pos, refine ⟨_, this, _, convex_iff_div.1 hs hx hy (le_of_lt cx_pos) (le_of_lt cy_pos) this, _⟩, simp only [smul_add, smul_smul, mul_div_assoc', mul_div_cancel_left _ (ne_of_gt this)] } end variables {s : set E} (hs : convex s) {x : E} lemma mem_to_cone : x ∈ hs.to_cone s ↔ ∃ (c > 0) (y ∈ s), (c : ℝ) • y = x := by simp only [to_cone, convex_cone.mem_mk, mem_Union, mem_smul_set, eq_comm, exists_prop] lemma mem_to_cone' : x ∈ hs.to_cone s ↔ ∃ c > 0, (c : ℝ) • x ∈ s := begin refine hs.mem_to_cone.trans ⟨_, _⟩, { rintros ⟨c, hc, y, hy, rfl⟩, exact ⟨c⁻¹, inv_pos.2 hc, by rwa [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]⟩ }, { rintros ⟨c, hc, hcx⟩, exact ⟨c⁻¹, inv_pos.2 hc, _, hcx, by rw [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]⟩ } end lemma subset_to_cone : s ⊆ hs.to_cone s := λ x hx, hs.mem_to_cone'.2 ⟨1, zero_lt_one, by rwa one_smul⟩ /-- `hs.to_cone s` is the least cone that includes `s`. -/ lemma to_cone_is_least : is_least { t : convex_cone E | s ⊆ t } (hs.to_cone s) := begin refine ⟨hs.subset_to_cone, λ t ht x hx, _⟩, rcases hs.mem_to_cone.1 hx with ⟨c, hc, y, hy, rfl⟩, exact t.smul_mem hc (ht hy) end lemma to_cone_eq_Inf : hs.to_cone s = Inf { t : convex_cone E | s ⊆ t } := hs.to_cone_is_least.is_glb.Inf_eq.symm end convex lemma convex_hull_to_cone_is_least (s : set E) : is_least {t : convex_cone E | s ⊆ t} ((convex_convex_hull s).to_cone _) := begin convert (convex_convex_hull s).to_cone_is_least, ext t, exact ⟨λ h, convex_hull_min h t.convex, λ h, subset.trans (subset_convex_hull s) h⟩ end lemma convex_hull_to_cone_eq_Inf (s : set E) : (convex_convex_hull s).to_cone _ = Inf {t : convex_cone E | s ⊆ t} := (convex_hull_to_cone_is_least s).is_glb.Inf_eq.symm /-! ### M. Riesz extension theorem Given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. We prove this theorem using Zorn's lemma. `riesz_extension.step` is the main part of the proof. It says that if the domain `p` of `f` is not the whole space, then `f` can be extended to a larger subspace `p ⊔ span ℝ {y}` without breaking the non-negativity condition. In `riesz_extension.exists_top` we use Zorn's lemma to prove that we can extend `f` to a linear map `g` on `⊤ : submodule E`. Mathematically this is the same as a linear map on `E` but in Lean `⊤ : submodule E` is isomorphic but is not equal to `E`. In `riesz_extension` we use this isomorphism to prove the theorem. -/ namespace riesz_extension open submodule variables (s : convex_cone E) (f : linear_pmap ℝ E ℝ) /-- Induction step in M. Riesz extension theorem. Given a convex cone `s` in a vector space `E`, a partially defined linear map `f : f.domain → ℝ`, assume that `f` is nonnegative on `f.domain ∩ p` and `p + s = E`. If `f` is not defined on the whole `E`, then we can extend it to a larger submodule without breaking the non-negativity condition. -/ lemma step (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) (hdom : f.domain ≠ ⊤) : ∃ g, f < g ∧ ∀ x : g.domain, (x : E) ∈ s → 0 ≤ g x := begin rcases exists_of_lt (lt_top_iff_ne_top.2 hdom) with ⟨y, hy', hy⟩, clear hy', obtain ⟨c, le_c, c_le⟩ : ∃ c, (∀ x : f.domain, -(x:E) - y ∈ s → f x ≤ c) ∧ (∀ x : f.domain, (x:E) + y ∈ s → c ≤ f x), { set Sp := f '' {x : f.domain | (x:E) + y ∈ s}, set Sn := f '' {x : f.domain | -(x:E) - y ∈ s}, suffices : (upper_bounds Sn ∩ lower_bounds Sp).nonempty, by simpa only [set.nonempty, upper_bounds, lower_bounds, ball_image_iff] using this, refine exists_between_of_forall_le (nonempty.image f _) (nonempty.image f (dense y)) _, { rcases (dense (-y)) with ⟨x, hx⟩, rw [← neg_neg x, coe_neg] at hx, exact ⟨_, hx⟩ }, rintros a ⟨xn, hxn, rfl⟩ b ⟨xp, hxp, rfl⟩, have := s.add_mem hxp hxn, rw [add_assoc, add_sub_cancel'_right, ← sub_eq_add_neg, ← coe_sub] at this, replace := nonneg _ this, rwa [f.map_sub, sub_nonneg] at this }, have hy' : y ≠ 0, from λ hy₀, hy (hy₀.symm ▸ zero_mem _), refine ⟨f.sup (linear_pmap.mk_span_singleton y (-c) hy') _, _, _⟩, { refine linear_pmap.sup_h_of_disjoint _ _ (submodule.disjoint_span_singleton.2 _), exact (λ h, (hy h).elim) }, { refine lt_iff_le_not_le.2 ⟨f.left_le_sup _ _, λ H, _⟩, replace H := linear_pmap.domain_mono.monotone H, rw [linear_pmap.domain_sup, linear_pmap.domain_mk_span_singleton, sup_le_iff, span_le, singleton_subset_iff] at H, exact hy H.2 }, { rintros ⟨z, hz⟩ hzs, rcases mem_sup.1 hz with ⟨x, hx, y', hy', rfl⟩, rcases mem_span_singleton.1 hy' with ⟨r, rfl⟩, simp only [subtype.coe_mk] at hzs, rw [linear_pmap.sup_apply _ ⟨x, hx⟩ ⟨_, hy'⟩ ⟨_, hz⟩ rfl, linear_pmap.mk_span_singleton_apply, smul_neg, ← sub_eq_add_neg, sub_nonneg], rcases lt_trichotomy r 0 with hr|hr|hr, { have : -(r⁻¹ • x) - y ∈ s, by rwa [← s.smul_mem_iff (neg_pos.2 hr), smul_sub, smul_neg, neg_smul, neg_neg, smul_smul, mul_inv_cancel (ne_of_lt hr), one_smul, sub_eq_add_neg, neg_smul, neg_neg], replace := le_c (r⁻¹ • ⟨x, hx⟩) this, rwa [← mul_le_mul_left (neg_pos.2 hr), ← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul, neg_le_neg_iff, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel (ne_of_lt hr), one_mul] at this }, { subst r, simp only [zero_smul, add_zero] at hzs ⊢, apply nonneg, exact hzs }, { have : r⁻¹ • x + y ∈ s, by rwa [← s.smul_mem_iff hr, smul_add, smul_smul, mul_inv_cancel (ne_of_gt hr), one_smul], replace := c_le (r⁻¹ • ⟨x, hx⟩) this, rwa [← mul_le_mul_left hr, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel (ne_of_gt hr), one_mul] at this } } end theorem exists_top (p : linear_pmap ℝ E ℝ) (hp_nonneg : ∀ x : p.domain, (x : E) ∈ s → 0 ≤ p x) (hp_dense : ∀ y, ∃ x : p.domain, (x : E) + y ∈ s) : ∃ q ≥ p, q.domain = ⊤ ∧ ∀ x : q.domain, (x : E) ∈ s → 0 ≤ q x := begin replace hp_nonneg : p ∈ { p | _ }, by { rw mem_set_of_eq, exact hp_nonneg }, obtain ⟨q, hqs, hpq, hq⟩ := zorn.zorn_partial_order₀ _ _ _ hp_nonneg, { refine ⟨q, hpq, _, hqs⟩, contrapose! hq, rcases step s q hqs _ hq with ⟨r, hqr, hr⟩, { exact ⟨r, hr, le_of_lt hqr, ne_of_gt hqr⟩ }, { exact λ y, let ⟨x, hx⟩ := hp_dense y in ⟨of_le hpq.left x, hx⟩ } }, { intros c hcs c_chain y hy, clear hp_nonneg hp_dense p, have cne : c.nonempty := ⟨y, hy⟩, refine ⟨linear_pmap.Sup c c_chain.directed_on, _, λ _, linear_pmap.le_Sup c_chain.directed_on⟩, rintros ⟨x, hx⟩ hxs, have hdir : directed_on (≤) (linear_pmap.domain '' c), from directed_on_image.2 (c_chain.directed_on.mono linear_pmap.domain_mono.monotone), rcases (mem_Sup_of_directed (cne.image _) hdir).1 hx with ⟨_, ⟨f, hfc, rfl⟩, hfx⟩, have : f ≤ linear_pmap.Sup c c_chain.directed_on, from linear_pmap.le_Sup _ hfc, convert ← hcs hfc ⟨x, hfx⟩ hxs, apply this.2, refl } end end riesz_extension /-- M. Riesz extension theorem: given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. -/ theorem riesz_extension (s : convex_cone E) (f : linear_pmap ℝ E ℝ) (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) : ∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x ∈ s, 0 ≤ g x) := begin rcases riesz_extension.exists_top s f nonneg dense with ⟨⟨g_dom, g⟩, ⟨hpg, hfg⟩, htop, hgs⟩, clear hpg, refine ⟨g.comp (linear_equiv.of_top _ htop).symm, _, _⟩; simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.of_top_symm_apply], { exact λ x, (hfg (submodule.coe_mk _ _).symm).symm }, { exact λ x hx, hgs ⟨x, _⟩ hx } end /-- Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`, then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x` for all `x`. -/ theorem exists_extension_of_le_sublinear (f : linear_pmap ℝ E ℝ) (N : E → ℝ) (N_hom : ∀ (c : ℝ), 0 < c → ∀ x, N (c • x) = c * N x) (N_add : ∀ x y, N (x + y) ≤ N x + N y) (hf : ∀ x : f.domain, f x ≤ N x) : ∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x, g x ≤ N x) := begin let s : convex_cone (E × ℝ) := { carrier := {p : E × ℝ | N p.1 ≤ p.2 }, smul_mem' := λ c hc p hp, calc N (c • p.1) = c * N p.1 : N_hom c hc p.1 ... ≤ c * p.2 : mul_le_mul_of_nonneg_left hp (le_of_lt hc), add_mem' := λ x hx y hy, le_trans (N_add _ _) (add_le_add hx hy) }, obtain ⟨g, g_eq, g_nonneg⟩ := riesz_extension s ((-f).coprod (linear_map.id.to_pmap ⊤)) _ _; simp only [linear_pmap.coprod_apply, to_pmap_apply, id_apply, linear_pmap.neg_apply, ← sub_eq_neg_add, sub_nonneg, subtype.coe_mk] at *, replace g_eq : ∀ (x : f.domain) (y : ℝ), g (x, y) = y - f x, { intros x y, simpa only [subtype.coe_mk, subtype.coe_eta] using g_eq ⟨(x, y), ⟨x.2, trivial⟩⟩ }, { refine ⟨-g.comp (inl ℝ E ℝ), _, _⟩; simp only [neg_apply, inl_apply, comp_apply], { intro x, simp [g_eq x 0] }, { intro x, have A : (x, N x) = (x, 0) + (0, N x), by simp, have B := g_nonneg ⟨x, N x⟩ (le_refl (N x)), rw [A, map_add, ← neg_le_iff_add_nonneg] at B, have C := g_eq 0 (N x), simp only [submodule.coe_zero, f.map_zero, sub_zero] at C, rwa ← C } }, { exact λ x hx, le_trans (hf _) hx }, { rintros ⟨x, y⟩, refine ⟨⟨(0, N x - y), ⟨f.domain.zero_mem, trivial⟩⟩, _⟩, simp only [convex_cone.mem_mk, mem_set_of_eq, subtype.coe_mk, prod.fst_add, prod.snd_add, zero_add, sub_add_cancel] } end
d3fb7ece69aa932d0d4ceede373ef33c892f9fe9
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/nat/parity.lean
2e4b6c655747de06ad5b0eb8bda020554d6f6a22
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
10,106
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Parity. -/ -- TODO(Leo): remove after refactoring exit import data.nat.power logic.identities namespace nat open decidable definition even (n : nat) := n % 2 = 0 attribute [instance] definition decidable_even : ∀ n, decidable (even n) := take n, !nat.has_decidable_eq definition odd (n : nat) := ¬even n attribute [instance] definition decidable_odd : ∀ n, decidable (odd n) := take n, decidable_not lemma even_of_dvd {n} : 2 ∣ n → even n := mod_eq_zero_of_dvd lemma dvd_of_even {n} : even n → 2 ∣ n := dvd_of_mod_eq_zero lemma not_odd_zero : ¬ odd 0 := dec_trivial lemma even_zero : even 0 := dec_trivial lemma odd_one : odd 1 := dec_trivial lemma not_even_one : ¬ even 1 := dec_trivial lemma odd_eq_not_even (n : nat) : odd n = ¬ even n := rfl lemma odd_iff_not_even (n : nat) : odd n ↔ ¬ even n := !iff.refl lemma odd_of_not_even {n} : ¬ even n → odd n := suppose ¬ even n, iff.mpr !odd_iff_not_even this lemma even_of_not_odd {n} : ¬ odd n → even n := suppose ¬ odd n, not_not_elim (iff.mp (not_iff_not_of_iff !odd_iff_not_even) this) lemma not_odd_of_even {n} : even n → ¬ odd n := suppose even n, iff.mpr (not_iff_not_of_iff !odd_iff_not_even) (not_not_intro this) lemma not_even_of_odd {n} : odd n → ¬ even n := suppose odd n, iff.mp !odd_iff_not_even this lemma odd_succ_of_even {n} : even n → odd (succ n) := suppose even n, have n ≡ 0 [mod 2], from this, have n+1 ≡ 0+1 [mod 2], from add_mod_eq_add_mod_right 1 this, have h : n+1 ≡ 1 [mod 2], from this, by_contradiction (suppose ¬ odd (succ n), have n+1 ≡ 0 [mod 2], from even_of_not_odd this, have 1 ≡ 0 [mod 2], from eq.trans (eq.symm h) this, have 1 = 0, from this, by contradiction) lemma eq_1_of_ne_0_lt_2 : ∀ {n : nat}, n ≠ 0 → n < 2 → n = 1 | 0 h₁ h₂ := absurd rfl h₁ | 1 h₁ h₂ := rfl | (n+2) h₁ h₂ := absurd (lt_of_succ_lt_succ (lt_of_succ_lt_succ h₂)) !not_lt_zero lemma mod_eq_of_odd {n} : odd n → n % 2 = 1 := suppose odd n, have ¬ n % 2 = 0, from this, have n % 2 < 2, from mod_lt n dec_trivial, eq_1_of_ne_0_lt_2 `¬ n % 2 = 0` `n % 2 < 2` lemma odd_of_mod_eq {n} : n % 2 = 1 → odd n := suppose n % 2 = 1, by_contradiction (suppose ¬ odd n, have n % 2 = 0, from even_of_not_odd this, by rewrite this at *; contradiction) lemma even_succ_of_odd {n} : odd n → even (succ n) := suppose odd n, have n % 2 = 1 % 2, from mod_eq_of_odd this, have (n+1) % 2 = 2 % 2, from add_mod_eq_add_mod_right 1 this, by rewrite mod_self at this; exact this lemma odd_succ_succ_of_odd {n} : odd n → odd (succ (succ n)) := suppose odd n, odd_succ_of_even (even_succ_of_odd this) lemma even_succ_succ_of_even {n} : even n → even (succ (succ n)) := suppose even n, even_succ_of_odd (odd_succ_of_even this) lemma even_of_odd_succ {n} : odd (succ n) → even n := suppose odd (succ n), by_contradiction (suppose ¬ even n, have odd n, from odd_of_not_even this, have even (succ n), from even_succ_of_odd this, absurd this (not_even_of_odd `odd (succ n)`)) lemma odd_of_even_succ {n} : even (succ n) → odd n := suppose even (succ n), by_contradiction (suppose ¬ odd n, have even n, from even_of_not_odd this, have odd (succ n), from odd_succ_of_even this, absurd `even (succ n)` (not_even_of_odd this)) lemma even_of_even_succ_succ {n} : even (succ (succ n)) → even n := suppose even (n+2), even_of_odd_succ (odd_of_even_succ this) lemma odd_of_odd_succ_succ {n} : odd (succ (succ n)) → odd n := suppose odd (n+2), odd_of_even_succ (even_of_odd_succ this) lemma dvd_of_odd {n} : odd n → 2 ∣ n+1 := suppose odd n, dvd_of_even (even_succ_of_odd this) lemma odd_of_dvd {n} : 2 ∣ n+1 → odd n := suppose 2 ∣ n+1, odd_of_even_succ (even_of_dvd this) lemma even_two_mul : ∀ n, even (2 * n) := take n, even_of_dvd (dvd_mul_right 2 n) lemma odd_two_mul_plus_one : ∀ n, odd (2 * n + 1) := take n, odd_succ_of_even (even_two_mul n) lemma not_even_two_mul_plus_one : ∀ n, ¬ even (2 * n + 1) := take n, not_even_of_odd (odd_two_mul_plus_one n) lemma not_odd_two_mul : ∀ n, ¬ odd (2 * n) := take n, not_odd_of_even (even_two_mul n) lemma even_pred_of_odd : ∀ {n}, odd n → even (pred n) | 0 h := absurd h not_odd_zero | (n+1) h := even_of_odd_succ h lemma even_or_odd : ∀ n, even n ∨ odd n := λ n, by_cases (λ h : even n, or.inl h) (λ h : ¬ even n, or.inr (odd_of_not_even h)) lemma exists_of_even {n} : even n → ∃ k, n = 2*k := λ h, exists_eq_mul_right_of_dvd (dvd_of_even h) lemma exists_of_odd : ∀ {n}, odd n → ∃ k, n = 2*k + 1 | 0 h := absurd h not_odd_zero | (n+1) h := obtain k (hk : n = 2*k), from exists_of_even (even_of_odd_succ h), exists.intro k (by subst n) lemma even_of_exists {n} : (∃ k, n = 2 * k) → even n := suppose ∃ k, n = 2 * k, obtain k (hk : n = 2 * k), from this, have 2 ∣ n, by subst n; apply dvd_mul_right, even_of_dvd this lemma odd_of_exists {n} : (∃ k, n = 2 * k + 1) → odd n := assume h, by_contradiction (λ hn, have even n, from even_of_not_odd hn, have ∃ k, n = 2 * k, from exists_of_even this, obtain k₁ (hk₁ : n = 2 * k₁ + 1), from h, obtain k₂ (hk₂ : n = 2 * k₂), from this, have (2 * k₁ + 1) % 2 = (2 * k₂) % 2, by rewrite [-hk₁, -hk₂], begin rewrite [mul_mod_right at this, add.comm at this, add_mul_mod_self_left at this], contradiction end) lemma even_add_of_even_of_even {n m} : even n → even m → even (n+m) := suppose even n, suppose even m, obtain k₁ (hk₁ : n = 2 * k₁), from exists_of_even `even n`, obtain k₂ (hk₂ : m = 2 * k₂), from exists_of_even `even m`, even_of_exists (exists.intro (k₁+k₂) (by rewrite [hk₁, hk₂, left_distrib])) lemma even_add_of_odd_of_odd {n m} : odd n → odd m → even (n+m) := suppose odd n, suppose odd m, have even (succ n + succ m), from even_add_of_even_of_even (even_succ_of_odd `odd n`) (even_succ_of_odd `odd m`), have even(succ (succ (n + m))), by rewrite [add_succ at this, succ_add at this]; exact this, even_of_even_succ_succ this lemma odd_add_of_even_of_odd {n m} : even n → odd m → odd (n+m) := suppose even n, suppose odd m, have even (n + succ m), from even_add_of_even_of_even `even n` (even_succ_of_odd `odd m`), odd_of_even_succ this lemma odd_add_of_odd_of_even {n m} : odd n → even m → odd (n+m) := suppose odd n, suppose even m, have odd (m+n), from odd_add_of_even_of_odd `even m` `odd n`, by rewrite add.comm at this; exact this lemma even_mul_of_even_left {n} (m) : even n → even (n*m) := suppose even n, obtain k (hk : n = 2*k), from exists_of_even this, even_of_exists (exists.intro (k*m) (by rewrite [hk, mul.assoc])) lemma even_mul_of_even_right {n} (m) : even n → even (m*n) := suppose even n, have even (n*m), from even_mul_of_even_left _ this, by rewrite mul.comm at this; exact this lemma odd_mul_of_odd_of_odd {n m} : odd n → odd m → odd (n*m) := suppose odd n, suppose odd m, have even (n * succ m), from even_mul_of_even_right _ (even_succ_of_odd `odd m`), have even (n * m + n), by rewrite mul_succ at this; exact this, by_contradiction (suppose ¬ odd (n*m), have even (n*m), from even_of_not_odd this, absurd `even (n * m + n)` (not_even_of_odd (odd_add_of_even_of_odd this `odd n`))) lemma even_of_even_mul_self {n} : even (n * n) → even n := suppose even (n * n), by_contradiction (suppose odd n, have odd (n * n), from odd_mul_of_odd_of_odd this this, show false, from this `even (n * n)`) lemma odd_of_odd_mul_self {n} : odd (n * n) → odd n := suppose odd (n * n), suppose even n, have even (n * n), from !even_mul_of_even_left this, show false, from `odd (n * n)` this lemma odd_pow {n m} (h : odd n) : odd (n^m) := nat.induction_on m (show odd (n^0), from dec_trivial) (take m, suppose odd (n^m), show odd (n^(m+1)), from odd_mul_of_odd_of_odd h this) lemma even_pow {n m} (mpos : m > 0) (h : even n) : even (n^m) := have h₁ : ∀ m, even (n^succ m), from take m, nat.induction_on m (show even (n^1), by rewrite pow_one; apply h) (take m, suppose even (n^succ m), show even (n^(succ (succ m))), from !even_mul_of_even_left h), obtain m' (h₂ : m = succ m'), from exists_eq_succ_of_pos mpos, show even (n^m), by rewrite h₂; apply h₁ lemma odd_of_odd_pow {n m} (mpos : m > 0) (h : odd (n^m)) : odd n := suppose even n, have even (n^m), from even_pow mpos this, show false, from `odd (n^m)` this lemma even_of_even_pow {n m} (h : even (n^m)) : even n := by_contradiction (suppose odd n, have odd (n^m), from odd_pow this, show false, from this `even (n^m)`) lemma eq_of_div2_of_even {n m : nat} : n / 2 = m / 2 → (even n ↔ even m) → n = m := assume h₁ h₂, or.elim (em (even n)) (suppose even n, or.elim (em (even m)) (suppose even m, obtain w₁ (hw₁ : n = 2*w₁), from exists_of_even `even n`, obtain w₂ (hw₂ : m = 2*w₂), from exists_of_even `even m`, begin substvars, rewrite [mul.comm 2 w₁ at h₁, mul.comm 2 w₂ at h₁, *nat.mul_div_cancel _ (dec_trivial : 2 > 0) at h₁, h₁] end) (suppose odd m, absurd `odd m` (not_odd_of_even (iff.mp h₂ `even n`)))) (suppose odd n, or.elim (em (even m)) (suppose even m, absurd `odd n` (not_odd_of_even (iff.mpr h₂ `even m`))) (suppose odd m, have d : 1 / 2 = (0:nat), from dec_trivial, obtain w₁ (hw₁ : n = 2*w₁ + 1), from exists_of_odd `odd n`, obtain w₂ (hw₂ : m = 2*w₂ + 1), from exists_of_odd `odd m`, begin substvars, rewrite [add.comm at h₁, add_mul_div_self_left _ _ (dec_trivial : 2 > 0) at h₁, d at h₁, zero_add at h₁], rewrite [add.comm at h₁, add_mul_div_self_left _ _ (dec_trivial : 2 > 0) at h₁, d at h₁, zero_add at h₁], rewrite h₁ end)) end nat
1b0103a637a820b2420be776681817f166a9f034
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq7.lean
176fb350835a9c39f2b8279d256f8a915c36d5eb
[ "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
436
lean
import data.examples.vector open nat vector definition diag {A : Type} : Π {n}, vector (vector A n) n → vector A n | diag nil := nil | diag ((a :: va) :: vs) := a :: diag (map tail vs) theorem diag_nil (A : Type) : diag (@nil (vector A 0)) = nil := rfl theorem diag_succ {A : Type} {n : nat} (a : A) (va : vector A n) (vs : vector (vector A (succ n)) n) : diag ((a :: va) :: vs) = a :: diag (map tail vs) := rfl
609b52f9e794529e1f3eb4e57861bc3107127104
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/group_theory/submonoid/membership.lean
e5f80970aec4c2a2f051fe157d78b876447f0f4e
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
7,446
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import group_theory.submonoid.operations import algebra.big_operators import algebra.free_monoid /-! # Submonoids: membership criteria In this file we prove various facts about membership in a submonoid: * `list_prod_mem`, `multiset_prod_mem`, `prod_mem`: if each element of a collection belongs to a multiplicative submonoid, then so does their product; * `list_sum_mem`, `multiset_sum_mem`, `sum_mem`: if each element of a collection belongs to an additive submonoid, then so does their sum; * `pow_mem`, `nsmul_mem`: if `x ∈ S` where `S` is a multiplicative (resp., additive) submonoid and `n` is a natural number, then `x^n` (resp., `n •ℕ x`) belongs to `S`; * `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`, `coe_Sup_of_directed_on`: the supremum of a directed collection of submonoid is their union. * `sup_eq_range`, `mem_sup`: supremum of two submonoids `S`, `T` of a commutative monoid is the set of products; * `closure_singleton_eq`, `mem_closure_singleton`: the multiplicative (resp., additive) closure of `{x}` consists of powers (resp., natural multiples) of `x`. ## Tags submonoid, submonoids -/ open_locale big_operators variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} namespace submonoid variables (S : submonoid M) /-- Product of a list of elements in a submonoid is in the submonoid. -/ @[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."] lemma list_prod_mem : ∀ {l : list M}, (∀x ∈ l, x ∈ S) → l.prod ∈ S | [] h := S.one_mem | (a::l) h := suffices a * l.prod ∈ S, by rwa [list.prod_cons], have a ∈ S ∧ (∀ x ∈ l, x ∈ S), from list.forall_mem_cons.1 h, S.mul_mem this.1 (list_prod_mem this.2) /-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/ @[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M) : (∀a ∈ m, a ∈ S) → m.prod ∈ S := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact S.list_prod_mem hl end /-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the submonoid. -/ @[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is in the `add_submonoid`."] lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M) {ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) : ∏ c in t, f c ∈ S := S.multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi lemma pow_mem {x : M} (hx : x ∈ S) : ∀ n:ℕ, x^n ∈ S | 0 := S.one_mem | (n+1) := S.mul_mem hx (pow_mem n) open set @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) {x : M} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq (S _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _), { exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hS i j with ⟨k, hki, hkj⟩, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) : ((⨆ i, S i : submonoid M) : set M) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : M} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hS end @[to_additive] lemma coe_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set M) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] variables {N : Type*} [monoid N] {P : Type*} [monoid P] end submonoid namespace free_monoid variables {α : Type*} open submonoid @[to_additive] theorem closure_range_of : closure (set.range $ @of α) = ⊤ := eq_top_iff.2 $ λ x hx, free_monoid.rec_on x (one_mem _) $ λ x xs hxs, mul_mem _ (subset_closure $ set.mem_range_self _) hxs end free_monoid namespace submonoid variables {N : Type*} [monoid N] open monoid_hom lemma closure_singleton_eq (x : M) : closure ({x} : set M) = (powers_hom M x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨multiplicative.of_add 1, trivial, pow_one x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ pow_mem _ (subset_closure $ set.mem_singleton _) _ /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ lemma mem_closure_singleton {x y : M} : y ∈ closure ({x} : set M) ↔ ∃ n:ℕ, x^n=y := by rw [closure_singleton_eq, mem_mrange]; refl @[to_additive] lemma closure_eq_mrange (s : set M) : closure s = (free_monoid.lift (coe : s → M)).mrange := by rw [mrange, ← free_monoid.closure_range_of, map_mclosure, ← set.range_comp, free_monoid.lift_comp_of, subtype.range_coe] @[to_additive] lemma exists_list_of_mem_closure {s : set M} {x : M} (hx : x ∈ closure s) : ∃ (l : list M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x := begin rw [closure_eq_mrange, mem_mrange] at hx, rcases hx with ⟨l, hx⟩, exact ⟨list.map coe l, λ y hy, let ⟨z, hz, hy⟩ := list.mem_map.1 hy in hy ▸ z.2, hx⟩ end end submonoid namespace submonoid variables {N : Type*} [comm_monoid N] open monoid_hom @[to_additive] lemma sup_eq_range (s t : submonoid N) : s ⊔ t = (s.subtype.coprod t.subtype).mrange := by rw [mrange, ← mrange_inl_sup_mrange_inr, map_sup, map_mrange, coprod_comp_inl, map_mrange, coprod_comp_inr, range_subtype, range_subtype] @[to_additive] lemma mem_sup {s t : submonoid N} {x : N} : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := by simp only [sup_eq_range, mem_mrange, coprod_apply, prod.exists, submonoid.exists, coe_subtype, subtype.coe_mk] end submonoid namespace add_submonoid open set lemma nsmul_mem (S : add_submonoid A) {x : A} (hx : x ∈ S) : ∀ n : ℕ, n •ℕ x ∈ S | 0 := S.zero_mem | (n+1) := S.add_mem hx (nsmul_mem n) lemma closure_singleton_eq (x : A) : closure ({x} : set A) = (multiples_hom A x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨1, trivial, one_nsmul x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ nsmul_mem _ (subset_closure $ set.mem_singleton _) _ /-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n:ℕ, n •ℕ x = y := by rw [closure_singleton_eq, add_monoid_hom.mem_mrange]; refl end add_submonoid
a8e54f528710fe248e8d58b78a6c860ff34b9536
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/combinatorics/simple_graph/prod.lean
57d96e121fed0c8764f509d2563b3ad71fc9f006
[ "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
8,638
lean
/- Copyright (c) 2022 George Peter Banyard, Yaël Dillies, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: George Peter Banyard, Yaël Dillies, Kyle Miller -/ import combinatorics.simple_graph.connectivity /-! # Graph products This file defines the box product of graphs and other product constructions. The box product of `G` and `H` is the graph on the product of the vertices such that `x` and `y` are related iff they agree on one component and the other one is related via either `G` or `H`. For example, the box product of two edges is a square. ## Main declarations * `simple_graph.box_prod`: The box product. ## Notation * `G □ H`: The box product of `G` and `H`. ## TODO Define all other graph products! -/ variables {α β γ : Type*} namespace simple_graph variables {G : simple_graph α} {H : simple_graph β} {I : simple_graph γ} {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α × β} /-- Box product of simple graphs. It relates `(a₁, b)` and `(a₂, b)` if `G` relates `a₁` and `a₂`, and `(a, b₁)` and `(a, b₂)` if `H` relates `b₁` and `b₂`. -/ def box_prod (G : simple_graph α) (H : simple_graph β) : simple_graph (α × β) := { adj := λ x y, G.adj x.1 y.1 ∧ x.2 = y.2 ∨ H.adj x.2 y.2 ∧ x.1 = y.1, symm := λ x y, by simp [and_comm, or_comm, eq_comm, adj_comm], loopless := λ x, by simp } infix ` □ `:70 := box_prod @[simp] lemma box_prod_adj : (G □ H).adj x y ↔ G.adj x.1 y.1 ∧ x.2 = y.2 ∨ H.adj x.2 y.2 ∧ x.1 = y.1 := iff.rfl @[simp] lemma box_prod_adj_left : (G □ H).adj (a₁, b) (a₂, b) ↔ G.adj a₁ a₂ := by rw [box_prod_adj, and_iff_left rfl, or_iff_left (λ h : H.adj b b ∧ _, h.1.ne rfl)] @[simp] lemma box_prod_adj_right : (G □ H).adj (a, b₁) (a, b₂) ↔ H.adj b₁ b₂ := by rw [box_prod_adj, and_iff_left rfl, or_iff_right (λ h : G.adj a a ∧ _, h.1.ne rfl)] lemma box_prod_neighbor_set (x : α × β) : (G □ H).neighbor_set x = ((G.neighbor_set x.1) ×ˢ {x.2}) ∪ ({x.1} ×ˢ (H.neighbor_set x.2)) := begin ext ⟨a',b'⟩, simp only [mem_neighbor_set, set.mem_union, box_prod_adj, set.mem_prod, set.mem_singleton_iff], simp only [eq_comm, and_comm], end variables (G H I) /-- The box product is commutative up to isomorphism. `equiv.prod_comm` as a graph isomorphism. -/ @[simps] def box_prod_comm : G □ H ≃g H □ G := ⟨equiv.prod_comm _ _, λ x y, or_comm _ _⟩ /-- The box product is associative up to isomorphism. `equiv.prod_assoc` as a graph isomorphism. -/ @[simps] def box_prod_assoc : (G □ H) □ I ≃g G □ (H □ I) := ⟨equiv.prod_assoc _ _ _, λ x y, by simp only [box_prod_adj, equiv.prod_assoc_apply, or_and_distrib_right, or_assoc, prod.ext_iff, and_assoc, @and.comm (x.1.1 = _)]⟩ /-- The embedding of `G` into `G □ H` given by `b`. -/ @[simps] def box_prod_left (b : β) : G ↪g G □ H := { to_fun := λ a, (a , b), inj' := λ a₁ a₂, congr_arg prod.fst, map_rel_iff' := λ a₁ a₂, box_prod_adj_left } /-- The embedding of `H` into `G □ H` given by `a`. -/ @[simps] def box_prod_right (a : α) : H ↪g G □ H := { to_fun := prod.mk a, inj' := λ b₁ b₂, congr_arg prod.snd, map_rel_iff' := λ b₁ b₂, box_prod_adj_right } namespace walk variables {G} /-- Turn a walk on `G` into a walk on `G □ H`. -/ protected def box_prod_left (b : β) : G.walk a₁ a₂ → (G □ H).walk (a₁, b) (a₂, b) := walk.map (G.box_prod_left H b).to_hom variables (G) {H} /-- Turn a walk on `H` into a walk on `G □ H`. -/ protected def box_prod_right (a : α) : H.walk b₁ b₂ → (G □ H).walk (a, b₁) (a, b₂) := walk.map (G.box_prod_right H a).to_hom variables {G} /-- Project a walk on `G □ H` to a walk on `G` by discarding the moves in the direction of `H`. -/ def of_box_prod_left [decidable_eq β] [decidable_rel G.adj] : Π {x y : α × β}, (G □ H).walk x y → G.walk x.1 y.1 | _ _ nil := nil | x z (cons h w) := or.by_cases h (λ hG, w.of_box_prod_left.cons hG.1) (λ hH, show G.walk x.1 z.1, by rw hH.2; exact w.of_box_prod_left) /-- Project a walk on `G □ H` to a walk on `H` by discarding the moves in the direction of `G`. -/ def of_box_prod_right [decidable_eq α] [decidable_rel H.adj] : Π {x y : α × β}, (G □ H).walk x y → H.walk x.2 y.2 | _ _ nil := nil | x z (cons h w) := (or.symm h).by_cases (λ hH, w.of_box_prod_right.cons hH.1) (λ hG, show H.walk x.2 z.2, by rw hG.2; exact w.of_box_prod_right) @[simp] lemma of_box_prod_left_box_prod_left [decidable_eq β] [decidable_rel G.adj] : ∀ {a₁ a₂ : α} (w : G.walk a₁ a₂), (w.box_prod_left H b).of_box_prod_left = w | _ _ nil := rfl | _ _ (cons' x y z h w) := begin rw [walk.box_prod_left, map_cons, of_box_prod_left, or.by_cases, dif_pos, ←walk.box_prod_left, of_box_prod_left_box_prod_left], exacts [rfl, ⟨h, rfl⟩], end @[simp] lemma of_box_prod_left_box_prod_right [decidable_eq α] [decidable_rel G.adj] : ∀ {b₁ b₂ : α} (w : G.walk b₁ b₂), (w.box_prod_right G a).of_box_prod_right = w | _ _ nil := rfl | _ _ (cons' x y z h w) := begin rw [walk.box_prod_right, map_cons, of_box_prod_right, or.by_cases, dif_pos, ←walk.box_prod_right, of_box_prod_left_box_prod_right], exacts [rfl, ⟨h, rfl⟩], end end walk variables {G H} protected lemma preconnected.box_prod (hG : G.preconnected) (hH : H.preconnected) : (G □ H).preconnected := begin rintro x y, obtain ⟨w₁⟩ := hG x.1 y.1, obtain ⟨w₂⟩ := hH x.2 y.2, rw [←@prod.mk.eta _ _ x, ←@prod.mk.eta _ _ y], exact ⟨(w₁.box_prod_left _ _).append (w₂.box_prod_right _ _)⟩, end protected lemma preconnected.of_box_prod_left [nonempty β] (h : (G □ H).preconnected) : G.preconnected := begin classical, rintro a₁ a₂, obtain ⟨w⟩ := h (a₁, classical.arbitrary _) (a₂, classical.arbitrary _), exact ⟨w.of_box_prod_left⟩, end protected lemma preconnected.of_box_prod_right [nonempty α] (h : (G □ H).preconnected) : H.preconnected := begin classical, rintro b₁ b₂, obtain ⟨w⟩ := h (classical.arbitrary _, b₁) (classical.arbitrary _, b₂), exact ⟨w.of_box_prod_right⟩, end protected lemma connected.box_prod (hG : G.connected) (hH : H.connected) : (G □ H).connected := by { haveI := hG.nonempty, haveI := hH.nonempty, exact ⟨hG.preconnected.box_prod hH.preconnected⟩ } protected lemma connected.of_box_prod_left (h : (G □ H).connected) : G.connected := by { haveI := (nonempty_prod.1 h.nonempty).1, haveI := (nonempty_prod.1 h.nonempty).2, exact ⟨h.preconnected.of_box_prod_left⟩ } protected lemma connected.of_box_prod_right (h : (G □ H).connected) : H.connected := by { haveI := (nonempty_prod.1 h.nonempty).1, haveI := (nonempty_prod.1 h.nonempty).2, exact ⟨h.preconnected.of_box_prod_right⟩ } @[simp] lemma box_prod_connected : (G □ H).connected ↔ G.connected ∧ H.connected := ⟨λ h, ⟨h.of_box_prod_left, h.of_box_prod_right⟩, λ h, h.1.box_prod h.2⟩ instance box_prod_fintype_neighbor_set (x : α × β) [fintype (G.neighbor_set x.1)] [fintype (H.neighbor_set x.2)] : fintype ((G □ H).neighbor_set x) := fintype.of_equiv ((G.neighbor_finset x.1 ×ˢ {x.2}).disj_union ({x.1} ×ˢ H.neighbor_finset x.2) $ finset.disjoint_product.mpr $ or.inl $ neighbor_finset_disjoint_singleton _ _) ((equiv.refl _).subtype_equiv $ λ y, begin simp_rw [finset.mem_disj_union, finset.mem_product, finset.mem_singleton, mem_neighbor_finset, mem_neighbor_set, equiv.refl_apply, box_prod_adj], simp only [eq_comm, and_comm], end) lemma box_prod_neighbor_finset (x : α × β) [fintype (G.neighbor_set x.1)] [fintype (H.neighbor_set x.2)] [fintype ((G □ H).neighbor_set x)] : (G □ H).neighbor_finset x = (G.neighbor_finset x.1 ×ˢ {x.2}).disj_union ({x.1} ×ˢ H.neighbor_finset x.2) (finset.disjoint_product.mpr $ or.inl $ neighbor_finset_disjoint_singleton _ _) := begin -- swap out the fintype instance for the canonical one letI : fintype ((G □ H).neighbor_set x) := simple_graph.box_prod_fintype_neighbor_set _, refine eq.trans _ finset.attach_map_val, convert (finset.map_map _ (function.embedding.subtype _) finset.univ), end lemma box_prod_degree (x : α × β) [fintype (G.neighbor_set x.1)] [fintype (H.neighbor_set x.2)] [fintype ((G □ H).neighbor_set x)] : (G □ H).degree x = G.degree x.1 + H.degree x.2 := begin rw [degree, degree, degree, box_prod_neighbor_finset, finset.card_disj_union], simp_rw [finset.card_product, finset.card_singleton, mul_one, one_mul], end end simple_graph
6806c0ec86f23476fd9186ec7fa840c57e279fa3
df561f413cfe0a88b1056655515399c546ff32a5
/3-multiplication-world/l8.lean
eec950e60db74e5747d115e5b8b34d4b95cfee36
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
152
lean
lemma mul_comm (a b : mynat) : a * b = b * a := begin induction b with k Pk, rw zero_mul, rw mul_zero, refl, rw mul_succ, rw succ_mul, rw Pk, refl, end
aa784a2a58959c104af4bd0a98a41f0749a6629f
b147e1312077cdcfea8e6756207b3fa538982e12
/data/fin.lean
baf38263306be538e53adfd9f8aab2b5d53830e6
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,374
lean
import data.nat.basic open fin nat namespace fin variable {n : ℕ} /-- Embedding of `fin n` in `fin (n+1)` -/ def raise (k : fin n) : fin (n + 1) := ⟨val k, lt_succ_of_lt (is_lt k)⟩ def add_nat {n} (i : fin n) (k) : fin (n + k) := ⟨i.1 + k, nat.add_lt_add_right i.2 _⟩ @[simp] lemma succ_val (j : fin n) : j.succ.val = j.val.succ := by cases j; simp [fin.succ] @[simp] lemma pred_val (j : fin (n+1)) (h : j ≠ 0) : (j.pred h).val = j.val.pred := by cases j; simp [fin.pred] end fin 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)) instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨fin.val⟩ instance fin_to_int (n : ℕ) : has_coe (fin n) int := ⟨λ k, ↑(fin.val k)⟩ variables {n : ℕ} {a b : fin n} protected theorem fin.succ.inj (p : fin.succ a = fin.succ b) : a = b := by cases a; cases b; exact eq_of_veq (nat.succ.inj (veq_of_eq p)) @[elab_as_eliminator] def fin.succ_rec {C : ∀ n, fin n → Sort*} (H0 : ∀ n, C (succ n) 0) (Hs : ∀ n i, C n i → C (succ n) i.succ) : ∀ {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (fin.succ_rec ⟨i, lt_of_succ_lt_succ h⟩) @[elab_as_eliminator] def fin.succ_rec_on {n : ℕ} (i : fin n) {C : ∀ n, fin n → Sort*} (H0 : ∀ n, C (succ n) 0) (Hs : ∀ n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem fin.succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem fin.succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl @[elab_as_eliminator] def fin.cases {n} {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : ∀ i : fin n, C (i.succ)) : ∀ (i : fin (succ n)), C i | ⟨0, h⟩ := H0 | ⟨succ i, h⟩ := Hs ⟨i, lt_of_succ_lt_succ h⟩ @[simp] theorem fin.cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem fin.cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl
2712c53c699dc139d74ebb40c6f77782dfb51157
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/Check.lean
1046e07b405657548c72eeb7a61c88ad80a60819
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,216
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.Meta.InferType import Lean.Meta.LevelDefEq /- This is not the Kernel type checker, but an auxiliary method for checking whether terms produced by tactics and `isDefEq` are type correct. -/ namespace Lean.Meta private def ensureType (e : Expr) : MetaM Unit := do discard <| getLevel e def throwLetTypeMismatchMessage {α} (fvarId : FVarId) : MetaM α := do let lctx ← getLCtx match lctx.find? fvarId with | some (LocalDecl.ldecl _ _ n t v _) => do let vType ← inferType v throwError! "invalid let declaration, term{indentExpr v}\nhas type{indentExpr vType}\nbut is expected to have type{indentExpr t}" | _ => unreachable! private def checkConstant (constName : Name) (us : List Level) : MetaM Unit := do let cinfo ← getConstInfo constName unless us.length == cinfo.levelParams.length do throwIncorrectNumberOfLevels constName us private def getFunctionDomain (f : Expr) : MetaM (Expr × BinderInfo) := do let fType ← inferType f let fType ← whnfD fType match fType with | Expr.forallE _ d _ c => return (d, c.binderInfo) | _ => throwFunctionExpected f /- Given to expressions `a` and `b`, this method tries to annotate terms with `pp.explicit := true` to expose "implicit" differences. For example, suppose `a` and `b` are of the form ```lean @HashMap Nat Nat eqInst hasInst1 @HashMap Nat Nat eqInst hasInst2 ``` By default, the pretty printer formats both of them as `HashMap Nat Nat`. So, counterintuitive error messages such as ```lean error: application type mismatch HashMap.insert m argument m has type HashMap Nat Nat but is expected to have type HashMap Nat Nat ``` would be produced. By adding `pp.explicit := true`, we can generate the more informative error ```lean error: application type mismatch HashMap.insert m argument m has type @HashMap Nat Nat eqInst hasInst1 but is expected to have type @HashMap Nat Nat eqInst hasInst2 ``` Remark: this method implements a simple heuristic, we should extend it as we find other counterintuitive error messages. -/ partial def addPPExplicitToExposeDiff (a b : Expr) : MetaM (Expr × Expr) := do if (← getOptions).getBool `pp.all false || (← getOptions).getBool `pp.explicit false then return (a, b) else visit a b where visit (a b : Expr) : MetaM (Expr × Expr) := do try if !a.isApp || !b.isApp then return (a, b) else if a.getAppNumArgs != b.getAppNumArgs then return (a, b) else if not (← isDefEq a.getAppFn b.getAppFn) then return (a, b) else let fType ← inferType a.getAppFn forallBoundedTelescope fType a.getAppNumArgs fun xs _ => do let mut as := a.getAppArgs let mut bs := b.getAppArgs if (← hasExplicitDiff xs as bs) then return (a, b) else for i in [:as.size] do let (ai, bi) ← visit as[i] bs[i] as := as.set! i ai bs := bs.set! i bi let a := mkAppN a.getAppFn as let b := mkAppN b.getAppFn bs return (a.setAppPPExplicit, b.setAppPPExplicit) catch _ => return (a, b) hasExplicitDiff (xs as bs : Array Expr) : MetaM Bool := do for i in [:xs.size] do let localDecl ← getLocalDecl xs[i].fvarId! if localDecl.binderInfo.isExplicit then if not (← isDefEq as[i] bs[i]) then return true return false /- Return error message "has type{givenType}\nbut is expected to have type{expectedType}" -/ def mkHasTypeButIsExpectedMsg (givenType expectedType : Expr) : MetaM MessageData := do let (givenType, expectedType) ← addPPExplicitToExposeDiff givenType expectedType m!"has type{indentExpr givenType}\nbut is expected to have type{indentExpr expectedType}" def throwAppTypeMismatch {α} (f a : Expr) (extraMsg : MessageData := Format.nil) : MetaM α := do let (expectedType, binfo) ← getFunctionDomain f let mut e := mkApp f a unless binfo.isExplicit do e := e.setAppPPExplicit let aType ← inferType a throwError! "application type mismatch{indentExpr e}\nargument{indentExpr a}\n{← mkHasTypeButIsExpectedMsg aType expectedType}" def checkApp (f a : Expr) : MetaM Unit := do let fType ← inferType f let fType ← whnf fType match fType with | Expr.forallE _ d _ _ => let aType ← inferType a unless (← isDefEq d aType) do throwAppTypeMismatch f a | _ => throwFunctionExpected (mkApp f a) private partial def checkAux : Expr → MetaM Unit | e@(Expr.forallE ..) => checkForall e | e@(Expr.lam ..) => checkLambdaLet e | e@(Expr.letE ..) => checkLambdaLet e | Expr.const c lvls _ => checkConstant c lvls | Expr.app f a _ => do checkAux f; checkAux a; checkApp f a | Expr.mdata _ e _ => checkAux e | Expr.proj _ _ e _ => checkAux e | _ => pure () where checkLambdaLet (e : Expr) : MetaM Unit := lambdaLetTelescope e fun xs b => do xs.forM fun x => do let xDecl ← getFVarLocalDecl x; match xDecl with | LocalDecl.cdecl (type := t) .. => ensureType t checkAux t | LocalDecl.ldecl (type := t) (value := v) .. => ensureType t checkAux t let vType ← inferType v unless (← isDefEq t vType) do throwLetTypeMismatchMessage x.fvarId! checkAux v checkAux b checkForall (e : Expr) : MetaM Unit := forallTelescope e fun xs b => do xs.forM fun x => do let xDecl ← getFVarLocalDecl x ensureType xDecl.type checkAux xDecl.type ensureType b checkAux b def check (e : Expr) : MetaM Unit := traceCtx `Meta.check do withTransparency TransparencyMode.all $ checkAux e def isTypeCorrect (e : Expr) : MetaM Bool := do try check e pure true catch ex => trace[Meta.typeError]! ex.toMessageData pure false builtin_initialize registerTraceClass `Meta.check registerTraceClass `Meta.typeError end Lean.Meta
126391f3da607cab9739ec0cf083b5e7c39a0f68
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/topology/metric_space/contracting.lean
85a051e8630edf1c459ac14df88f5303d266f0a8
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
15,528
lean
/- Copyright (c) 2019 Rohan Mitta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov -/ import analysis.specific_limits import data.setoid /-! # Contracting maps A Lipschitz continuous self-map with Lipschitz constant `K < 1` is called a *contracting map*. In this file we prove the Banach fixed point theorem, some explicit estimates on the rate of convergence, and some properties of the map sending a contracting map to its fixed point. ## Main definitions * `contracting_with K f` : a Lipschitz continuous self-map with `K < 1`; * `efixed_point` : given a contracting map `f` on a complete emetric space and a point `x` such that `edist x (f x) < ∞`, `efixed_point f hf x hx` is the unique fixed point of `f` in `emetric.ball x ∞`; * `fixed_point` : the unique fixed point of a contracting map on a complete nonempty metric space. -/ open_locale nnreal topological_space classical open filter variables {α : Type*} /-- If the iterates `f^[n] x₀` converge to `x` and `f` is continuous at `x`, then `x` is a fixed point for `f`. -/ lemma fixed_point_of_tendsto_iterate [topological_space α] [t2_space α] {f : α → α} {x : α} (hf : continuous_at f x) (hx : ∃ x₀ : α, tendsto (λ n, f^[n] x₀) at_top (𝓝 x)) : f x = x := begin rcases hx with ⟨x₀, hx⟩, refine tendsto_nhds_unique at_top_ne_bot _ hx, rw [← tendsto_add_at_top_iff_nat 1, funext (assume n, nat.iterate_succ' f n x₀)], exact tendsto.comp hf hx end /-- A map is said to be `contracting_with K`, if `K < 1` and `f` is `lipschitz_with K`. -/ def contracting_with [emetric_space α] (K : ℝ≥0) (f : α → α) := (K < 1) ∧ lipschitz_with K f namespace contracting_with variables [emetric_space α] [cs : complete_space α] {K : ℝ≥0} {f : α → α} open emetric set lemma to_lipschitz_with (hf : contracting_with K f) : lipschitz_with K f := hf.2 lemma one_sub_K_pos' (hf : contracting_with K f) : (0:ennreal) < 1 - K := by simp [hf.1] lemma one_sub_K_ne_zero (hf : contracting_with K f) : (1:ennreal) - K ≠ 0 := ne_of_gt hf.one_sub_K_pos' lemma one_sub_K_ne_top : (1:ennreal) - K ≠ ⊤ := by { norm_cast, exact ennreal.coe_ne_top } lemma edist_inequality (hf : contracting_with K f) {x y} (h : edist x y < ⊤) : edist x y ≤ (edist x (f x) + edist y (f y)) / (1 - K) := suffices edist x y ≤ edist x (f x) + edist y (f y) + K * edist x y, by rwa [ennreal.le_div_iff_mul_le (or.inl hf.one_sub_K_ne_zero) (or.inl one_sub_K_ne_top), mul_comm, ennreal.sub_mul (λ _ _, ne_of_lt h), one_mul, ennreal.sub_le_iff_le_add], calc edist x y ≤ edist x (f x) + edist (f x) (f y) + edist (f y) y : edist_triangle4 _ _ _ _ ... = edist x (f x) + edist y (f y) + edist (f x) (f y) : by rw [edist_comm y, add_right_comm] ... ≤ edist x (f x) + edist y (f y) + K * edist x y : add_le_add' (le_refl _) (hf.2 _ _) lemma edist_le_of_fixed_point (hf : contracting_with K f) {x y} (h : edist x y < ⊤) (hy : f y = y) : edist x y ≤ (edist x (f x)) / (1 - K) := by simpa only [hy, edist_self, add_zero] using hf.edist_inequality h lemma eq_or_edist_eq_top_of_fixed_points (hf : contracting_with K f) {x y} (hx : f x = x) (hy : f y = y) : x = y ∨ edist x y = ⊤ := begin cases eq_or_lt_of_le (le_top : edist x y ≤ ⊤), from or.inr h, refine or.inl (edist_le_zero.1 _), simpa only [hx, edist_self, add_zero, ennreal.zero_div] using hf.edist_le_of_fixed_point h hy end /-- If a map `f` is `contracting_with K`, and `s` is a forward-invariant set, then restriction of `f` to `s` is `contracting_with K` as well. -/ lemma restrict (hf : contracting_with K f) {s : set α} (hs : maps_to f s s) : contracting_with K (hs.restrict f s s) := ⟨hf.1, λ x y, hf.2 x y⟩ include cs /-- Banach fixed-point theorem, contraction mapping theorem, `emetric_space` version. A contracting map on a complete metric space has a fixed point. We include more conclusions in this theorem to avoid proving them again later. The main API for this theorem are the functions `efixed_point` and `fixed_point`, and lemmas about these functions. -/ theorem exists_fixed_point (hf : contracting_with K f) (x : α) (hx : edist x (f x) < ⊤) : ∃ y, f y = y ∧ tendsto (λ n, f^[n] x) at_top (𝓝 y) ∧ ∀ n:ℕ, edist (f^[n] x) y ≤ (edist x (f x)) * K^n / (1 - K) := have cauchy_seq (λ n, f^[n] x), from cauchy_seq_of_edist_le_geometric K (edist x (f x)) (ennreal.coe_lt_one_iff.2 hf.1) (ne_of_lt hx) (hf.to_lipschitz_with.edist_iterate_succ_le_geometric x), let ⟨y, hy⟩ := cauchy_seq_tendsto_of_complete this in ⟨y, fixed_point_of_tendsto_iterate hf.2.continuous.continuous_at ⟨x, hy⟩, hy, edist_le_of_edist_le_geometric_of_tendsto K (edist x (f x)) (hf.to_lipschitz_with.edist_iterate_succ_le_geometric x) hy⟩ variable (f) -- avoid `efixed_point _` in pretty printer /-- Let `x` be a point of a complete emetric space. Suppose that `f` is a contracting map, and `edist x (f x) < ∞`. Then `efixed_point` is the unique fixed point of `f` in `emetric.ball x ∞`. -/ noncomputable def efixed_point (hf : contracting_with K f) (x : α) (hx : edist x (f x) < ⊤) : α := classical.some $ hf.exists_fixed_point x hx variables {f} lemma efixed_point_is_fixed (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) : f (efixed_point f hf x hx) = efixed_point f hf x hx := (classical.some_spec $ hf.exists_fixed_point x hx).1 lemma tendsto_iterate_efixed_point (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) : tendsto (λn, f^[n] x) at_top (𝓝 $ efixed_point f hf x hx) := (classical.some_spec $ hf.exists_fixed_point x hx).2.1 lemma apriori_edist_iterate_efixed_point_le (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) (n : ℕ) : edist (f^[n] x) (efixed_point f hf x hx) ≤ (edist x (f x)) * K^n / (1 - K) := (classical.some_spec $ hf.exists_fixed_point x hx).2.2 n lemma edist_efixed_point_le (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) : edist x (efixed_point f hf x hx) ≤ (edist x (f x)) / (1 - K) := by { convert hf.apriori_edist_iterate_efixed_point_le hx 0, simp only [pow_zero, mul_one] } lemma edist_efixed_point_lt_top (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) : edist x (efixed_point f hf x hx) < ⊤ := lt_of_le_of_lt (hf.edist_efixed_point_le hx) (ennreal.mul_lt_top hx $ ennreal.lt_top_iff_ne_top.2 $ ennreal.inv_ne_top.2 hf.one_sub_K_ne_zero) lemma efixed_point_eq_of_edist_lt_top (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) {y : α} (hy : edist y (f y) < ⊤) (h : edist x y < ⊤) : efixed_point f hf x hx = efixed_point f hf y hy := begin refine (hf.eq_or_edist_eq_top_of_fixed_points _ _).elim id (λ h', false.elim (ne_of_lt _ h')); try { apply efixed_point_is_fixed }, change edist_lt_top_setoid.rel _ _, transitivity x, by { symmetry, exact hf.edist_efixed_point_lt_top hx }, transitivity y, exacts [h, hf.edist_efixed_point_lt_top hy] end omit cs /-- Banach fixed-point theorem for maps contracting on a complete subset. -/ theorem exists_fixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : ∃ y ∈ s, f y = y ∧ tendsto (λ n, f^[n] x) at_top (𝓝 y) ∧ ∀ n:ℕ, edist (f^[n] x) y ≤ (edist x (f x)) * K^n / (1 - K) := begin haveI := hsc.complete_space_coe, rcases hf.exists_fixed_point ⟨x, hxs⟩ hx with ⟨y, hfy, h_tendsto, hle⟩, refine ⟨y, y.2, subtype.ext.1 hfy, _, λ n, _⟩, { convert (continuous_subtype_coe.tendsto _).comp h_tendsto, ext n, simp only [(∘), maps_to.iterate_restrict, maps_to.coe_restrict_apply, subtype.coe_mk] }, { convert hle n, rw [maps_to.iterate_restrict, eq_comm, maps_to.coe_restrict_apply, subtype.coe_mk] } end variable (f) -- avoid `efixed_point _` in pretty printer /-- Let `s` be a complete forward-invariant set of a self-map `f`. If `f` contracts on `s` and `x ∈ s` satisfies `edist x (f x) < ⊤`, then `efixed_point'` is the unique fixed point of the restriction of `f` to `s ∩ emetric.ball x ⊤`. -/ noncomputable def efixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) (x : α) (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : α := classical.some $ hf.exists_fixed_point' hsc hsf hxs hx variables {f} lemma efixed_point_mem' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : efixed_point' f hsc hsf hf x hxs hx ∈ s := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).fst lemma efixed_point_is_fixed' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : f (efixed_point' f hsc hsf hf x hxs hx) = efixed_point' f hsc hsf hf x hxs hx := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.1 lemma tendsto_iterate_efixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : tendsto (λn, f^[n] x) at_top (𝓝 $ efixed_point' f hsc hsf hf x hxs hx) := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.2.1 lemma apriori_edist_iterate_efixed_point_le' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) (n : ℕ) : edist (f^[n] x) (efixed_point' f hsc hsf hf x hxs hx) ≤ (edist x (f x)) * K^n / (1 - K) := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.2.2 n lemma edist_efixed_point_le' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : edist x (efixed_point' f hsc hsf hf x hxs hx) ≤ (edist x (f x)) / (1 - K) := by { convert hf.apriori_edist_iterate_efixed_point_le' hsc hsf hxs hx 0, rw [pow_zero, mul_one] } lemma edist_efixed_point_lt_top' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : edist x (efixed_point' f hsc hsf hf x hxs hx) < ⊤ := lt_of_le_of_lt (hf.edist_efixed_point_le' hsc hsf hxs hx) (ennreal.mul_lt_top hx $ ennreal.lt_top_iff_ne_top.2 $ ennreal.inv_ne_top.2 hf.one_sub_K_ne_zero) /-- If a globally contracting map `f` has two complete forward-invariant sets `s`, `t`, and `x ∈ s` is at a finite distance from `y ∈ t`, then the `efixed_point'` constructed by `x` is the same as the `efixed_point'` constructed by `y`. This lemma takes additional arguments stating that `f` contracts on `s` and `t` because this way it can be used to prove the desired equality with non-trivial proofs of these facts. -/ lemma efixed_point_eq_of_edist_lt_top' (hf : contracting_with K f) {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hfs : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) {t : set α} (htc : is_complete t) (htf : maps_to f t t) (hft : contracting_with K $ htf.restrict f t t) {y : α} (hyt : y ∈ t) (hy : edist y (f y) < ⊤) (hxy : edist x y < ⊤) : efixed_point' f hsc hsf hfs x hxs hx = efixed_point' f htc htf hft y hyt hy := begin refine (hf.eq_or_edist_eq_top_of_fixed_points _ _).elim id (λ h', false.elim (ne_of_lt _ h')); try { apply efixed_point_is_fixed' }, change edist_lt_top_setoid.rel _ _, transitivity x, by { symmetry, apply edist_efixed_point_lt_top' }, transitivity y, exact hxy, apply edist_efixed_point_lt_top' end end contracting_with namespace contracting_with variables [metric_space α] {K : ℝ≥0} {f : α → α} (hf : contracting_with K f) include hf lemma one_sub_K_pos (hf : contracting_with K f) : (0:ℝ) < 1 - K := sub_pos.2 hf.1 lemma dist_le_mul (x y : α) : dist (f x) (f y) ≤ K * dist x y := hf.to_lipschitz_with.dist_le_mul x y lemma dist_inequality (x y) : dist x y ≤ (dist x (f x) + dist y (f y)) / (1 - K) := suffices dist x y ≤ dist x (f x) + dist y (f y) + K * dist x y, by rwa [le_div_iff hf.one_sub_K_pos, mul_comm, sub_mul, one_mul, sub_le_iff_le_add], calc dist x y ≤ dist x (f x) + dist y (f y) + dist (f x) (f y) : dist_triangle4_right _ _ _ _ ... ≤ dist x (f x) + dist y (f y) + K * dist x y : add_le_add_left (hf.dist_le_mul _ _) _ lemma dist_le_of_fixed_point (x) {y} (hy : f y = y) : dist x y ≤ (dist x (f x)) / (1 - K) := by simpa only [hy, dist_self, add_zero] using hf.dist_inequality x y theorem fixed_point_unique' {x y} (hx : f x = x) (hy : f y = y) : x = y := (hf.eq_or_edist_eq_top_of_fixed_points hx hy).elim id (λ h, (edist_ne_top _ _ h).elim) /-- Let `f` be a contracting map with constant `K`; let `g` be another map uniformly `C`-close to `f`. If `x` and `y` are their fixed points, then `dist x y ≤ C / (1 - K)`. -/ lemma dist_fixed_point_fixed_point_of_dist_le' (g : α → α) {x y} (hx : f x = x) (hy : g y = y) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) : dist x y ≤ C / (1 - K) := calc dist x y = dist y x : dist_comm x y ... ≤ (dist y (f y)) / (1 - K) : hf.dist_le_of_fixed_point y hx ... = (dist (f y) (g y)) / (1 - K) : by rw [hy, dist_comm] ... ≤ C / (1 - K) : (div_le_div_right hf.one_sub_K_pos).2 (hfg y) noncomputable theory variables [nonempty α] [complete_space α] variable (f) /-- The unique fixed point of a contracting map in a nonempty complete metric space. -/ def fixed_point : α := efixed_point f hf _ (edist_lt_top (classical.choice ‹nonempty α›) _) variable {f} /-- The point provided by `contracting_with.fixed_point` is actually a fixed point. -/ lemma fixed_point_is_fixed : f (fixed_point f hf) = fixed_point f hf := hf.efixed_point_is_fixed _ lemma fixed_point_unique {x} (hx : f x = x) : x = fixed_point f hf := hf.fixed_point_unique' hx hf.fixed_point_is_fixed lemma dist_fixed_point_le (x) : dist x (fixed_point f hf) ≤ (dist x (f x)) / (1 - K) := hf.dist_le_of_fixed_point x hf.fixed_point_is_fixed /-- Aposteriori estimates on the convergence of iterates to the fixed point. -/ lemma aposteriori_dist_iterate_fixed_point_le (x n) : dist (f^[n] x) (fixed_point f hf) ≤ (dist (f^[n] x) (f^[n+1] x)) / (1 - K) := by { rw [nat.iterate_succ'], apply hf.dist_fixed_point_le } lemma apriori_dist_iterate_fixed_point_le (x n) : dist (f^[n] x) (fixed_point f hf) ≤ (dist x (f x)) * K^n / (1 - K) := le_trans (hf.aposteriori_dist_iterate_fixed_point_le x n) $ (div_le_div_right hf.one_sub_K_pos).2 $ hf.to_lipschitz_with.dist_iterate_succ_le_geometric x n lemma tendsto_iterate_fixed_point (x) : tendsto (λn, f^[n] x) at_top (𝓝 $ fixed_point f hf) := begin convert tendsto_iterate_efixed_point hf (edist_lt_top x _), refine (fixed_point_unique _ _).symm, apply efixed_point_is_fixed end lemma fixed_point_lipschitz_in_map {g : α → α} (hg : contracting_with K g) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) : dist (fixed_point f hf) (fixed_point g hg) ≤ C / (1 - K) := hf.dist_fixed_point_fixed_point_of_dist_le' g hf.fixed_point_is_fixed hg.fixed_point_is_fixed hfg end contracting_with
8bebad26f07a20a73344ef5912d4e3932a22ae85
491705a910060fcbc8431b3d688327aa85e58779
/src/week04.lean
e89d3e443d92d48ef08cf63b8a00215d7fa367bd
[]
no_license
UVM-M52/week04-justcadams
2a022f804b8fe8a99a57844bfdee51813b888a47
b24cbce05e3d9cdab9ed5322dde57dc7f068a0c2
refs/heads/master
1,609,225,255,451
1,580,926,167,000
1,580,926,167,000
238,503,094
0
0
null
null
null
null
UTF-8
Lean
false
false
3,539
lean
-- Math 52: Week 4 import .utils.int_refl -- Lakins Definition 1.2.1: definition is_even (n : ℤ) := ∃ (k : ℤ), n = 2 * k definition is_odd (n : ℤ) := ∃ (k : ℤ), n = 2 * k + 1 -- Lakins Definition 2.1.1: Let a, b ∈ ℤ. -- a divides b if there exists n ∈ ℤ such that b = an. -- We write a ∣ b for "a divides b" and say that a is -- a divisor of b. definition divides (a b : ℤ) : Prop := ∃ (n : ℤ), a * n = b -- The notation `a ∣ b` can be used for `divides a b` local infix ∣ := divides -- Lakins Example 2.1.2: example : 3 ∣ 12 := begin unfold divides, existsi (4:ℤ), refl, end -- Theorem: For every integer a, a ∣ a. theorem divides_refl : ∀ (a : ℤ), a ∣ a := begin intro a, unfold divides, existsi (1:ℤ), calc a * 1 = a : by rw mul_one, end -- Proof: Let a ∈ ℤ be arbitrary. We must show that a ∣ a; -- i.e., we must find an integer k such that a = a * k. -- Since a = a * 1 and 1 is an integer, we see that -- a ∣ a is true. □ -- Lakins Proposition 2.1.3: For all integers a, b, c, -- if a ∣ b and b ∣ c, then a ∣ c. theorem divides_trans : ∀ (a b c : ℤ), a ∣ b ∧ b ∣ c → a ∣ c := begin intros a b c H, cases H with Hl Hr, unfold divides, unfold divides at Hl Hr, cases Hl with n Summer_sez, cases Hr with m Thomas_sez, existsi(n * m :ℤ), symmetry, calc c = b * m : by rw Thomas_sez ... = (a * n) * m : by rw Summer_sez ... = a * (n * m) : by ac_refl, end -- Proof: Let a,b,c ∈ ℤ be arbitrary and assume that -- a ∣ b and b ∣ c. We must show that a ∣ c; i.e., we -- must find an integer k such that c = a * k. -- -- Since a ∣ b, by Definition 2.1.1 we may fix n ∈ ℤ -- such that b = a * n. Similarly, since b | c, we may -- fix m ∈ ℤ such that c = b * m, again by Definition -- 2.1.1. Then -- c = b * m = (a * n) * m = a * (n * m), -- since multiplication of integers is associative -- (Basic Properties of Integers 1.2.3). Since -- n * m ∈ ℤ, we have proved that a ∣ c, by -- Definition 2.1.1, as desired. 􏰟 -- Lakins Exercise 2.1.1: Let a,b, and c be integers. -- For all integers m and n, if a ∣ b and a ∣ c, then -- a ∣ (bm + cn). theorem L211 : ∀ (a b c m n : ℤ), a ∣ b ∧ a ∣ c → a ∣ (b * m + c * n) := begin sorry end -- Theorem: For every integer a, a is even if and only if 2 ∣ a. theorem is_even_iff_two_divides : ∀ (a : ℤ), is_even a ↔ 2 ∣ a := begin sorry end -- We will prove this fact later after we discuss induction. -- For now we take it as an axiom, i.e., as statement that we -- take as true without proof. axiom even_or_odd (a : ℤ) : is_even a ∨ is_odd a -- Lakins Theorem 2.1.9: For all integers a, a(a + 1) is even. theorem even_product : ∀ (a : ℤ), is_even (a * (a + 1)) := begin sorry end -- Proof: Let a ∈ ℤ. We show that a(a + 1) is even by -- considering two cases. -- -- Case I: a is even. -- Then 2 ∣ a, by Definition 1.2.1. Since a ∣ a(a + 1) -- by Definition 2.1.1, we have that 2 ∣ a(a + 1) since -- the divisibility relation is transitive (Proposition -- 2.1.3). Hence a(a + 1) is even. -- -- Case II: a is not even. -- Since a is not even, we know that a is odd. Then -- a+1 is even by Exercise 1.2.2b. Then, using an -- argument similar to that of Case I, we have that -- 2 ∣ (a+1) and (a+1) ∣ a(a+1), and hence 2 ∣ a(a+1) -- by Proposition 2.1.3. Thus a(a + 1) is even. -- -- Hence, since we have considered all possible cases -- for the integer a, we have proved that for all -- integers a, a(a + 1) is even. 􏰟
811154d3591198eac1128c331f1166515bdd0721
947b78d97130d56365ae2ec264df196ce769371a
/tests/compiler/termparsertest1.lean
858b2acf9c93c4ef2c99b3c86ac41af6f2ce932f
[ "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
2,603
lean
import Lean open Lean open Lean.Parser def testParser (input : String) : IO Unit := do env ← mkEmptyEnvironment; stx ← IO.ofExcept $ runParserCategory env `term input "<input>"; IO.println stx def test (is : List String) : IO Unit := is.forM $ fun input => do IO.println input; testParser input def testParserFailure (input : String) : IO Unit := do env ← mkEmptyEnvironment; match runParserCategory env `term input "<input>" with | Except.ok stx => throw (IO.userError ("unexpected success\n" ++ toString stx)) | Except.error msg => IO.println ("failed as expected, error: " ++ msg) def testFailures (is : List String) : IO Unit := is.forM $ fun input => do IO.println input; testParserFailure input def main (xs : List String) : IO Unit := do test [ "Prod.mk", "x.{u, v+1}", "x.{u}", "x", "x.{max u v}", "x.{max u v, 0}", "f 0 1", "f.{u+1} \"foo\" x", "(f x, 0, 1)", "()", "(f x)", "(f x : Type)", "h (f x) (g y)", "if x then f x else g x", "if h : x then f x h else g x h", "have p x y from f x; g this", "suffices h : p x y from f x; g this", "show p x y from f x", "fun x y => f y x", "fun (x y : Nat) => f y x", "fun (x, y) => f y x", "fun z (x, y) => f y x", "fun ⟨x, y⟩ ⟨z, w⟩ => f y x w z", "fun (Prod.mk x y) => f y x", "{ x := 10, y := 20 }", "{ x := 10, y := 20, }", "{ x // p x 10 }", "{ x : Nat // p x 10 }", "{ .. }", "{ fst := 10, .. : Nat × Nat }", "a[i]", "f [10, 20]", "g a[x+2]", "g f.a.1.2.bla x.1.a", "x+y*z < 10/3", "id (α := Nat) 10", "(x : a)", "a -> b", "{x : a} -> b", "{a : Type} -> [HasToString a] -> (x : a) -> b", "f ({x : a} -> b)", "f (x : a) -> b", "f ((x : a) -> b)", "(f : (n : Nat) → Vector Nat n) -> Nat", "∀ x y (z : Nat), x > y -> x > y - z", " match x with | some x => true | none => false", " match x with | some y => match y with | some (a, b) => a + b | none => 1 | none => 0 ", "Type u", "Sort v", "Type 1", "f Type 1", "let x := 0; x + 1", "let x : Nat := 0; x + 1", "let f (x : Nat) := x + 1; f 0", "let f {α : Type} (a : α) : α := a; f 10", "let f (x) := x + 1; f 10 + f 20", "let (x, y) := f 10; x + y", "let { fst := x, .. } := f 10; x + x", "let x.y := f 10; x", "let x.1 := f 10; x", "let x[i].y := f 10; x", "let x[i] := f 20; x", "-x + y", "!x", "¬ a ∧ b", " do let x ← f a; let x : Nat ← f a; g x; let y := g x; let (a, b) <- h x y; let (a, b) := (b, a); pure (a + b)", "do { let x ← f a; pure $ a + a }", "let f : Nat → Nat → Nat | 0, a => a + 10 | n+1, b => n * b; f 20", "max a b" ]; testFailures [ "f {x : a} -> b", "(x := 20)", "let x 10; x", "let x := y" ]
b668e6d53e6a2b058ece3d1d15b6db20a2e2c05e
367134ba5a65885e863bdc4507601606690974c1
/src/topology/locally_constant/algebra.lean
68970eadfa705e083242ab3ee76862904ec64ebe
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
3,883
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.locally_constant.basic /-! # Algebraic structure on locally constant functions This file puts algebraic structure (`add_group`, etc) on the type of locally constant functions. -/ namespace locally_constant variables {X Y : Type*} [topological_space X] @[to_additive] instance [has_one Y] : has_one (locally_constant X Y) := { one := const X 1 } @[simp, to_additive] lemma one_apply [has_one Y] (x : X) : (1 : locally_constant X Y) x = 1 := rfl @[to_additive] instance [has_inv Y] : has_inv (locally_constant X Y) := { inv := λ f, ⟨f⁻¹ , f.is_locally_constant.inv⟩ } @[simp, to_additive] lemma inv_apply [has_inv Y] (f : locally_constant X Y) (x : X) : f⁻¹ x = (f x)⁻¹ := rfl @[to_additive] instance [has_mul Y] : has_mul (locally_constant X Y) := { mul := λ f g, ⟨f * g, f.is_locally_constant.mul g.is_locally_constant⟩ } @[simp, to_additive] lemma mul_apply [has_mul Y] (f g : locally_constant X Y) (x : X) : (f * g) x = f x * g x := rfl @[to_additive] instance [has_div Y] : has_div (locally_constant X Y) := { div := λ f g, ⟨f / g, f.is_locally_constant.div g.is_locally_constant⟩ } @[to_additive] lemma div_apply [has_div Y] (f g : locally_constant X Y) (x : X) : (f / g) x = f x / g x := rfl @[to_additive] instance [semigroup Y] : semigroup (locally_constant X Y) := { mul_assoc := by { intros, ext, simp only [mul_apply, mul_assoc] }, .. locally_constant.has_mul } @[to_additive] instance [comm_semigroup Y] : comm_semigroup (locally_constant X Y) := { mul_comm := by { intros, ext, simp only [mul_apply, mul_comm] }, .. locally_constant.semigroup } @[to_additive] instance [monoid Y] : monoid (locally_constant X Y) := { one_mul := by { intros, ext, simp only [mul_apply, one_apply, one_mul] }, mul_one := by { intros, ext, simp only [mul_apply, one_apply, mul_one] }, .. locally_constant.semigroup, .. locally_constant.has_one } @[to_additive] instance [comm_monoid Y] : comm_monoid (locally_constant X Y) := { .. locally_constant.comm_semigroup, .. locally_constant.monoid } @[to_additive] instance [group Y] : group (locally_constant X Y) := { mul_left_inv := by { intros, ext, simp only [mul_apply, inv_apply, one_apply, mul_left_inv] }, div_eq_mul_inv := by { intros, ext, simp only [mul_apply, inv_apply, div_apply, div_eq_mul_inv] }, .. locally_constant.monoid, .. locally_constant.has_inv, .. locally_constant.has_div } @[to_additive] instance [comm_group Y] : comm_group (locally_constant X Y) := { .. locally_constant.comm_monoid, .. locally_constant.group } instance [distrib Y] : distrib (locally_constant X Y) := { left_distrib := by { intros, ext, simp only [mul_apply, add_apply, mul_add] }, right_distrib := by { intros, ext, simp only [mul_apply, add_apply, add_mul] }, .. locally_constant.has_add, .. locally_constant.has_mul } instance [mul_zero_class Y] : mul_zero_class (locally_constant X Y) := { mul_zero := by { intros, ext, simp only [mul_apply, zero_apply, mul_zero] }, zero_mul := by { intros, ext, simp only [mul_apply, zero_apply, zero_mul] }, .. locally_constant.has_zero, .. locally_constant.has_mul } instance [semiring Y] : semiring (locally_constant X Y) := { .. locally_constant.add_comm_monoid, .. locally_constant.monoid, .. locally_constant.distrib, .. locally_constant.mul_zero_class } instance [comm_semiring Y] : comm_semiring (locally_constant X Y) := { .. locally_constant.semiring, .. locally_constant.comm_monoid } instance [ring Y] : ring (locally_constant X Y) := { .. locally_constant.semiring, .. locally_constant.add_comm_group } instance [comm_ring Y] : comm_ring (locally_constant X Y) := { .. locally_constant.comm_semiring, .. locally_constant.ring } end locally_constant
f3e4a65eac9bace6d5c328f9242653efa6ce6c56
43390109ab88557e6090f3245c47479c123ee500
/src/Topology/Material/Sutherland_Chapter_10.lean
174e74a8859165b5acd6340758915d82fd78156c
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,165
lean
import analysis.topology.continuity import analysis.topology.topological_space import analysis.topology.infinite_sum import analysis.topology.topological_structures import analysis.topology.uniform_space import Topology.Material.Sutherland_Chapter_8 import data.equiv.basic local attribute [instance] classical.prop_decidable universes u v w open set filter lattice classical -- Below is the definition of the subspace_topology -- I think we should actually use the subspace topology already in lean -- It is the one induced by the inclusion map, subspace.val -- It is called subtype.topological_space def subspace_topology {α : Type u} [X : topological_space α] (A : set α) : topological_space A := { is_open := λ I, ∃ U : set α, X.is_open U ∧ subtype.val '' I = U ∩ A, is_open_univ := begin existsi univ, split, exact X.is_open_univ, rw univ_inter, unfold set.image, simp, end, is_open_inter := begin intros s t Hs Ht, cases Hs with Us HUs, cases Ht with Ut HUt, let Ust := Us ∩ Ut, existsi Ust, split, exact X.is_open_inter Us Ut HUs.1 HUt.1, have H1 : Ust ∩ A = (Us ∩ A) ∩ (Ut ∩ A), rw inter_right_comm Us A (Ut ∩ A), simp [inter_assoc], rw H1, rw [← HUs.2, ← HUt.2], rw set.image_inter, exact subtype.val_injective, end, is_open_sUnion := begin intros I HI, let Uset := {U : set α | topological_space.is_open X U ∧ ∃ t ∈ I, subtype.val '' t = U ∩ A}, let Uunion := ⋃₀ Uset, existsi Uunion, split, have H1 : (∀ (t : set α), t ∈ Uset → is_open t), intros t Ht, exact Ht.1, exact is_open_sUnion H1, apply set.ext, intro x, split, swap, intro Hx, cases Hx with Hx1 Hx2, simp at Hx1, cases Hx1 with U HU, simp, existsi Hx2, cases HU with HU HxU, cases HU with HUopen HU, cases HU with t Ht, existsi t, apply and.intro Ht.1, rw ← preimage_image_eq t subtype.val_injective, show x ∈ subtype.val '' t, rw Ht.2, exact ⟨HxU,Hx2⟩, simp, intros Hx HxinU0I, cases HxinU0I with t Ht, split, swap, exact Hx, have Hnext := HI t Ht.1, cases Hnext with Unext HUnext, existsi Unext, split, apply and.intro HUnext.1, existsi t, exact ⟨Ht.1, HUnext.2⟩, have x_in_val_t : x ∈ subtype.val '' t, simp, existsi Hx, exact Ht.2, rw HUnext.2 at x_in_val_t, exact x_in_val_t.1, end, } --Proof of equivalence of definitions theorem subspace_top_eq_subtype_top {α : Type u} [X : topological_space α] (A : set α) : (subspace_topology A).is_open = (subtype.topological_space).is_open := begin dunfold subtype.topological_space, unfold topological_space.induced, simp, funext V, apply propext, split, intro HU, cases HU with U HU, existsi U, apply and.intro HU.1, have H0 : subtype.val ⁻¹' (subtype.val '' V) = subtype.val ⁻¹' (A ∩ U), rw HU.2, simp, apply inter_comm, have H1 : V = subtype.val ⁻¹' (A ∩ U), rw ← H0, rw preimage_image_eq, exact subtype.val_injective, rw H1, simp, have preimage_A_eq_univ : subtype.val ⁻¹' A = @univ (subtype A), apply set.ext, intro x, simp, exact x.2, rw preimage_A_eq_univ, apply univ_inter, intro HU, cases HU with U HU, existsi U, apply and.intro HU.1, have H0 : subtype.val '' V = subtype.val '' (subtype.val ⁻¹' U), by rw HU.2, rw H0, apply set.ext, intro x, simp, split, intro Hx, cases Hx with a Ha, rw ← Ha.2.2, apply and.intro Ha.2.1, exact Ha.1, intro Hx, existsi x, exact ⟨Hx.2, Hx.1, refl x⟩, end --Prop 10.4 theorem inclusion_cont_subtype_top {α : Type u} [X : topological_space α] (A : set α) : @continuous _ _ (subtype.topological_space) _ (λ (a : A), (a : α)) := begin unfold continuous, unfold is_open, intros s Hs, simp, unfold subtype.topological_space, unfold topological_space.induced, simp, existsi s, apply and.intro Hs, unfold coe, unfold lift_t, unfold has_lift_t.lift, unfold coe_t, unfold has_coe_t.coe, unfold coe_b, unfold has_coe.coe, end --Prop 10.4 but with subspace topology (I won't do any more with the subspace topology) theorem inclusion_cont_subspace_top {α : Type u} [X : topological_space α] (A : set α) : @continuous _ _ (subspace_topology A) _ (λ (a : A), (a : α)) := begin unfold continuous, unfold is_open, rw subspace_top_eq_subtype_top, exact inclusion_cont_subtype_top A, end --Corollary 10.5 theorem restriction_cont {α : Type u} [X : topological_space α] {β : Type v} [Y : topological_space β] (f : α → β) (H : continuous f) (A : set α) : continuous (λ (x : A), f x) := begin have H0 : (λ (x : A), f ↑x) = f ∘ (λ (a : A), (a : α)), by simp, rw H0, exact (continuous.comp (inclusion_cont_subtype_top A) H), end --Proposition 10.6 theorem inclusion_comp_cont_iff_cont {α : Type*} [X : topological_space α] {A : set α} {γ : Type*} [Z : topological_space γ] (g : γ → A) : continuous g ↔ continuous ((λ (a : A), (a : α)) ∘ g) := begin split, intro Hg, exact continuous.comp Hg (inclusion_cont_subtype_top A), simp, unfold continuous, unfold is_open, intro H_i_comp_g, intros V HV, unfold subtype.topological_space at HV, unfold topological_space.induced at HV, simp at HV, cases HV with U HU, have H1 := H_i_comp_g U HU.1, rw HU.2, exact H1, end --Proposition 10.8 theorem inclusion_comp_cont_iff_cont_to_subtype_top {α : Type u} [X : topological_space α] {A : set α} (Trandom : topological_space A) : (∀ {γ : Type u} [Z : topological_space γ] (g : γ → A), (@continuous γ ↥A Z _ g ↔ @continuous γ α Z _ ((λ (a : A), (a : α)) ∘ g))) ↔ Trandom.is_open = (subtype.topological_space).is_open := begin split, swap, { intros H _ _ _, rw ←(@inclusion_comp_cont_iff_cont _ _ _ _ Z g), unfold continuous, unfold is_open, rw H, }, intro H, apply set.ext, intro V, split, swap, have H1 := (@H (↥A) Trandom (@id A)).1 id_map_continuous, intro HV, unfold subtype.topological_space at HV, unfold topological_space.induced at HV, simp at HV, cases HV with U HU, have H2 : Trandom.is_open (subtype.val ⁻¹' U), simp at H1, unfold continuous at H1, exact H1 U HU.1, rw ← HU.2 at H2, assumption, have H1 := (@H (↥A) subtype.topological_space (@id A)).2, simp at H1, intro HV, have H2 := H1 _, unfold continuous at H2, exact H2 V HV, exact continuous_subtype_val, end --Product Topologies def product_top {α : Type*} {β : Type*} (X : topological_space α) (Y : topological_space β) : topological_space (α × β) := {is_open := λ (W : set (α × β)), ∃ (I ⊆ { b : set (α × β) | ∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V}), W = ⋃₀ I, is_open_univ := begin existsi {d : set (α × β) | d = set.prod univ univ}, have H : set.subset {d : set (α × β) | d = set.prod univ univ} {b : set (α × β) | ∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V}, rw univ_prod_univ, unfold set.subset, intros a Ha, rw mem_set_of_eq at Ha, rw Ha, existsi univ, existsi univ, apply and.intro is_open_univ, apply and.intro is_open_univ, rw univ_prod_univ, existsi H, rw univ_prod_univ, have H1 : {d : set (α × β) | d = univ} = {univ}, apply set.ext, intro x, rw mem_set_of_eq, rw mem_singleton_iff, rw H1, rw sUnion_singleton, end, is_open_inter := begin intros W1 W2 HW1 HW2, cases HW1 with I1 HI1, cases HI1 with HI1 HWI1, cases HW2 with I2 HI2, cases HI2 with HI2 HWI2, existsi {e : set (α × β) | ∃ (U ∈ I1) (V ∈ I2), e = U ∩ V}, have H : set.subset {e : set (α × β) | ∃ (U : set (α × β)) (H : U ∈ I1) (V : set (α × β)) (H : V ∈ I2), e = U ∩ V} {b : set (α × β) | ∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V}, unfold set.subset, simp, intros a w1 Hw1 w2 Hw2 Ha, rw Ha, have H1 := HI1 Hw1, rw mem_set_of_eq at H1, have H2 := HI2 Hw2, rw mem_set_of_eq at H2, rcases H1 with ⟨U1, V1, HU1, HV1, H1UV⟩, rcases H2 with ⟨U2, V2, HU2, HV2, H2UV⟩, existsi (U1 ∩ U2), apply and.intro (X.is_open_inter U1 U2 HU1 HU2), existsi (V1 ∩ V2), apply and.intro (Y.is_open_inter V1 V2 HV1 HV2), rw H1UV, rw H2UV, apply prod_inter_prod, existsi H, rw HWI1, rw HWI2, apply set.ext, intro x, rw mem_set_of_eq, unfold set.inter, rw mem_set_of_eq, unfold set.sUnion, rw mem_set_of_eq, rw mem_set_of_eq, split, intro Hx, rcases Hx with ⟨HU, V, HV1, HV2⟩, rcases HU with ⟨U, HU1, HU2⟩, existsi (U ∩ V), existsi _, exact ⟨HU2, HV2⟩, rw mem_set_of_eq, existsi [U, HU1, V, HV1], trivial, intro Hx, rcases Hx with ⟨a, Ha1, Ha2⟩, rw mem_set_of_eq at Ha1, rcases Ha1 with ⟨U, HU, V, HV, HUV⟩, rw HUV at Ha2, split, existsi [U, HU], exact Ha2.1, existsi [V, HV], exact Ha2.2, end, is_open_sUnion := begin intros I2 HI2, let Iset := {I | set.subset I {b : set (α × β) | ∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V} ∧ (∃ t ∈ I2, t = ⋃₀ I)}, existsi ⋃₀ Iset, existsi _, swap, intros x Hx, rw mem_set_of_eq at Hx, rcases Hx with ⟨a, Ha, Ha2⟩, rw mem_set_of_eq at Ha, exact Ha.1 Ha2, apply set.ext, intro s, simp, split, intro HW, rcases HW with ⟨W, HW, HW2⟩, have H := HI2 W HW, rcases H with ⟨IW, HIW, HIIW⟩, rw HIIW at HW2, rw mem_sUnion_eq at HW2, rcases HW2 with ⟨square, Hsquare, Hsquare_s⟩, existsi square, split, existsi IW, refine ⟨_, Hsquare⟩, rw HIIW at HW, refine ⟨_, HW⟩, have Hsame : {b : set (α × β) | ∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V} = {b : set (α × β) | ∃ (U : set α), is_open U ∧ ∃ (V : set β), is_open V ∧ b = set.prod U V}, apply set.ext, intro x, simp, rw ←Hsame, exact HIW, exact Hsquare_s, intro HW, cases HW with W HW, cases HW with HW HsW, cases HW with I HI, existsi ⋃₀ I, refine ⟨HI.1.2, _⟩, rw mem_sUnion_eq, existsi W, existsi HI.2, exact HsW, end } --Product Topology Basis definition product_top_basis {α : Type*} {β : Type*} (X : topological_space α) (Y : topological_space β) : set (set (α × β)) := { b : set (α × β) | ∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V} theorem is_basis_product_top_basis {α : Type*} {β : Type*} (X : topological_space α) (Y : topological_space β) : @topological_space.is_topological_basis _ (product_top X Y) (product_top_basis X Y) := begin unfold topological_space.is_topological_basis, split, intros t1 Ht1 t2 Ht2 x Hx, unfold product_top_basis at Ht1, rw mem_set_of_eq at Ht1, unfold product_top_basis at Ht2, rw mem_set_of_eq at Ht2, rcases Ht1 with ⟨U1, V1, Ht1⟩, rcases Ht2 with ⟨U2, V2, Ht2⟩, existsi (set.prod (U1 ∩ U2) (V1 ∩ V2)), refine ⟨_,_⟩, unfold product_top_basis, rw mem_set_of_eq, existsi [U1 ∩ U2, V1 ∩ V2], exact ⟨is_open_inter Ht1.1 Ht2.1, is_open_inter Ht1.2.1 Ht2.2.1, refl (set.prod (U1 ∩ U2) (V1 ∩ V2))⟩, rw mem_prod, cases Hx with Hx1 Hx2, rw Ht1.2.2 at Hx1, rw Ht2.2.2 at Hx2, rw mem_prod at Hx1, rw mem_prod at Hx2, refine ⟨⟨⟨Hx1.1,Hx2.1⟩,Hx1.2,Hx2.2⟩,_⟩, rw Ht1.2.2, rw Ht2.2.2, intros y Hy, rw mem_prod at Hy, split, exact ⟨Hy.1.1, Hy.2.1⟩, exact ⟨Hy.1.2, Hy.2.2⟩, split, apply eq_univ_of_univ_subset, apply subset_sUnion_of_mem, existsi [univ, univ], apply and.intro is_open_univ, apply and.intro is_open_univ, rw ← univ_prod_univ, unfold product_top, unfold topological_space.generate_from, apply topological_space_eq, apply set.ext, intro W, split, intro HW, rcases HW with ⟨open_rects_set, Hopen_rects_set, HW⟩, unfold product_top_basis, rw HW, exact topological_space.generate_open.sUnion open_rects_set (λ (s : set (α × β)) (H : s ∈ open_rects_set), topological_space.generate_open.basic s (Hopen_rects_set H)), apply topological_space.generate_open.rec, --THIS IS THE CORRECT PATH intros s Hs, unfold product_top_basis at Hs, rcases Hs with ⟨U, V, HU, HV, HW⟩, existsi {set.prod U V}, have H : {set.prod U V} ⊆ {b : set (α × β) | ∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V}, intros s Hs, rw mem_singleton_iff at Hs, rw Hs, existsi [U, V], exact ⟨HU, HV, refl (set.prod U V)⟩, existsi H, rw sUnion_singleton, exact HW, existsi {univ}, have H : {univ} ⊆ {b : set (α × β) | ∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V}, intros UNI HUNI, existsi [univ, univ], rw mem_singleton_iff at HUNI, rw HUNI, apply and.intro is_open_univ, apply and.intro is_open_univ, exact eq.symm univ_prod_univ, existsi H, rw sUnion_singleton, intros s t Hs1 Ht1 Hs Ht, rcases Hs with ⟨Is, HIs, HsUnionIs⟩, rcases Ht with ⟨It, HIt, HsUnionIt⟩, apply is_open_inter, existsi [Is, HIs], assumption, existsi [It, HIt], assumption, intros I HI_gen_prod_top_bas HI_open_sets, -- WHat set do I need? The set that contains all open rectangles appearing in any element of I existsi { b : set (α × β) | (∃ (U : set α) (V : set β), is_open U ∧ is_open V ∧ b = set.prod U V) ∧ ∃ s ∈ I, b ⊆ s}, existsi _, swap, intros x Hx, rw mem_set_of_eq, rw mem_set_of_eq at Hx, cases Hx with Hx1 Hx2, exact Hx1, apply eq_of_subset_of_subset, intros x Hx, rw mem_sUnion_eq at Hx, rcases Hx with ⟨t, Ht, Hxt⟩, -- Need to existsi the open rectangle that x is in have H := HI_open_sets t Ht, cases H with It HIt, cases HIt with HIt HIt2, rw HIt2 at Hxt, rcases Hxt with ⟨rect,rectIt,xrect⟩, existsi rect, refine ⟨⟨HIt rectIt,_⟩, _⟩, existsi [t, Ht], rw HIt2, apply subset_sUnion_of_mem rectIt, exact xrect, apply sUnion_subset, intros t Ht, cases Ht, rcases Ht_right, cases Ht_right_h, apply subset.trans Ht_right_h_h (subset_sUnion_of_mem Ht_right_h_w), end --Proof that our definition of product top is equivalent to the instance built into mathlib. theorem product_top_eq_induced_prod_top {α : Type*} {β : Type*} (X : topological_space α) (Y : topological_space β) : product_top X Y = topological_space.induced prod.fst X ⊔ topological_space.induced prod.snd Y := begin apply topological_space_eq, unfold product_top, unfold lattice.has_sup.sup, unfold semilattice_sup.sup, unfold semilattice_sup_bot.sup, unfold bounded_lattice.sup, unfold complete_lattice.sup, unfold Inf, unfold has_Inf.Inf, simp only [exists_prop, mem_set_of_eq, not_and, and_imp], apply set.ext, intro U, split, intro HU, rcases HU with ⟨I_U,HI_U,HI_U2⟩, intros T HXT HYT, unfold has_le.le at HXT, unfold preorder.le at HXT, unfold partial_order.le at HXT, unfold has_le.le at HXT, unfold preorder.le at HXT, unfold has_le.le at HXT, unfold preorder.le at HXT, unfold partial_order.le at HXT, unfold order_bot.le at HXT, unfold bounded_lattice.le at HXT, unfold complete_lattice.le at HXT, unfold bounded_lattice.le at HXT, --THe following should be each prod U1 univ, prod univ V1 for all rectangles prod U1 V1 --in U. Then intersect each pair and union them. rw HI_U2, apply is_open_sUnion, intros rect Hrect, --Split rect into the intersection of prod U1 univ and prod univ V1 have Hrect2 := HI_U Hrect, rcases Hrect2 with ⟨Urect,Vrect,HUrect,HVrect,HUrectVrect⟩, have HUrectuniv : topological_space.is_open T (set.prod Urect univ), apply HXT, existsi Urect, split, exact HUrect, unfold preimage, apply set.ext, intro x, rw mem_set_of_eq, rw mem_prod, rw and_iff_left, exact mem_univ _, have HunivVrect : topological_space.is_open T (set.prod univ Vrect), apply HYT, existsi Vrect, split, exact HVrect, unfold preimage, apply set.ext, intro x, rw mem_set_of_eq, rw mem_prod, rw and_iff_right, exact mem_univ _, have H_open_rect := T.is_open_inter _ _ HUrectuniv HunivVrect, have Hrect_prod : set.prod Urect univ ∩ set.prod univ Vrect = rect, rw prod_inter_prod, rw inter_univ, rw univ_inter, rw HUrectVrect, rw Hrect_prod at H_open_rect, exact H_open_rect, intro HU, have H := HU (product_top X Y), have HX : topological_space.induced prod.fst X ≤ product_top X Y, intros V HV, unfold topological_space.induced at HV, cases HV with S HS, cases HS with HS HV, unfold preimage at HV, rw HV, existsi {set.prod S univ}, existsi _, rw sUnion_singleton, apply set.ext, intro x, rw mem_set_of_eq,rw mem_prod, rw and_iff_left, exact mem_univ _, intros x Hx, existsi S, existsi univ, exact ⟨HS, is_open_univ, mem_singleton_iff.1 Hx⟩, have HY : topological_space.induced prod.snd Y ≤ product_top X Y, intros V HV, cases HV with S HS, cases HS with HS HV, unfold preimage at HV, rw HV, existsi {set.prod univ S}, existsi _, rw sUnion_singleton, apply set.ext, intro x, rw mem_set_of_eq, rw mem_prod, rw and_iff_right, exact mem_univ _, intros x Hx, existsi univ, existsi S, exact ⟨is_open_univ, HS, mem_singleton_iff.1 Hx⟩, have H1 := H HX HY, unfold product_top at H1, simp only [exists_prop, mem_set_of_eq, not_and, and_imp] at H1, exact H1, end #print prefix set --Proposition 10.10 theorem left_proj_cont {α : Type*} {β : Type*} (X : topological_space α) (Y : topological_space β) : @continuous (α × β) α (product_top X Y) X (λ p, p.1) := begin unfold continuous, unfold is_open, intros s Hs, unfold product_top, existsi {set.prod s (univ : set β)}, split, intros pre Hpre, rw mem_singleton_iff at Hpre, rw Hpre, rw mem_set_of_eq, existsi [s, univ], exact ⟨Hs, Y.is_open_univ, rfl⟩, apply set.ext, intro x, rw mem_preimage_eq, rw sUnion_singleton, rw mem_prod, rw and_iff_left, exact mem_univ x.snd, end theorem right_proj_cont {α : Type*} {β : Type*} (X : topological_space α) (Y : topological_space β) : @continuous (α × β) β (product_top X Y) Y (λ p, p.2) := begin unfold continuous, unfold is_open, intros s Hs, unfold product_top, existsi {set.prod (univ : set α) s}, split, intros pre Hpre, rw @mem_singleton_iff at Hpre, rw Hpre, rw mem_set_of_eq, existsi [univ, s], exact ⟨X.is_open_univ, Hs, rfl⟩, apply set.ext, intro x, rw mem_preimage_eq, rw sUnion_singleton, rw mem_prod, rw and_iff_right, exact mem_univ x.fst, end --set_option pp.implicit true set_option trace.simplify.rewrite true theorem cont_iff_proj_cont {α : Type*} {β : Type*} {γ : Type*} (X : topological_space α) (Y : topological_space β) (Z : topological_space γ) (f : γ → (α × β)) : @continuous _ _ Z (product_top X Y) f ↔ (continuous ((λ (p : α × β), p.2) ∘ f) ∧ continuous ((λ (p : α × β), p.1) ∘ f)) := begin split, intro Hf, split, exact @continuous.comp _ _ _ _ (product_top X Y) _ _ _ Hf (right_proj_cont X Y), exact @continuous.comp _ _ _ _ (product_top X Y) _ _ _ Hf (left_proj_cont X Y), intro Hf, apply continuous_basis_to_continuous, apply is_basis_product_top_basis, intro b, unfold product_top_basis at b, rename b b1, rcases b.property with ⟨U, V, HU, HV,HB⟩, cases Hf with Hfsnd Hffst, have Hsnd := Hfsnd V HV, have Hfst := Hffst U HU, have H1 := is_open_inter Hfst Hsnd, have EQ : (λ (p : α × β), p.fst) ∘ f ⁻¹' U ∩ (λ (p : α × β), p.snd) ∘ f ⁻¹' V = (f ⁻¹' ↑b), rw preimage_comp, rw @preimage_comp _ _ _ f (λ (p : α × β), p.snd) _, rw ← preimage_inter, have H2 : prod.fst ⁻¹' U = set.prod U univ, apply set.ext, intro x, split, intro Hx, rw mem_preimage_eq at Hx, split, exact Hx, exact @mem_univ β x.snd, intro Hx, rw mem_preimage_eq, exact Hx.1, rw H2, have H3 : prod.snd ⁻¹' V = set.prod univ V, apply set.ext, intro x, split, intro Hx, rw mem_preimage_eq at Hx, split, exact @mem_univ α x.fst, exact Hx, intro Hx, rw mem_preimage_eq, exact Hx.2, rw H3, rw prod_inter_prod, rw inter_univ, rw univ_inter, rw ← HB, have H4 : b.val = ↑b, trivial, rw H4, rw ← EQ, exact H1, end
fd086972dd76a220fedfe8cd5188367e99344a6c
9a0b1b3a653ea926b03d1495fef64da1d14b3174
/tidy/forwards_reasoning.lean
9ab478faed2723034e74ae311d1e7826200b680a
[ "Apache-2.0" ]
permissive
khoek/mathlib-tidy
8623b27b4e04e7d598164e7eaf248610d58f768b
866afa6ab597c47f1b72e8fe2b82b97fff5b980f
refs/heads/master
1,585,598,975,772
1,538,659,544,000
1,538,659,544,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,326
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import tidy.lib.tactic import tidy.lib.pretty_print open tactic meta def forward_attribute : user_attribute := { name := `forward, descr := "A lemma whose conclusion should be deduced whenever all arguments are satisfiable from hypotheses; use `forwards_reasoning` to automatically try all lemmas tagged `@[forward]`." } run_cmd attribute.register `forward_attribute /- Improvements: * Store the local_context, and its types, rather than recomputing. * Give up earlier if our current expression is obviously still just a hypothesis. * Don't use dsimplify; does it still work? * If not, try using whnf * In mk_apps, `to_expr` is probably too expensive. Can we get away with just the second option? * In the second option, `mk_app_aux`, either delete the instance implicit branch, and hope unify handles typeclass inference for us later, or make do typeclass inference by hand, using `apply_instance` For testing, we better be able to run against lean-category-theory... -/ meta def guard_no_duplicate_hypothesis (t : expr) : tactic unit := do hyps ← local_context, types ← hyps.mmap (λ h, infer_type h), success_if_fail (types.mfirst (λ s, is_def_eq s t)) meta def guard_prop (e : expr) : tactic unit := do t ← infer_type e, guard (t = `(Prop)) meta def attempt_forwards_reasoning (only_props : bool) (s : simp_lemmas) : list (expr × list string) → tactic string | [] := fail "forwards_reasoning failed" | (e :: es) := do t ← infer_type e.1, t' ← try_core (s.dsimplify [] t), -- FIXME too expensive let changed := t'.is_some, let t := t'.get_or_else t, if t.is_pi then do hyps ← local_context, apps ← mk_apps e.1 hyps, apps ← apps.mmap (λ p, do h_pp ← pretty_print p.2, return (p.1, list.cons h_pp e.2)), attempt_forwards_reasoning (apps ++ es) else (do if only_props then guard_prop t else skip, guard_no_duplicate_hypothesis t, let n := "_".intercalate e.2.reverse, assertv n t e.1, term ← pretty_print e.1, -- TODO sometimes this reported tactic won't work, and we need to write instead -- `have n : t := by convert term` return ("have " ++ n ++ " := " ++ term) ) <|> attempt_forwards_reasoning es /-- Attempt to `have` a lemma marked with the attribute @[forward], whose conclusion is not yet known and whose arguments can be filled in by hypotheses. -/ meta def forwards_library_reasoning : tactic string := do cs ← attribute.get_instances `forward, es ← cs.mmap (λ n, (do e ← mk_const n, let s := n.components.ilast.to_string, return (e, [s]))), s ← mk_simp_set ff [] [], attempt_forwards_reasoning ff s.1 es /-- Attempt to `have` a result obtained by applying one hypothesis to others, as long as the conclusion is propositional, is not yet known, and has no further arguments. -/ meta def forwards_reasoning : tactic string := do hyps ← local_context, es ← hyps.mmap (λ e, (do s ← pretty_print e, return (e, [s]))), s ← mk_simp_set ff [] [], attempt_forwards_reasoning tt s.1 es attribute [forward] congr_fun
0223616cfb2302ba8b6cdb590e769689022521ab
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/LCNF/ConfigOptions.lean
a9bfc7c42c9ba4b5de9edbc0d3d2a3186a994a31
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
1,911
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.Options namespace Lean.Compiler.LCNF /-- User controlled configuration options for the code generator. -/ structure ConfigOptions where /-- Any function declaration or join point with size `≤ smallThresold` is inlined even if there are multiple occurrences. -/ smallThreshold : Nat := 1 /-- Maximum number of times a recursive definition tagged with `[inline]` can be recursively inlined before generating an error during compilation. -/ maxRecInline : Nat := 1 /-- Maximum number of times a recursive definition tagged with `[inlineIfReduce]` can be recursively inlined before generating an error during compilation. -/ maxRecInlineIfReduce : Nat := 16 deriving Inhabited register_builtin_option compiler.small : Nat := { defValue := 1 group := "compiler" descr := "(compiler) function declarations with size `≤ small` is inlined even if there are multiple occurrences." } register_builtin_option compiler.maxRecInline : Nat := { defValue := 1 group := "compiler" descr := "(compiler) maximum number of times a recursive definition tagged with `[inline]` can be recursively inlined before generating an error during compilation." } register_builtin_option compiler.maxRecInlineIfReduce : Nat := { defValue := 16 group := "compiler" descr := "(compiler) maximum number of times a recursive definition tagged with `[inlineIfReduce]` can be recursively inlined before generating an error during compilation." } def toConfigOptions (opts : Options) : ConfigOptions := { smallThreshold := compiler.small.get opts maxRecInline := compiler.maxRecInline.get opts maxRecInlineIfReduce := compiler.maxRecInlineIfReduce.get opts } end Lean.Compiler.LCNF
322373e94c8c66a6124fbc8fb21a802c89d41715
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/linear_algebra/clifford_algebra.lean
603ea51cac8a2a033b3c7df21627d5e94b1c883e
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,723
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Utensil Song. -/ import algebra.ring_quot import linear_algebra.tensor_algebra import linear_algebra.exterior_algebra import linear_algebra.quadratic_form /-! # Clifford Algebras We construct the Clifford algebra of a module `M` over a commutative ring `R`, equipped with a quadratic_form `Q`. ## Notation The Clifford algebra of the `R`-module `M` equipped with a quadratic_form `Q` is denoted as `clifford_algebra Q`. Given a linear morphism `f : M → A` from a semimodule `M` to another `R`-algebra `A`, such that `cond : ∀ m, f m * f m = algebra_map _ _ (Q m)`, there is a (unique) lift of `f` to an `R`-algebra morphism, which is denoted `clifford_algebra.lift Q f cond`. The canonical linear map `M → clifford_algebra Q` is denoted `clifford_algebra.ι Q`. ## Theorems The main theorems proved ensure that `clifford_algebra Q` satisfies the universal property of the Clifford algebra. 1. `ι_comp_lift` is the fact that the composition of `ι Q` with `lift Q f cond` agrees with `f`. 2. `lift_unique` ensures the uniqueness of `lift Q f cond` with respect to 1. Additionally, when `Q = 0` an `alg_equiv` to the `exterior_algebra` is provided as `as_exterior`. ## Implementation details The Clifford algebra of `M` is constructed as a quotient of the tensor algebra, as follows. 1. We define a relation `clifford_algebra.rel Q` on `tensor_algebra R M`. This is the smallest relation which identifies squares of elements of `M` with `Q m`. 2. The Clifford algebra is the quotient of the tensor algebra by this relation. This file is almost identical to `linear_algebra/exterior_algebra.lean`. -/ variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables (Q : quadratic_form R M) variable {n : ℕ} namespace clifford_algebra open tensor_algebra /-- `rel` relates each `ι m * ι m`, for `m : M`, with `Q m`. The Clifford algebra of `M` is defined as the quotient modulo this relation. -/ inductive rel : tensor_algebra R M → tensor_algebra R M → Prop | of (m : M) : rel (ι R m * ι R m) (algebra_map R _ (Q m)) end clifford_algebra /-- The Clifford algebra of an `R`-module `M` equipped with a quadratic_form `Q`. -/ @[derive [inhabited, ring, algebra R]] def clifford_algebra := ring_quot (clifford_algebra.rel Q) namespace clifford_algebra /-- The canonical linear map `M →ₗ[R] clifford_algebra Q`. -/ def ι : M →ₗ[R] clifford_algebra Q := (ring_quot.mk_alg_hom R _).to_linear_map.comp (tensor_algebra.ι R) /-- As well as being linear, `ι Q` squares to the quadratic form -/ @[simp] theorem ι_square_scalar (m : M) : ι Q m * ι Q m = algebra_map R _ (Q m) := begin erw [←alg_hom.map_mul, ring_quot.mk_alg_hom_rel R (rel.of m), alg_hom.commutes], refl, end variables {Q} {A : Type*} [semiring A] [algebra R A] @[simp] theorem comp_ι_square_scalar (g : clifford_algebra Q →ₐ[R] A) (m : M) : g (ι Q m) * g (ι Q m) = algebra_map _ _ (Q m) := by rw [←alg_hom.map_mul, ι_square_scalar, alg_hom.commutes] variables (Q) /-- Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition: `cond : ∀ m : M, f m * f m = Q(m)`, this is the canonical lift of `f` to a morphism of `R`-algebras from `clifford_algebra Q` to `A`. -/ @[simps symm_apply] def lift : {f : M →ₗ[R] A // ∀ m, f m * f m = algebra_map _ _ (Q m)} ≃ (clifford_algebra Q →ₐ[R] A) := { to_fun := λ f, ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : M →ₗ[R] A), (λ x y (h : rel Q x y), by { induction h, rw [alg_hom.commutes, alg_hom.map_mul, tensor_algebra.lift_ι_apply, f.prop], })⟩, inv_fun := λ F, ⟨F.to_linear_map.comp (ι Q), λ m, by rw [ linear_map.comp_apply, alg_hom.to_linear_map_apply, comp_ι_square_scalar]⟩, left_inv := λ f, by { ext, simp [ι] }, right_inv := λ F, by { ext, simp [ι] } } variables {Q} @[simp] theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) : (lift Q ⟨f, cond⟩).to_linear_map.comp (ι Q) = f := (subtype.mk_eq_mk.mp $ (lift Q).symm_apply_apply ⟨f, cond⟩) @[simp] theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) (x) : lift Q ⟨f, cond⟩ (ι Q x) = f x := (linear_map.ext_iff.mp $ ι_comp_lift f cond) x @[simp] theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m : M, f m * f m = algebra_map _ _ (Q m)) (g : clifford_algebra Q →ₐ[R] A) : g.to_linear_map.comp (ι Q) = f ↔ g = lift Q ⟨f, cond⟩ := begin convert (lift Q).symm_apply_eq, rw lift_symm_apply, simp only, end attribute [irreducible] clifford_algebra ι lift @[simp] theorem lift_comp_ι (g : clifford_algebra Q →ₐ[R] A) : lift Q ⟨g.to_linear_map.comp (ι Q), comp_ι_square_scalar _⟩ = g := begin convert (lift Q).apply_symm_apply g, rw lift_symm_apply, refl, end @[ext] theorem hom_ext {A : Type*} [semiring A] [algebra R A] {f g : clifford_algebra Q →ₐ[R] A} : f.to_linear_map.comp (ι Q) = g.to_linear_map.comp (ι Q) → f = g := begin intro h, apply (lift Q).symm.injective, rw [lift_symm_apply, lift_symm_apply], simp only [h], end /-- A Clifford algebra with a zero quadratic form is isomorphic to an `exterior_algebra` -/ def as_exterior : clifford_algebra (0 : quadratic_form R M) ≃ₐ[R] exterior_algebra R M := alg_equiv.of_alg_hom (clifford_algebra.lift 0 ⟨(exterior_algebra.ι R), by simp⟩) (exterior_algebra.lift R ⟨(ι (0 : quadratic_form R M)), by simp⟩) (by { ext, simp, }) (by { ext, simp, }) end clifford_algebra
d493d4f818f423bebfcf2ce635388e3ab2232d83
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/playground/eval2.lean
9a3b1faa0f6b1994b7fdec5d09fe65eabe2af564
[ "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
772
lean
import init.lean.evalconst open Lean def someVal := 100 def someVal2 : UInt64 := 302 def someVal3 : Bool := true def add10 (n : Nat) := n+10 def mul10 (n : Nat) := n*10 def inc (n : Nat) := n+1 unsafe def evalNatFn (fName : Name) (n : Nat) : IO Unit := do f ← evalConst (Nat → Nat) fName, IO.println (f n) unsafe def evalVal (α : Type) [Inhabited α] [HasToString α] (n : Name) : IO Unit := do v ← evalConst α n, IO.println v unsafe def main (xs : List String) : IO Unit := do let x := xs.head.toNat, sortConstTable, -- we don't sort the constant table by default in standalone applications evalNatFn `add10 x, evalNatFn `mul10 x, evalNatFn `inc x, evalVal Nat `someVal, evalVal UInt64 `someVal2, evalVal Bool `someVal3, pure ()
6ec0cd0bd17fd11f838661f1abc66692bc0efcc1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1649b.lean
3736595e1416b2c6592253db9958e3f08cf2743b
[ "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
311
lean
section parameter n : false def blah (n : false) : false := n #check @blah -- blah : false end #check @blah -- blah : false theorem fs : false → false := blah -- failed to add declaration to environment, it contains local constants #print blah -- error: invalid #print command (reported at a line below)
014408371cd040f0ae983e61220429a57096e9b0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/pfunctor/univariate/basic.lean
9b8f965f1d501e7e53ec203b010ec2363c6d02e3
[ "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
6,318
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.W /-! # Polynomial functors This file defines polynomial functors and the W-type construction as a polynomial functor. (For the M-type construction, see pfunctor/M.lean.) -/ universe u /-- A polynomial functor `P` is given by a type `A` and a family `B` of types over `A`. `P` maps any type `α` to a new type `P.obj α`, which is defined as the sigma type `Σ x, P.B x → α`. An element of `P.obj α` is a pair `⟨a, f⟩`, where `a` is an element of a type `A` and `f : B a → α`. Think of `a` as the shape of the object and `f` as an index to the relevant elements of `α`. -/ structure pfunctor := (A : Type u) (B : A → Type u) namespace pfunctor instance : inhabited pfunctor := ⟨⟨default _, default _⟩⟩ variables (P : pfunctor) {α β : Type u} /-- Applying `P` to an object of `Type` -/ def obj (α : Type*) := Σ x : P.A, P.B x → α /-- Applying `P` to a morphism of `Type` -/ def map {α β : Type*} (f : α → β) : P.obj α → P.obj β := λ ⟨a, g⟩, ⟨a, f ∘ g⟩ instance obj.inhabited [inhabited P.A] [inhabited α] : inhabited (P.obj α) := ⟨ ⟨ default _, λ _, default _ ⟩ ⟩ instance : functor P.obj := {map := @map P} protected theorem map_eq {α β : Type*} (f : α → β) (a : P.A) (g : P.B a → α) : @functor.map P.obj _ _ _ f ⟨a, g⟩ = ⟨a, f ∘ g⟩ := rfl protected theorem id_map {α : Type*} : ∀ x : P.obj α, id <$> x = id x := λ ⟨a, b⟩, rfl protected theorem comp_map {α β γ : Type*} (f : α → β) (g : β → γ) : ∀ x : P.obj α, (g ∘ f) <$> x = g <$> (f <$> x) := λ ⟨a, b⟩, rfl instance : is_lawful_functor P.obj := {id_map := @pfunctor.id_map P, comp_map := @pfunctor.comp_map P} /-- re-export existing definition of W-types and adapt it to a packaged definition of polynomial functor -/ def W := _root_.W_type P.B /- inhabitants of W types is awkward to encode as an instance assumption because there needs to be a value `a : P.A` such that `P.B a` is empty to yield a finite tree -/ attribute [nolint has_inhabited_instance] W variables {P} /-- root element of a W tree -/ def W.head : W P → P.A | ⟨a, f⟩ := a /-- children of the root of a W tree -/ def W.children : Π x : W P, P.B (W.head x) → W P | ⟨a, f⟩ := f /-- destructor for W-types -/ def W.dest : W P → P.obj (W P) | ⟨a, f⟩ := ⟨a, f⟩ /-- constructor for W-types -/ def W.mk : P.obj (W P) → W P | ⟨a, f⟩ := ⟨a, f⟩ @[simp] theorem W.dest_mk (p : P.obj (W P)) : W.dest (W.mk p) = p := by cases p; reflexivity @[simp] theorem W.mk_dest (p : W P) : W.mk (W.dest p) = p := by cases p; reflexivity variables (P) /-- `Idx` identifies a location inside the application of a pfunctor. For `F : pfunctor`, `x : F.obj α` and `i : F.Idx`, `i` can designate one part of `x` or is invalid, if `i.1 ≠ x.1` -/ def Idx := Σ x : P.A, P.B x instance Idx.inhabited [inhabited P.A] [inhabited (P.B (default _))] : inhabited P.Idx := ⟨ ⟨default _, default _⟩ ⟩ variables {P} /-- `x.iget i` takes the component of `x` designated by `i` if any is or returns a default value -/ def obj.iget [decidable_eq P.A] {α} [inhabited α] (x : P.obj α) (i : P.Idx) : α := if h : i.1 = x.1 then x.2 (cast (congr_arg _ h) i.2) else default _ @[simp] lemma fst_map {α β : Type u} (x : P.obj α) (f : α → β) : (f <$> x).1 = x.1 := by { cases x; refl } @[simp] lemma iget_map [decidable_eq P.A] {α β : Type u} [inhabited α] [inhabited β] (x : P.obj α) (f : α → β) (i : P.Idx) (h : i.1 = x.1) : (f <$> x).iget i = f (x.iget i) := by { simp only [obj.iget, fst_map, *, dif_pos, eq_self_iff_true], cases x, refl } end pfunctor /- Composition of polynomial functors. -/ namespace pfunctor /-- functor composition for polynomial functors -/ def comp (P₂ P₁ : pfunctor.{u}) : pfunctor.{u} := ⟨ Σ a₂ : P₂.1, P₂.2 a₂ → P₁.1, λ a₂a₁, Σ u : P₂.2 a₂a₁.1, P₁.2 (a₂a₁.2 u) ⟩ /-- constructor for composition -/ def comp.mk (P₂ P₁ : pfunctor.{u}) {α : Type} (x : P₂.obj (P₁.obj α)) : (comp P₂ P₁).obj α := ⟨ ⟨ x.1, sigma.fst ∘ x.2 ⟩, λ a₂a₁, (x.2 a₂a₁.1).2 a₂a₁.2 ⟩ /-- destructor for composition -/ def comp.get (P₂ P₁ : pfunctor.{u}) {α : Type} (x : (comp P₂ P₁).obj α) : P₂.obj (P₁.obj α) := ⟨ x.1.1, λ a₂, ⟨x.1.2 a₂, λ a₁, x.2 ⟨a₂,a₁⟩ ⟩ ⟩ end pfunctor /- Lifting predicates and relations. -/ namespace pfunctor variables {P : pfunctor.{u}} open functor theorem liftp_iff {α : Type u} (p : α → Prop) (x : P.obj α) : liftp p x ↔ ∃ a f, x = ⟨a, f⟩ ∧ ∀ i, p (f i) := begin split, { rintros ⟨y, hy⟩, cases h : y with a f, refine ⟨a, λ i, (f i).val, _, λ i, (f i).property⟩, rw [←hy, h, pfunctor.map_eq] }, rintros ⟨a, f, xeq, pf⟩, use ⟨a, λ i, ⟨f i, pf i⟩⟩, rw [xeq], reflexivity end theorem liftp_iff' {α : Type u} (p : α → Prop) (a : P.A) (f : P.B a → α) : @liftp.{u} P.obj _ α p ⟨a,f⟩ ↔ ∀ i, p (f i) := begin simp only [liftp_iff, sigma.mk.inj_iff]; split; intro, { casesm* [Exists _, _ ∧ _], subst_vars, assumption }, repeat { constructor <|> assumption } end theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : P.obj α) : liftr r x y ↔ ∃ a f₀ f₁, x = ⟨a, f₀⟩ ∧ y = ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) := begin split, { rintros ⟨u, xeq, yeq⟩, cases h : u with a f, use [a, λ i, (f i).val.fst, λ i, (f i).val.snd], split, { rw [←xeq, h], refl }, split, { rw [←yeq, h], refl }, intro i, exact (f i).property }, rintros ⟨a, f₀, f₁, xeq, yeq, h⟩, use ⟨a, λ i, ⟨(f₀ i, f₁ i), h i⟩⟩, split, { rw [xeq], refl }, rw [yeq], refl end open set theorem supp_eq {α : Type u} (a : P.A) (f : P.B a → α) : @supp.{u} P.obj _ α (⟨a,f⟩ : P.obj α) = f '' univ := begin ext, simp only [supp, image_univ, mem_range, mem_set_of_eq], split; intro h, { apply @h (λ x, ∃ (y : P.B a), f y = x), rw liftp_iff', intro, refine ⟨_,rfl⟩ }, { simp only [liftp_iff'], cases h, subst x, tauto } end end pfunctor
bbcb08210e1b849d002f7f8bf75dbb30627a974c
947fa6c38e48771ae886239b4edce6db6e18d0fb
/archive/imo/imo2013_q5.lean
925a5b83d95966d1d1af38175c6a7ebf6fb6fdc2
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
12,987
lean
/- Copyright (c) 2021 David Renshaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Renshaw -/ import algebra.geom_sum import data.rat.defs import data.real.basic import tactic.positivity /-! # IMO 2013 Q5 Let `ℚ>₀` be the positive rational numbers. Let `f : ℚ>₀ → ℝ` be a function satisfying the conditions 1. `f(x) * f(y) ≥ f(x * y)` 2. `f(x + y) ≥ f(x) + f(y)` for all `x, y ∈ ℚ>₀`. Given that `f(a) = a` for some rational `a > 1`, prove that `f(x) = x` for all `x ∈ ℚ>₀`. # Solution We provide a direct translation of the solution found in https://www.imo-official.org/problems/IMO2013SL.pdf -/ open_locale big_operators lemma le_of_all_pow_lt_succ {x y : ℝ} (hx : 1 < x) (hy : 1 < y) (h : ∀ n : ℕ, 0 < n → x^n - 1 < y^n) : x ≤ y := begin by_contra' hxy, have hxmy : 0 < x - y := sub_pos.mpr hxy, have hn : ∀ n : ℕ, 0 < n → (x - y) * (n : ℝ) ≤ x^n - y^n, { intros n hn, have hterm : ∀ i : ℕ, i ∈ finset.range n → 1 ≤ x^i * y^(n - 1 - i), { intros i hi, have hx' : 1 ≤ x ^ i := one_le_pow_of_one_le hx.le i, have hy' : 1 ≤ y ^ (n - 1 - i) := one_le_pow_of_one_le hy.le (n - 1 - i), calc 1 ≤ x^i : hx' ... = x^i * 1 : (mul_one _).symm ... ≤ x^i * y^(n-1-i) : mul_le_mul_of_nonneg_left hy' (zero_le_one.trans hx') }, calc (x - y) * (n : ℝ) = (n : ℝ) * (x - y) : mul_comm _ _ ... = (∑ (i : ℕ) in finset.range n, (1 : ℝ)) * (x - y) : by simp only [mul_one, finset.sum_const, nsmul_eq_mul, finset.card_range] ... ≤ (∑ (i : ℕ) in finset.range n, x ^ i * y ^ (n - 1 - i)) * (x-y) : (mul_le_mul_right hxmy).mpr (finset.sum_le_sum hterm) ... = x^n - y^n : geom_sum₂_mul x y n, }, -- Choose n larger than 1 / (x - y). obtain ⟨N, hN⟩ := exists_nat_gt (1 / (x - y)), have hNp : 0 < N, { exact_mod_cast (one_div_pos.mpr hxmy).trans hN }, have := calc 1 = (x - y) * (1 / (x - y)) : by field_simp [ne_of_gt hxmy] ... < (x - y) * N : (mul_lt_mul_left hxmy).mpr hN ... ≤ x^N - y^N : hn N hNp, linarith [h N hNp] end /-- Like le_of_all_pow_lt_succ, but with a weaker assumption for y. -/ lemma le_of_all_pow_lt_succ' {x y : ℝ} (hx : 1 < x) (hy : 0 < y) (h : ∀ n : ℕ, 0 < n → x^n - 1 < y^n) : x ≤ y := begin refine le_of_all_pow_lt_succ hx _ h, by_contra' hy'' : y ≤ 1, -- Then there exists y' such that 0 < y ≤ 1 < y' < x. let y' := (x + 1) / 2, have h_y'_lt_x : y' < x, { have hh : (x + 1)/2 < (x * 2) / 2, { linarith }, calc y' < (x * 2) / 2 : hh ... = x : by field_simp }, have h1_lt_y' : 1 < y', { have hh' : 1 * 2 / 2 < (x + 1) / 2, { linarith }, calc 1 = 1 * 2 / 2 : by field_simp ... < y' : hh' }, have h_y_lt_y' : y < y' := hy''.trans_lt h1_lt_y', have hh : ∀ n, 0 < n → x^n - 1 < y'^n, { intros n hn, calc x^n - 1 < y^n : h n hn ... ≤ y'^n : pow_le_pow_of_le_left hy.le h_y_lt_y'.le n }, exact h_y'_lt_x.not_le (le_of_all_pow_lt_succ hx h1_lt_y' hh) end lemma f_pos_of_pos {f : ℚ → ℝ} {q : ℚ} (hq : 0 < q) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) : 0 < f q := begin have num_pos : 0 < q.num := rat.num_pos_iff_pos.mpr hq, have hmul_pos := calc (0 : ℝ) < q.num : int.cast_pos.mpr num_pos ... = ((q.num.nat_abs : ℤ) : ℝ) : congr_arg coe (int.nat_abs_of_nonneg num_pos.le).symm ... ≤ f q.num.nat_abs : H4 q.num.nat_abs (int.nat_abs_pos_of_ne_zero num_pos.ne') ... = f q.num : by { rw ←int.nat_abs_of_nonneg num_pos.le, norm_cast } ... = f (q * q.denom) : by rw ←rat.mul_denom_eq_num ... ≤ f q * f q.denom : H1 q q.denom hq (nat.cast_pos.mpr q.pos), have h_f_denom_pos := calc (0 : ℝ) < q.denom : nat.cast_pos.mpr q.pos ... ≤ f q.denom : H4 q.denom q.pos, exact pos_of_mul_pos_left hmul_pos h_f_denom_pos.le, end lemma fx_gt_xm1 {f : ℚ → ℝ} {x : ℚ} (hx : 1 ≤ x) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) : (x - 1 : ℝ) < f x := begin have hx0 := calc (x - 1 : ℝ) < ⌊x⌋₊ : by exact_mod_cast nat.sub_one_lt_floor x ... ≤ f ⌊x⌋₊ : H4 _ (nat.floor_pos.2 hx), obtain h_eq | h_lt := (nat.floor_le $ zero_le_one.trans hx).eq_or_lt, { rwa h_eq at hx0 }, calc (x - 1 : ℝ) < f ⌊x⌋₊ : hx0 ... < f (x - ⌊x⌋₊) + f ⌊x⌋₊ : lt_add_of_pos_left _ (f_pos_of_pos (sub_pos.mpr h_lt) H1 H4) ... ≤ f (x - ⌊x⌋₊ + ⌊x⌋₊) : H2 _ _ (sub_pos.mpr h_lt) (nat.cast_pos.2 (nat.floor_pos.2 hx)) ... = f x : by rw sub_add_cancel end lemma pow_f_le_f_pow {f : ℚ → ℝ} {n : ℕ} (hn : 0 < n) {x : ℚ} (hx : 1 < x) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) : f (x^n) ≤ (f x)^n := begin induction n with pn hpn, { exfalso, exact nat.lt_asymm hn hn }, cases pn, { simp only [pow_one] }, have hpn' := hpn pn.succ_pos, rw [pow_succ' x (pn + 1), pow_succ' (f x) (pn + 1)], have hxp : 0 < x := by positivity, calc f ((x ^ (pn+1)) * x) ≤ f (x ^ (pn+1)) * f x : H1 (x ^ (pn+1)) x (pow_pos hxp (pn+1)) hxp ... ≤ (f x) ^ (pn+1) * f x : (mul_le_mul_right (f_pos_of_pos hxp H1 H4)).mpr hpn' end lemma fixed_point_of_pos_nat_pow {f : ℚ → ℝ} {n : ℕ} (hn : 0 < n) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) (H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x) {a : ℚ} (ha1 : 1 < a) (hae : f a = a) : f (a^n) = a^n := begin have hh0 : (a : ℝ) ^ n ≤ f (a ^ n), { exact_mod_cast H5 (a ^ n) (one_lt_pow ha1 hn.ne') }, have hh1 := calc f (a^n) ≤ (f a)^n : pow_f_le_f_pow hn ha1 H1 H4 ... = (a : ℝ)^n : by rw ← hae, exact hh1.antisymm hh0 end lemma fixed_point_of_gt_1 {f : ℚ → ℝ} {x : ℚ} (hx : 1 < x) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) (H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x) {a : ℚ} (ha1 : 1 < a) (hae : f a = a) : f x = x := begin -- Choose n such that 1 + x < a^n. obtain ⟨N, hN⟩ := pow_unbounded_of_one_lt (1 + x) ha1, have h_big_enough : (1:ℚ) < a^N - x := lt_sub_iff_add_lt.mpr hN, have h1 := calc (x : ℝ) + ((a^N - x) : ℚ) ≤ f x + ((a^N - x) : ℚ) : add_le_add_right (H5 x hx) _ ... ≤ f x + f (a^N - x) : add_le_add_left (H5 _ h_big_enough) _, have hxp : 0 < x := by positivity, have hNp : 0 < N, { by_contra' H, rw [nat.le_zero_iff.mp H] at hN, linarith }, have h2 := calc f x + f (a^N - x) ≤ f (x + (a^N - x)) : H2 x (a^N - x) hxp (zero_lt_one.trans h_big_enough) ... = f (a^N) : by ring_nf ... = a^N : fixed_point_of_pos_nat_pow hNp H1 H4 H5 ha1 hae ... = x + (a^N - x) : by ring, have heq := h1.antisymm (by exact_mod_cast h2), linarith [H5 x hx, H5 _ h_big_enough] end theorem imo2013_q5 (f : ℚ → ℝ) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H_fixed_point : ∃ a, 1 < a ∧ f a = a) : ∀ x, 0 < x → f x = x := begin obtain ⟨a, ha1, hae⟩ := H_fixed_point, have H3 : ∀ x : ℚ, 0 < x → ∀ n : ℕ, 0 < n → ↑n * f x ≤ f (n * x), { intros x hx n hn, cases n, { exact (lt_irrefl 0 hn).elim }, induction n with pn hpn, { simp only [one_mul, nat.cast_one] }, calc ↑(pn + 2) * f x = (↑pn + 1 + 1) * f x : by norm_cast ... = ((pn : ℝ) + 1) * f x + 1 * f x : add_mul (↑pn + 1) 1 (f x) ... = (↑pn + 1) * f x + f x : by rw one_mul ... ≤ f ((↑pn.succ) * x) + f x : by exact_mod_cast add_le_add_right (hpn pn.succ_pos) (f x) ... ≤ f ((↑pn + 1) * x + x) : by exact_mod_cast H2 _ _ (mul_pos pn.cast_add_one_pos hx) hx ... = f ((↑pn + 1) * x + 1 * x) : by rw one_mul ... = f ((↑pn + 1 + 1) * x) : congr_arg f (add_mul (↑pn + 1) 1 x).symm ... = f (↑(pn + 2) * x) : by norm_cast }, have H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n, { intros n hn, have hf1 : 1 ≤ f 1, { have a_pos : (0 : ℝ) < a := rat.cast_pos.mpr (zero_lt_one.trans ha1), suffices : ↑a * 1 ≤ ↑a * f 1, from (mul_le_mul_left a_pos).mp this, calc ↑a * 1 = ↑a : mul_one ↑a ... = f a : hae.symm ... = f (a * 1) : by rw mul_one ... ≤ f a * f 1 : (H1 a 1) (zero_lt_one.trans ha1) zero_lt_one ... = ↑a * f 1 : by rw hae }, calc (n : ℝ) = (n : ℝ) * 1 : (mul_one _).symm ... ≤ (n : ℝ) * f 1 : mul_le_mul_of_nonneg_left hf1 (nat.cast_nonneg _) ... ≤ f (n * 1) : H3 1 zero_lt_one n hn ... = f n : by rw mul_one }, have H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x, { intros x hx, have hxnm1 : ∀ n : ℕ, 0 < n → (x : ℝ)^n - 1 < (f x)^n, { intros n hn, calc (x : ℝ)^n - 1 < f (x^n) : by exact_mod_cast fx_gt_xm1 (one_le_pow_of_one_le hx.le n) H1 H2 H4 ... ≤ (f x)^n : pow_f_le_f_pow hn hx H1 H4 }, have hx' : 1 < (x : ℝ) := by exact_mod_cast hx, have hxp : 0 < x := by positivity, exact le_of_all_pow_lt_succ' hx' (f_pos_of_pos hxp H1 H4) hxnm1 }, have h_f_commutes_with_pos_nat_mul : ∀ n : ℕ, 0 < n → ∀ x : ℚ, 0 < x → f (n * x) = n * f x, { intros n hn x hx, have h2 : f (n * x) ≤ n * f x, { cases n, { exfalso, exact nat.lt_asymm hn hn }, cases n, { simp only [one_mul, nat.cast_one] }, have hfneq : f (n.succ.succ) = n.succ.succ, { have := fixed_point_of_gt_1 (nat.one_lt_cast.mpr (nat.succ_lt_succ n.succ_pos)) H1 H2 H4 H5 ha1 hae, rwa (rat.cast_coe_nat n.succ.succ) at this }, rw ← hfneq, exact H1 (n.succ.succ : ℚ) x (nat.cast_pos.mpr hn) hx }, exact h2.antisymm (H3 x hx n hn) }, -- For the final calculation, we expand x as (2*x.num) / (2*x.denom), because -- we need the top of the fraction to be strictly greater than 1 in order -- to apply fixed_point_of_gt_1. intros x hx, let x2denom := 2 * x.denom, let x2num := 2 * x.num, have hx2pos := calc 0 < x.denom : x.pos ... < x.denom + x.denom : lt_add_of_pos_left x.denom x.pos ... = 2 * x.denom : by ring, have hxcnez : (x.denom : ℚ) ≠ (0 : ℚ) := ne_of_gt (nat.cast_pos.mpr x.pos), have hx2cnezr : (x2denom : ℝ) ≠ (0 : ℝ) := nat.cast_ne_zero.mpr (ne_of_gt hx2pos), have hrat_expand2 := calc x = x.num / x.denom : by exact_mod_cast rat.num_denom.symm ... = x2num / x2denom : by { field_simp [-rat.num_div_denom], linarith }, have h_denom_times_fx := calc (x2denom : ℝ) * f x = f (x2denom * x) : (h_f_commutes_with_pos_nat_mul x2denom hx2pos x hx).symm ... = f (x2denom * (x2num / x2denom)) : by rw hrat_expand2 ... = f x2num : by { congr, field_simp, ring }, have h_fx2num_fixed : f x2num = x2num, { have hx2num_gt_one : (1 : ℚ) < (2 * x.num : ℤ), { norm_cast, linarith [rat.num_pos_iff_pos.mpr hx] }, have hh := fixed_point_of_gt_1 hx2num_gt_one H1 H2 H4 H5 ha1 hae, rwa (rat.cast_coe_int x2num) at hh }, calc f x = f x * 1 : (mul_one (f x)).symm ... = f x * (x2denom / x2denom) : by rw ←(div_self hx2cnezr) ... = (f x * x2denom) / x2denom : mul_div_assoc' (f x) _ _ ... = (x2denom * f x) / x2denom : by rw mul_comm ... = f x2num / x2denom : by rw h_denom_times_fx ... = x2num / x2denom : by rw h_fx2num_fixed ... = (((x2num : ℚ) / (x2denom : ℚ) : ℚ) : ℝ) : by norm_cast ... = x : by rw ←hrat_expand2 end
8e7aed5211d0810d9c3c59b2d0d7c225e78f11d0
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/library/init/meta/tactic.lean
21fed20cbc10c9c7161f3fd0adf3204ce589b5fe
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,685
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment meta constant to_format : tactic_state → format /- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { interaction_monad.monad with failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _ } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) open nat /- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨fmap to_fmt ∘ monad.mapm pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := take state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : tactic α) : tactic α := λ s, timeit desc (t s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s inductive transparency | all | semireducible | reducible | none export transparency (reducible semireducible) /- (eval_expr α α_as_expr e) evaluates 'e' IF 'e' has type 'α'. 'α' must be a closed term. 'α_as_expr' is synthesized by the code generator. 'e' must be a closed expression at runtime. -/ meta constant eval_expr (α : Type u) {α_expr : pexpr} : expr → tactic α /- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /- Display the partial term/proof constructed so far. This tactic is *not* equivalent to do { r ← result, s ← read, return (format_expr s r) } because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. -/ meta constant whnf (e : expr) (md := semireducible) : tactic expr /- (head) eta expand the given expression -/ meta constant head_eta_expand : expr → tactic expr /- (head) beta reduction -/ meta constant head_beta : expr → tactic expr /- (head) zeta reduction -/ meta constant head_zeta : expr → tactic expr /- zeta reduction -/ meta constant zeta : expr → tactic expr /- (head) eta reduction -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) : tactic unit /- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit /- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name : name → option nat → tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply susbstitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. If `allow_mvars` is tt, then metavariables are tolerated and become new goals. If `report_errors` is ff, then errors are reported using position information from q. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) : tactic expr /- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /- Change the target of the main goal. The input expression must be definitionally equal to the current target. -/ meta constant change : expr → tactic unit /- (assert_core H T), adds a new goal for T, and change target to (T -> target). -/ meta constant assert_core : name → expr → tactic unit /- (assertv_core H T P), change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /- (define_core H T), adds a new goal for T, and change target to (let H : T := ?M in target) in the current goal. -/ meta constant define_core : name → expr → tactic unit /- (definev_core H T P), change target to (Let H : T := P in target) if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit /-- Configuration options for the `apply` tactic. -/ structure apply_cfg := (md := semireducible) (approx := tt) (all := ff) (use_instances := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. If cfg.approx is `tt`, then fallback to first-order unification, and approximate context during unification. If cfg.all is `tt`, then all unassigned meta-variables are added as new goals. If cfg.use_instances is `tt`, then use type class resolution to instantiate unassigned meta-variables. It returns a list of all introduced meta variables, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list expr) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr meta constant mk_fresh_name : tactic name /- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal a list of new hypotheses and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (list expr × list (name × expr))) /- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr meta constant module_doc_strings : tactic (list (option name × string)) /- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /- (unset_attribute attr_name c_name) -/ meta constant unset_attribute : name → name → tactic unit /- (has_attribute attr_name c_name) succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat /- (copy_attribute attr_name c_name d_name) copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /- (save_type_info e ref) save (typeof e) at position associated with ref -/ meta constant save_type_info : expr → expr → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool open list nat meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (step t s)).clamp_pos line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = ```(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none meta def whnf_target : tactic unit := target >>= whnf >>= change meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← pexpr.to_raw_expr <$> resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible /- (find_same_type t es) tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := show p, by assumption /- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /- (assert h t), adds a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : tactic unit := assert_core h t >> swap >> intro h >> swap /- (assertv h t v), adds the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic unit := assertv_core h t v >> intro h >> return () /- (define h t), adds a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : tactic unit := define_core h t >> swap >> intro h >> swap /- (definev h t v), adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic unit := definev_core h t v >> intro h >> return () /- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (pr : expr) : tactic unit := do t ← infer_type pr, definev h t pr /- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (n : name) (pr : expr) : tactic unit := do t ← infer_type pr, assertv n t pr /- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /- first [t_1, ..., t_n] applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "focus tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "focus tactic failed, focused goal has not been solved" end end /- solve [t_1, ... t_n] applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] gs rs := set_goals $ rs ++ gs | (t::ts) (g::gs) rs := do set_goals [g], t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" /- focus [t_1, ..., t_n] applies t_i to the i-th goal. Fails if there are less tha n goals. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance : has_andthen (tactic unit) := ⟨seq⟩ meta constant is_trace_enabled_for : name → bool /- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /- Fail if there are unsolved goals. -/ meta def now : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "now tactic failed, there are unsolved goals") meta def apply (e : expr) : tactic unit := apply_core e >> return () meta def fapply (e : expr) : tactic unit := apply_core e {all := tt} >> return () /- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /- Return (expr.const c [l_1, ..., l_n]) where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) : tactic unit := mk_const c >>= apply meta def save_const_type_info (n : name) (ref : expr) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /- Create a fresh universe ?u, a metavariable (?T : Type.{?u}), and return metavariable (?M : ?T). This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : name) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= apply) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", intro H private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic unit := if e.is_local_constant then cases_core e ids md >> return () else do x ← mk_fresh_name, n ← revert_kdependencies e dmd, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, (step (cases_core h ids md); intron n) meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ to_string i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /- (solve_aux type tac) synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) meta def apply_opt_param : tactic unit := do ```(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do ```(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Define id_locked using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_locked is used in the builtin implementation of tactic.change -/ run_cmd do let l := level.param `l, let Ty := expr.sort l, type ← to_expr ``(Π (α : %%Ty), α → α), val ← to_expr ``(λ (α : %%Ty) (a : α), a), add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt) lemma id_locked_eq {α : Type u} (a : α) : id_locked α a = a := rfl /- Install monad laws tactic and use it to prove some instances. -/ meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact meta def unsafe_monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind, id_map := undefined, pure_bind := undefined, bind_assoc := undefined} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined}
a74031962c12804b761ff4a6ab0e6277993b2191
bdb33f8b7ea65f7705fc342a178508e2722eb851
/order/conditionally_complete_lattice.lean
d897487b0c1d2ae6ae87399e2397b8222dc5b96b
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
21,190
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Adapted from the corresponding theory for complete lattices. Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and non-emptyness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ import order.lattice order.complete_lattice tactic.finish data.set.countable set_option old_structure_cmd true open preorder set lattice universes u v variables {α : Type u} {β : Type v} section preorder variables [preorder α] {s t : set α} {a b : α} /-Sets bounded above and bounded below.-/ def bdd_above (s : set α) := ∃x, ∀y∈s, y ≤ x def bdd_below (s : set α) := ∃x, ∀y∈s, x ≤ y /-Introduction rules for boundedness above and below. Most of the time, it is more efficient to use ⟨w, P⟩ where P is a proof that all elements of the set are bounded by w. However, they are sometimes handy.-/ lemma bdd_above.mk (a : α) (H : ∀y∈s, y≤a) : bdd_above s := ⟨a, H⟩ lemma bdd_below.mk (a : α) (H : ∀y∈s, a≤y) : bdd_below s := ⟨a, H⟩ /-Empty sets and singletons are trivially bounded. For finite sets, we need a notion of maximum and minimum, i.e., a lattice structure, see later on.-/ @[simp] lemma bdd_above_empty [inhabited α] : bdd_above (∅ : set α) := ⟨default α, by simp⟩ @[simp] lemma bdd_below_empty [inhabited α] : bdd_below (∅ : set α) := ⟨default α, by simp⟩ @[simp] lemma bdd_above_singleton : bdd_above ({a} : set α) := ⟨a, by simp⟩ @[simp] lemma bdd_below_singleton : bdd_below ({a} : set α) := ⟨a, by simp⟩ /-If a set is included in another one, boundedness of the second implies boundedness of the first-/ lemma bdd_above_subset (_ : s ⊆ t) (_ : bdd_above t) : bdd_above s := let ⟨w, hw⟩ := ‹bdd_above t› in /-hw : ∀ (y : α), y ∈ t → y ≤ w-/ ⟨w, assume (y : α) (_ : y ∈ s), hw _ (‹s ⊆ t› ‹y ∈ s›)⟩ lemma bdd_below_subset (_ : s ⊆ t) (_ : bdd_below t) : bdd_below s := let ⟨w, hw⟩ := ‹bdd_below t› in /-hw : ∀ (y : α), y ∈ t → w ≤ y-/ ⟨w, assume (y : α) (_ : y ∈ s), hw _ (‹s ⊆ t› ‹y ∈ s›)⟩ /- Boundedness of intersections of sets, in different guises, deduced from the monotonicity of boundedness.-/ lemma bdd_above_Int1 (_ : bdd_above s) : bdd_above (s ∩ t) := by apply bdd_above_subset _ ‹bdd_above s›; simp lemma bdd_above_Int2 (_ : bdd_above t) : bdd_above (s ∩ t) := by apply bdd_above_subset _ ‹bdd_above t›; simp lemma bdd_below_Int1 (_ : bdd_below s) : bdd_below (s ∩ t) := by apply bdd_below_subset _ ‹bdd_below s›; simp lemma bdd_below_Int2 (_ : bdd_below t) : bdd_below (s ∩ t) := by apply bdd_below_subset _ ‹bdd_below t›; simp end preorder /--When there is a global maximum, every set is bounded above.-/ @[simp] lemma bdd_above_top [order_top α] (s : set α) : bdd_above s := ⟨⊤, by intros; apply order_top.le_top⟩ /--When there is a global minimum, every set is bounded below.-/ @[simp] lemma bdd_above_bot [order_bot α] (s : set α): bdd_below s := ⟨⊥, by intros; apply order_bot.bot_le⟩ /-When there is a max (i.e., in the class semilattice_sup), then the union of two bounded sets is bounded, by the maximum of the bounds for the two sets. With this, we deduce that finite sets are bounded by induction, and that a finite union of bounded sets is bounded.-/ section semilattice_sup variables [semilattice_sup α] {s t : set α} {a b : α} /--The union of two sets is bounded above if and only if each of the sets is.-/ @[simp] lemma bdd_above_union : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t := ⟨show bdd_above (s ∪ t) → (bdd_above s ∧ bdd_above t), from assume : bdd_above (s ∪ t), have S : bdd_above s, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp, have T : bdd_above t, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp, and.intro S T, show (bdd_above s ∧ bdd_above t) → bdd_above (s ∪ t), from assume H : bdd_above s ∧ bdd_above t, let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in /-hs : ∀ (y : α), y ∈ s → y ≤ ws ht : ∀ (y : α), y ∈ s → y ≤ wt-/ have Bs : ∀b∈s, b ≤ ws ⊔ wt, by intros; apply le_trans (hs b ‹b ∈ s›) _; simp, have Bt : ∀b∈t, b ≤ ws ⊔ wt, by intros; apply le_trans (ht b ‹b ∈ t›) _; simp, show bdd_above (s ∪ t), begin apply bdd_above.mk (ws ⊔ wt), intros b H_1, cases H_1, apply Bs _ ‹b ∈ s›, apply Bt _ ‹b ∈ t›, end⟩ /--Adding a point to a set preserves its boundedness above.-/ @[simp] lemma bdd_above_insert : bdd_above (insert a s) ↔ bdd_above s := ⟨show bdd_above (insert a s) → bdd_above s, from bdd_above_subset (by simp), show bdd_above s → bdd_above (insert a s), by rw[insert_eq]; finish⟩ /--A finite set is bounded above.-/ lemma bdd_above_finite [inhabited α] (_ : finite s) : bdd_above s := by apply finite.induction_on ‹finite s›; simp; simp /--A finite union of sets which are all bounded above is still bounded above.-/ lemma bdd_above_finite_union [inhabited α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := ⟨show (bdd_above (⋃i∈I, S i)) → (∀i ∈ I, bdd_above (S i)), by intros; apply bdd_above_subset _ ‹bdd_above (⋃i∈I, S i)›; apply subset_bUnion_of_mem ‹i ∈ I›, show (∀i ∈ I, bdd_above (S i)) → (bdd_above (⋃i∈I, S i)), by apply finite.induction_on ‹finite I›; simp; finish⟩ end semilattice_sup /-When there is a min (i.e., in the class semilattice_inf), then the union of two sets which are bounded from below is bounded from below, by the minimum of the bounds for the two sets. With this, we deduce that finite sets are bounded below by induction, and that a finite union of sets which are bounded below is still bounded below.-/ section semilattice_inf variables [semilattice_inf α] {s t : set α} {a b : α} /--The union of two sets is bounded below if and only if each of the sets is.-/ @[simp] lemma bdd_below_union : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t := ⟨show bdd_below (s ∪ t) → (bdd_below s ∧ bdd_below t), from assume : bdd_below (s ∪ t), have S : bdd_below s, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp, have T : bdd_below t, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp, and.intro S T, show (bdd_below s ∧ bdd_below t) → bdd_below (s ∪ t), from assume H : bdd_below s ∧ bdd_below t, let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in /-hs : ∀ (y : α), y ∈ s → ws ≤ y ht : ∀ (y : α), y ∈ s → wt ≤ y-/ have Bs : ∀b∈s, ws ⊓ wt ≤ b, by intros; apply le_trans _ (hs b ‹b ∈ s›); simp, have Bt : ∀b∈t, ws ⊓ wt ≤ b, by intros; apply le_trans _ (ht b ‹b ∈ t›); simp, show bdd_below (s ∪ t), begin apply bdd_below.mk (ws ⊓ wt), intros b H_1, cases H_1, apply Bs _ ‹b ∈ s›, apply Bt _ ‹b ∈ t›, end⟩ /--Adding a point to a set preserves its boundedness below.-/ @[simp] lemma bdd_below_insert : bdd_below (insert a s) ↔ bdd_below s := ⟨show bdd_below (insert a s) → bdd_below s, from bdd_below_subset (by simp), show bdd_below s → bdd_below (insert a s), by rw[insert_eq]; finish⟩ /--A finite set is bounded below.-/ lemma bdd_below_finite [inhabited α] (_ : finite s) : bdd_below s := by apply finite.induction_on ‹finite s›; simp; simp /--A finite union of sets which are all bounded below is still bounded below.-/ lemma bdd_below_finite_union [inhabited α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := ⟨show (bdd_below (⋃i∈I, S i)) → (∀i ∈ I, bdd_below (S i)), by intros; apply bdd_below_subset _ ‹bdd_below (⋃i∈I, S i)›; apply subset_bUnion_of_mem ‹i ∈ I›, show (∀i ∈ I, bdd_below (S i)) → (bdd_below (⋃i∈I, S i)), by apply finite.induction_on ‹finite I›; simp; finish⟩ end semilattice_inf namespace lattice /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of non-emptyness or boundedness.-/ class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀s a, s ≠ ∅ → (∀b∈s, b ≤ a) → Sup s ≤ a) (cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀s a, s ≠ ∅ → (∀b∈s, a ≤ b) → a ≤ Inf s) class conditionally_complete_linear_order (α : Type u) extends conditionally_complete_lattice α, linear_order α /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]: conditionally_complete_lattice α := {le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α›} section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s ≠ ∅) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s ≠ ∅) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup ‹bdd_above s› hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le ‹bdd_below s› hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s ≠ ∅) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le ‹s ≠ ∅› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ :s ≠ ∅) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf ‹s ≠ ∅› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha)) theorem cSup_le_iff (_ : bdd_above s) (_ : s ≠ ∅) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := ⟨assume (_ : Sup s ≤ a) (b) (_ : b ∈ s), le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) ‹Sup s ≤ a›, cSup_le ‹s ≠ ∅›⟩ theorem le_cInf_iff (_ : bdd_below s) (_ : s ≠ ∅) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := ⟨assume (_ : a ≤ Inf s) (b) (_ : b ∈ s), le_trans ‹a ≤ Inf s› (cInf_le ‹bdd_below s› ‹b ∈ s›), le_cInf ‹s ≠ ∅›⟩ /--Introduction rule to prove that b is the supremum of s: it suffices to check that b is larger than all elements of s, and that this is not the case of any w<b.-/ theorem cSup_intro (_ : s ≠ ∅) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹s ≠ ∅› ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that b is the infimum of s: it suffices to check that b is smaller than all elements of s, and that this is not the case of any w>b.-/ theorem cInf_intro (_ : s ≠ ∅) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := have bdd_below s := ⟨b, by assumption⟩, have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹s ≠ ∅› ‹∀a∈s, b ≤ a›), have ¬(b < Inf s) := assume: b < Inf s, let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/ have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› , show false, by finish [lt_irrefl (Inf s)], show Inf s = b, by finish /--When an element a of a set s is larger than all elements of the set, it is Sup s-/ theorem cSup_of_in_of_le (_ : a ∈ s) (_ : ∀w∈s, w ≤ a) : Sup s = a := have bdd_above s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : a ≤ Sup s := le_cSup ‹bdd_above s› ‹a ∈ s›, have B : Sup s ≤ a := cSup_le ‹s ≠ ∅› ‹∀w∈s, w ≤ a›, le_antisymm B A /--When an element a of a set s is smaller than all elements of the set, it is Inf s-/ theorem cInf_of_in_of_le (_ : a ∈ s) (_ : ∀w∈s, a ≤ w) : Inf s = a := have bdd_below s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : Inf s ≤ a := cInf_le ‹bdd_below s› ‹a ∈ s›, have B : a ≤ Inf s := le_cInf ‹s ≠ ∅› ‹∀w∈s, a ≤ w›, le_antisymm A B /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptyness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›) /--Inf s < b s when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptyness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b› /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := have A : a ≤ Sup {a} := by apply le_cSup _ _; simp; simp, have B : Sup {a} ≤ a := by apply cSup_le _ _; simp; simp, le_antisymm B A /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := have A : Inf {a} ≤ a := by apply cInf_le _ _; simp; simp, have B : a ≤ Inf {a} := by apply le_cInf _ _; simp; simp, le_antisymm A B /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (_ : bdd_below s) (_ : bdd_above s) (_ : s ≠ ∅) : Inf s ≤ Sup s := let ⟨w, hw⟩ := exists_mem_of_ne_empty ‹s ≠ ∅› in /-hw : w ∈ s-/ have Inf s ≤ w := cInf_le ‹bdd_below s› ‹w ∈ s›, have w ≤ Sup s := le_cSup ‹bdd_above s› ‹w ∈ s›, le_trans ‹Inf s ≤ w› ‹w ≤ Sup s› /--The sup of a union of sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (_ : bdd_above s) (_ : s ≠ ∅) (_ : bdd_above t) (_ : t ≠ ∅) : Sup (s ∪ t) = Sup s ⊔ Sup t := have A : Sup (s ∪ t) ≤ Sup s ⊔ Sup t := have s ∪ t ≠ ∅ := by simp at *; finish, have F : ∀b∈ s∪t, b ≤ Sup s ⊔ Sup t := begin intros, cases H, apply le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) _, simp, apply le_trans (le_cSup ‹bdd_above t› ‹b ∈ t›) _, simp end, cSup_le this F, have B : Sup s ⊔ Sup t ≤ Sup (s ∪ t) := have Sup s ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹s ≠ ∅›; simp; finish, have Sup t ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹t ≠ ∅›; simp; finish, by simp; split; assumption; assumption, le_antisymm A B /--The inf of a union of sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (_ : bdd_below s) (_ : s ≠ ∅) (_ : bdd_below t) (_ : t ≠ ∅) : Inf (s ∪ t) = Inf s ⊓ Inf t := have A : Inf s ⊓ Inf t ≤ Inf (s ∪ t) := have s ∪ t ≠ ∅ := by simp at *; finish, have F : ∀b∈ s∪t, Inf s ⊓ Inf t ≤ b := begin intros, cases H, apply le_trans _ (cInf_le ‹bdd_below s› ‹b ∈ s›), simp, apply le_trans _ (cInf_le ‹bdd_below t› ‹b ∈ t›), simp end, le_cInf this F, have B : Inf (s ∪ t) ≤ Inf s ⊓ Inf t := have Inf (s ∪ t) ≤ Inf s := by apply cInf_le_cInf _ ‹s ≠ ∅›; simp; finish, have Inf (s ∪ t) ≤ Inf t := by apply cInf_le_cInf _ ‹t ≠ ∅›; simp; finish, by simp; split; assumption; assumption, le_antisymm B A /--The supremum of an intersection of sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (_ : s ∩ t ≠ ∅) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := begin apply cSup_le ‹s ∩ t ≠ ∅› _, simp, intros b _ _, split, apply le_cSup ‹bdd_above s› ‹b ∈ s›, apply le_cSup ‹bdd_above t› ‹b ∈ t› end /--The infimum of an intersection of sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (_ : s ∩ t ≠ ∅) : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := begin apply le_cInf ‹s ∩ t ≠ ∅› _, simp, intros b _ _, split, apply cInf_le ‹bdd_below s› ‹b ∈ s›, apply cInf_le ‹bdd_below t› ‹b ∈ t› end /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (_ : bdd_above s) (_ : s ≠ ∅) : Sup (insert a s) = a ⊔ Sup s := calc Sup (insert a s) = Sup ({a} ∪ s) : by rw [insert_eq] ... = Sup {a} ⊔ Sup s : by apply cSup_union _ _ ‹bdd_above s› ‹s ≠ ∅›; simp; simp ... = a ⊔ Sup s : by simp /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (_ : bdd_below s) (_ : s ≠ ∅) : Inf (insert a s) = a ⊓ Inf s := calc Inf (insert a s) = Inf ({a} ∪ s) : by rw [insert_eq] ... = Inf {a} ⊓ Inf s : by apply cInf_union _ _ ‹bdd_below s› ‹s ≠ ∅›; simp; simp ... = a ⊓ Inf s : by simp end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /--When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_lt_cSup (_ : s ≠ ∅) (_ : b < Sup s) : ∃a∈s, b < a := begin apply classical.by_contradiction, assume : ¬ (∃a∈s, b < a), have : Sup s ≤ b := by apply cSup_le ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›) end /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (_ : s ≠ ∅) (_ : Inf s < b) : ∃a∈s, a < b := begin apply classical.by_contradiction, assume : ¬ (∃a∈s, a < b), have : b ≤ Inf s := by apply le_cInf ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›) end end conditionally_complete_linear_order end lattice /-end of namespace lattice-/
c4fc97e27c745f354acfdd83b35710a5b5913a31
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/char.lean
886537912db32d9a6ea5d494269e07110c5fb014
[ "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,012
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ /-! # More `char` instances > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides a `linear_order` instance on `char`. `char` is the type of Unicode scalar values. -/ instance : linear_order char := { le_refl := λ a, @le_refl ℕ _ _, le_trans := λ a b c, @le_trans ℕ _ _ _ _, le_antisymm := λ a b h₁ h₂, char.eq_of_veq $ le_antisymm h₁ h₂, le_total := λ a b, @le_total ℕ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ℕ _ _ _, decidable_le := char.decidable_le, decidable_eq := char.decidable_eq, decidable_lt := char.decidable_lt, ..char.has_le, ..char.has_lt } lemma char.of_nat_to_nat {c : char} (h : is_valid_char c.to_nat) : char.of_nat c.to_nat = c := begin rw [char.of_nat, dif_pos h], cases c, simp [char.to_nat] end
1f9fae6dc0112867b41fce8c32cdf3d26d95f2c8
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Compiler/IR/PushProj.lean
178d8f24c36ed4f00cb24473907ccf9b88bfd0df
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
2,063
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.IR.Basic import Lean.Compiler.IR.FreeVars import Lean.Compiler.IR.NormIds namespace Lean.IR partial def pushProjs (bs : Array FnBody) (alts : Array Alt) (altsF : Array IndexSet) (ctx : Array FnBody) (ctxF : IndexSet) : Array FnBody × Array Alt := if bs.isEmpty then (ctx.reverse, alts) else let b := bs.back let bs := bs.pop let done (_ : Unit) := (bs.push b ++ ctx.reverse, alts) let skip (_ : Unit) := pushProjs bs alts altsF (ctx.push b) (b.collectFreeIndices ctxF) let push (x : VarId) := if !ctxF.contains x.idx then let alts := alts.mapIdx fun i alt => alt.modifyBody fun b' => if (altsF.get! i).contains x.idx then b.setBody b' else b' let altsF := altsF.map fun s => if s.contains x.idx then b.collectFreeIndices s else s pushProjs bs alts altsF ctx ctxF else skip () match b with | FnBody.vdecl x _ v _ => match v with | Expr.proj _ _ => push x | Expr.uproj _ _ => push x | Expr.sproj _ _ _ => push x | Expr.isShared _ => skip () | Expr.isTaggedPtr _ => skip () | _ => done () | _ => done () partial def FnBody.pushProj (b : FnBody) : FnBody := let (bs, term) := b.flatten let bs := modifyJPs bs pushProj match term with | .case tid x xType alts => let altsF := alts.map fun alt => alt.body.freeIndices let (bs, alts) := pushProjs bs alts altsF #[] (mkIndexSet x.idx) let alts := alts.map fun alt => alt.modifyBody pushProj let term := FnBody.case tid x xType alts reshape bs term | _ => reshape bs term /-- Push projections inside `case` branches. -/ def Decl.pushProj (d : Decl) : Decl := match d with | .fdecl (body := b) .. => d.updateBody! b.pushProj |>.normalizeIds | other => other end Lean.IR