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
68eb4fc1d439f6ee01e71f38e2109993439e249c
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Server/Snapshots.lean
f4e2b76bf697e9b6fd3c1c4a7fd0541255516730
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
7,292
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Init.System.IO import Lean.Elab.Import import Lean.Elab.Command import Lean.Widget.InteractiveDiagnostic /-! One can think of this module as being a partial reimplementation of Lean.Elab.Frontend which also stores a snapshot of the world after each command. Importantly, we allow (re)starting compilation from any snapshot/position in the file for interactive editing purposes. -/ namespace Lean.Server.Snapshots open Elab /- For `Inhabited Snapshot` -/ builtin_initialize dummyTacticCache : IO.Ref Tactic.Cache ← IO.mkRef {} /-- What Lean knows about the world after the header and each command. -/ structure Snapshot where /-- Where the command which produced this snapshot begins. Note that neighbouring snapshots are *not* necessarily attached beginning-to-end, since inputs outside the grammar advance the parser but do not produce snapshots. -/ beginPos : String.Pos stx : Syntax mpState : Parser.ModuleParserState cmdState : Command.State /-- We cache interactive diagnostics in order not to invoke the pretty-printer again on messages from previous snapshots when publishing diagnostics for every new snapshot (this is quadratic), as well as not to invoke it once again when handling `$/lean/interactiveDiagnostics`. -/ interactiveDiags : PersistentArray Widget.InteractiveDiagnostic tacticCache : IO.Ref Tactic.Cache namespace Snapshot def endPos (s : Snapshot) : String.Pos := s.mpState.pos def env (s : Snapshot) : Environment := s.cmdState.env def msgLog (s : Snapshot) : MessageLog := s.cmdState.messages def diagnostics (s : Snapshot) : PersistentArray Lsp.Diagnostic := s.interactiveDiags.map fun d => d.toDiagnostic def infoTree (s : Snapshot) : InfoTree := -- the parser returns exactly one command per snapshot, and the elaborator creates exactly one node per command assert! s.cmdState.infoState.trees.size == 1 s.cmdState.infoState.trees[0]! def isAtEnd (s : Snapshot) : Bool := Parser.isEOI s.stx || Parser.isTerminalCommand s.stx open Command in /-- Use the command state in the given snapshot to run a `CommandElabM`.-/ def runCommandElabM (snap : Snapshot) (meta : DocumentMeta) (c : CommandElabM α) : EIO Exception α := do let ctx : Command.Context := { cmdPos := snap.beginPos, fileName := meta.uri, fileMap := meta.text, tacticCache? := snap.tacticCache, } c.run ctx |>.run' snap.cmdState /-- Run a `CoreM` computation using the data in the given snapshot.-/ def runCoreM (snap : Snapshot) (meta : DocumentMeta) (c : CoreM α) : EIO Exception α := snap.runCommandElabM meta <| Command.liftCoreM c /-- Run a `TermElabM` computation using the data in the given snapshot.-/ def runTermElabM (snap : Snapshot) (meta : DocumentMeta) (c : TermElabM α) : EIO Exception α := snap.runCommandElabM meta <| Command.liftTermElabM c end Snapshot /-- Parses the next command occurring after the given snapshot without elaborating it. -/ def parseNextCmd (inputCtx : Parser.InputContext) (snap : Snapshot) : IO Syntax := do let cmdState := snap.cmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmdStx, _, _) := Parser.parseCommand inputCtx pmctx snap.mpState snap.msgLog return cmdStx register_builtin_option server.stderrAsMessages : Bool := { defValue := true group := "server" descr := "(server) capture output to the Lean stderr channel (such as from `dbg_trace`) during elaboration of a command as a diagnostic message" } /-- Compiles the next command occurring after the given snapshot. If there is no next command (file ended), `Snapshot.isAtEnd` will hold of the return value. -/ -- NOTE: This code is really very similar to Elab.Frontend. But generalizing it -- over "store snapshots"/"don't store snapshots" would likely result in confusing -- isServer? conditionals and not be worth it due to how short it is. def compileNextCmd (inputCtx : Parser.InputContext) (snap : Snapshot) (hasWidgets : Bool) : IO Snapshot := do let cmdState := snap.cmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmdStx, cmdParserState, msgLog) := Parser.parseCommand inputCtx pmctx snap.mpState snap.msgLog let cmdPos := cmdStx.getPos?.get! if Parser.isEOI cmdStx then let endSnap : Snapshot := { beginPos := cmdPos stx := cmdStx mpState := cmdParserState cmdState := snap.cmdState interactiveDiags := ← withNewInteractiveDiags msgLog tacticCache := snap.tacticCache } return endSnap else let cmdStateRef ← IO.mkRef { snap.cmdState with messages := msgLog } /- The same snapshot may be executed by different tasks. So, to make sure `elabCommandTopLevel` has exclusive access to the cache, we create a fresh reference here. Before this change, the following `snap.tacticCache.modify` would reset the tactic post cache while another snapshot was still using it. -/ let tacticCacheNew ← IO.mkRef (← snap.tacticCache.get) let cmdCtx : Elab.Command.Context := { cmdPos := snap.endPos fileName := inputCtx.fileName fileMap := inputCtx.fileMap tacticCache? := some tacticCacheNew } let (output, _) ← IO.FS.withIsolatedStreams (isolateStderr := server.stderrAsMessages.get scope.opts) <| liftM (m := BaseIO) do Elab.Command.catchExceptions (getResetInfoTrees *> Elab.Command.elabCommandTopLevel cmdStx) cmdCtx cmdStateRef let postNew := (← tacticCacheNew.get).post snap.tacticCache.modify fun _ => { pre := postNew, post := {} } let mut postCmdState ← cmdStateRef.get if !output.isEmpty then postCmdState := { postCmdState with messages := postCmdState.messages.add { fileName := inputCtx.fileName severity := MessageSeverity.information pos := inputCtx.fileMap.toPosition snap.endPos data := output } } let postCmdSnap : Snapshot := { beginPos := cmdPos stx := cmdStx mpState := cmdParserState cmdState := postCmdState interactiveDiags := ← withNewInteractiveDiags postCmdState.messages tacticCache := (← IO.mkRef {}) } return postCmdSnap where /-- Compute the current interactive diagnostics log by finding a "diff" relative to the parent snapshot. We need to do this because unlike the `MessageLog` itself, interactive diags are not part of the command state. -/ withNewInteractiveDiags (msgLog : MessageLog) : IO (PersistentArray Widget.InteractiveDiagnostic) := do let newMsgCount := msgLog.msgs.size - snap.msgLog.msgs.size let mut ret := snap.interactiveDiags for i in List.iota newMsgCount do let newMsg := msgLog.msgs.get! (msgLog.msgs.size - i) ret := ret.push (← Widget.msgToInteractiveDiagnostic inputCtx.fileMap newMsg hasWidgets) return ret end Lean.Server.Snapshots
8f7ceebeb7cc1102451b668eed8c2e2c64909d6d
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/foncteur/test.lean
761eb0c25cc2d76a9983662331367df567700a74
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
314
lean
set_option profiler true open polynomial example (R : Type) [comm_ring R] (x : R) : (1 + x^2 + x^4 + x^6) * (1 + x) = 1+x+x^2+x^3+x^4+x^5+x^6+x^7 := by ring -- 5 seconds example (R : Type) [comm_ring R] : (1 + X^2 + X^4 + X^6 : polynomial R) * (1 + X) = 1+X+X^2+X^3+X^4+X^5+X^6+X^7 := by ring -- 18 seconds
f1bc8f71b5ecccc06831a23a412541b30515fb17
450ef90ab419a8d1a41b0acbfcd9c40d706ef262
/data/list/perm.lean
4d483ed1d6195b223cba8216fc30f0e89b206b44
[]
no_license
minchaowu/library_dev
7bb62d254aaeae027dd78095cc4b1f0b0f3271ba
9309df1085d8fb019f5b12d22fafd06bc1be6bf4
refs/heads/master
1,609,344,118,976
1,501,167,567,000
1,501,167,567,000
91,199,828
0
0
null
1,494,705,872,000
1,494,705,872,000
null
UTF-8
Lean
false
false
41,775
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, Jeremy Avigad List permutations. -/ import .basic .comb .set -- TODO(Jeremy): Here is a common idiom: after simplifying, we have a goal 1 + t = nat.succ t -- and need to say rw [add_comm, reflexivity]. Can we get the simplifier to finish this off? namespace list universe variables uu vv variables {α : Type uu} {β : Type vv} inductive perm : list α → list α → Prop | nil : perm [] [] | skip : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ namespace perm infix ~ := perm @[refl] protected theorem refl : ∀ (l : list α), l ~ l | [] := nil | (x::xs) := skip x (refl xs) @[symm] protected theorem symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p nil (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁) attribute [trans] perm.trans theorem eqv (α : Type) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) attribute [instance] protected definition is_setoid (α : Type) : setoid (list α) := setoid.mk (@perm α) (perm.eqv α) theorem mem_of_perm {a : α} {l₁ l₂ : list α} (p : l₁ ~ l₂) : a ∈ l₁ → a ∈ l₂ := perm.rec_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim i (λ ax, by simp [ax]) (λ al₁, or.inr (r₁ al₁))) (λ x y l ayxl, or.elim ayxl (λ ay, by simp [ay]) (λ axl, or.elim axl (λ ax, by simp [ax]) (λ al, or.inr (or.inr al)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem not_mem_of_perm {a : α} {l₁ l₂ : list α} : l₁ ~ l₂ → a ∉ l₁ → a ∉ l₂ := assume p nainl₁ ainl₂, nainl₁ (mem_of_perm p.symm ainl₂) theorem mem_iff_mem_of_perm {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ := iff.intro (mem_of_perm h) (mem_of_perm h.symm) theorem perm_app_left {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : (l₁++t₁) ~ (l₂++t₁) := perm.rec_on p (perm.refl ([] ++ t₁)) (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_app_right {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → (l++t₁) ~ (l++t₂) | [] p := p | (x::xs) p := skip x (perm_app_right xs p) theorem perm_app {l₁ l₂ t₁ t₂ : list α} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁++t₁) ~ (l₂++t₂) := assume p₁ p₂, trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂) --theorem perm_app_cons (a : α) {h₁ h₂ t₁ t₂ : list α} : -- h₁ ~ h₂ → t₁ ~ t₂ → (h₁ ++ (a::t₁)) ~ (h₂ ++ (a::t₂)) := --assume p₁ p₂, perm_app p₁ (skip a p₂) theorem perm_cons_app (a : α) : ∀ (l : list α), (a::l) ~ (l ++ [a]) | [] := perm.refl _ | (x::xs) := trans (swap x a xs) $ skip x (perm_cons_app xs) @[simp] theorem perm_cons_app_simp (a : α) (l : list α) : (l ++ [a]) ~ (a::l) := perm.symm (perm_cons_app a l) @[simp] theorem perm_app_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁) | [] l₂ := by simp | (a::t) l₂ := calc a::(t++l₂) ~ a::(l₂++t) : skip a perm_app_comm ... ~ l₂++t++[a] : perm_cons_app _ _ ... = l₂++(t++[a]) : by rw append.assoc ... ~ l₂++(a::t) : perm_app_right l₂ (perm.symm (perm_cons_app a t)) theorem length_eq_length_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ := perm.rec_on p rfl (λ x l₁ l₂ p r, by simp[r]) (λ x y l, by simp) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem eq_nil_of_perm_nil {l₁ : list α} (p : ([] : list α) ~ l₁) : l₁ = ([] : list α) := eq_nil_of_length_eq_zero (length_eq_length_of_perm p).symm theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ (x::l) := assume p, by have h := eq_nil_of_perm_nil p; contradiction theorem eq_singleton_of_perm {a b : α} (p : [a] ~ [b]) : a = b := have a ∈ [b], from mem_of_perm p (by simp), by simp at this; simp [*] theorem eq_singleton_of_perm_inv {a : α} {l : list α} (p : [a] ~ l) : l = [a] := match l, length_eq_length_of_perm p, p with | [a'], rfl, p := by simp [eq_singleton_of_perm p] end theorem perm_rev : ∀ (l : list α), l ~ (reverse l) | [] := nil | (x::xs) := calc x::xs ~ x::reverse xs : skip x (perm_rev xs) ... ~ reverse xs ++ [x] : perm_cons_app _ _ ... = reverse (x::xs) : by rw [reverse_cons, concat_eq_append] @[simp] theorem perm_rev_simp (l : list α) : (reverse l) ~ l := perm.symm (perm_rev l) theorem perm_middle (a : α) (l₁ l₂ : list α) : (a::l₁)++l₂ ~ l₁++(a::l₂) := have a::l₁++l₂ ~ l₁++[a]++l₂, from perm_app_left l₂ (perm_cons_app a l₁), by simp at this; exact this attribute [simp] theorem perm_middle_simp (a : α) (l₁ l₂ : list α) : l₁++(a::l₂) ~ (a::l₁)++l₂ := perm.symm $ perm_middle a l₁ l₂ theorem perm_cons_app_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) := trans (skip a p) $ perm_middle a l₁ l₂ open decidable theorem perm_erase [decidable_eq α] {a : α} : ∀ {l : list α}, a ∈ l → l ~ a:: l.erase a | [] h := false.elim h | (x::t) h := if ax : x = a then by rw [ax, erase_cons_head] else by rw [erase_cons_tail _ ax]; exact have aint : a ∈ t, from mem_of_ne_of_mem (assume h, ax h.symm) h, trans (skip _ $ perm_erase aint) (swap _ _ _) @[elab_as_eliminator] theorem perm_induction_on {P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l, from assume l, list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ theorem xswap {l₁ l₂ : list α} (x y : α) : l₁ ~ l₂ → x::y::l₁ ~ y::x::l₂ := assume p, calc x::y::l₁ ~ y::x::l₁ : swap y x l₁ ... ~ y::x::l₂ : skip y (skip x p) @[congr] theorem perm_map (f : α → β) {l₁ l₂ : list α} : l₁ ~ l₂ → map f l₁ ~ map f l₂ := assume p, perm_induction_on p nil (λ x l₁ l₂ p r, skip (f x) r) (λ x y l₁ l₂ p r, xswap (f y) (f x) r) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) /- TODO(Jeremy) In the next section, the decidability proof works, but gave the following error: equation compiler failed to generate bytecode for auxiliary declaration 'list.perm.decidable_perm_aux._main' nested exception message: code generation failed, inductive predicate 'eq' is not supported So I will comment it out and give another decidability proof below. -/ /- /- permutation is decidable if α has decidable equality -/ section dec open decidable variable [Ha : decidable_eq α] include Ha def decidable_perm_aux : ∀ (n : nat) (l₁ l₂ : list α), length l₁ = n → length l₂ = n → decidable (l₁ ~ l₂) | 0 l₁ l₂ H₁ H₂ := have l₁n : l₁ = [], from eq_nil_of_length_eq_zero H₁, have l₂n : l₂ = [], from eq_nil_of_length_eq_zero H₂, begin rw [l₁n, l₂n], exact (is_true perm.nil) end | (n+1) (x::t₁) l₂ H₁ H₂ := by_cases (assume xinl₂ : x ∈ l₂, -- TODO(Jeremy): it seems the equation editor abstracts t₂, and loses the definition, so -- I had to expand it manually -- let t₂ : list α := erase x l₂ in have len_t₁ : length t₁ = n, begin simp at H₁, have H₁' : nat.succ (length t₁) = nat.succ n, exact H₁, injection H₁' with e, exact e end, have length (erase x l₂) = nat.pred (length l₂), from length_erase_of_mem xinl₂, have length (erase x l₂) = n, begin rw [this, H₂], reflexivity end, match decidable_perm_aux n t₁ (erase x l₂) len_t₁ this with | is_true p := is_true (calc x::t₁ ~ x::erase x l₂ : skip x p ... ~ l₂ : perm.symm (perm_erase xinl₂)) | is_false np := is_false (λ p : x::t₁ ~ l₂, have erase x (x::t₁) ~ erase x l₂, from erase_perm_erase_of_perm x p, have t₁ ~ erase x l₂, begin rw [erase_cons_head] at this, exact this end, absurd this np) end) (assume nxinl₂ : x ∉ l₂, is_false (λ p : x::t₁ ~ l₂, absurd (mem_of_perm p (mem_cons_self _ _)) nxinl₂)) attribute [instance] definition decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) := λ l₁ l₂, by_cases (assume eql : length l₁ = length l₂, decidable_perm_aux (length l₂) l₁ l₂ eql rfl) (assume neql : length l₁ ≠ length l₂, is_false (λ p : l₁ ~ l₂, absurd (length_eq_length_of_perm p) neql)) end dec -/ section count variable [decα : decidable_eq α] include decα theorem count_eq_count_of_perm {l₁ l₂ : list α} : l₁ ~ l₂ → ∀ a, count a l₁ = count a l₂ := assume : l₁ ~ l₂, perm.rec_on this (λ a, rfl) (λ x l₁ l₂ p h a, begin simp [count_cons', h a] end) (λ x y l a, begin simp [count_cons'] end) (λ l₁ l₂ l₃ p₁ p₂ h₁ h₂ a, eq.trans (h₁ a) (h₂ a)) theorem perm_of_forall_count_eq : ∀ {l₁ l₂ : list α}, (∀ a, count a l₁ = count a l₂) → l₁ ~ l₂ | [] := assume l₂, assume h : ∀ a, count a [] = count a l₂, have ∀ a, a ∉ l₂, from assume a, not_mem_of_count_eq_zero (by simp [(h a).symm]), have l₂ = [], from eq_nil_of_forall_not_mem this, show [] ~ l₂, by rw this | (b :: l) := assume l₂, assume h : ∀ a, count a (b :: l) = count a l₂, have b ∈ l₂, from mem_of_count_pos (begin rw [←(h b)], simp, apply nat.succ_pos end), have l₂ ~ b :: l₂.erase b, from perm_erase this, have ∀ a, count a l = count a (l₂.erase b), from assume a, if h' : a = b then nat.succ_inj (calc count a l + 1 = count a (b :: l) : begin simp [h'], rw add_comm end ... = count a l₂ : by rw h ... = count a (b :: l₂.erase b) : count_eq_count_of_perm (by assumption) a ... = count a (l₂.erase b) + 1 : begin simp [h'], rw add_comm end) else calc count a l = count a (b :: l) : by simp [h'] ... = count a l₂ : by rw h ... = count a (b :: l₂.erase b) : count_eq_count_of_perm (by assumption) a ... = count a (l₂.erase b) : by simp [h'], have l ~ l₂.erase b, from perm_of_forall_count_eq this, calc b :: l ~ b :: l₂.erase b : skip b this ... ~ l₂ : perm.symm (by assumption) theorem perm_iff_forall_count_eq_count (l₁ l₂ : list α) : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ := iff.intro count_eq_count_of_perm perm_of_forall_count_eq -- This next theorem shows that perm is equivalent to a decidable (and efficiently checkable) -- property. theorem perm_iff_forall_mem_count_eq_count (l₁ l₂ : list α) : l₁ ~ l₂ ↔ ∀ a ∈ erase_dup (l₁ ∪ l₂), count a l₁ = count a l₂ := iff.intro (assume h : l₁ ~ l₂, assume a, assume ha, count_eq_count_of_perm h a) (assume h, have ∀ a, count a l₁ = count a l₂, from assume a, if hl₁ : a ∈ l₁ then have a ∈ erase_dup (l₁ ∪ l₂), from mem_erase_dup (mem_union_left hl₁ l₂), h a this else if hl₂ : a ∈ l₂ then have a ∈ erase_dup (l₁ ∪ l₂), from mem_erase_dup (mem_union_right l₁ hl₂), h a this else by simp [hl₁, hl₂], perm_of_forall_count_eq this) instance : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) := assume l₁ l₂, decidable_of_decidable_of_iff (decidable_forall_mem _) (perm_iff_forall_mem_count_eq_count l₁ l₂).symm end count -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr {P : Prop} {a b : α} {l₁ l₂ l₃ : list α} : a::l₁ = l₂++(b::l₃) → (l₂ = [] → a = b → l₁ = l₃ → P) → (∀ t, l₂ = a::t → l₁ = t++(b::l₃) → P) → P := match l₂ with | [] := λ e h₁ h₂, begin simp at e, injection e with e₁ e₂, exact h₁ rfl e₁ e₂ end | h::t := λ e h₁ h₂, begin simp at e, injection e with e₁ e₂, rw e₁ at h₂, exact h₂ t rfl e₂ end end -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr₂ {P : Prop} {a b c : α} {l₁ l₂ l₃ : list α} (e : a::b::l₁ = l₂++(c::l₃)) (H₁ : l₂ = [] → l₃ = b::l₁ → a = c → P) (H₂ : l₂ = [a] → b = c → l₁ = l₃ → P) (H₃ : ∀ t, l₂ = a::b::t → l₁ = t++(c::l₃) → P) : P := discr e (λh₁ h₂ h₃, H₁ h₁ h₃.symm h₂) $ λt h₁ h₂, discr h₂ (λh₃ h₄, match t, h₃, h₁ with ._, rfl, h₁ := H₂ h₁ h₄ end) (λt' h₃ h₄, match t, h₃, h₁ with ._, rfl, h₁ := H₃ t' h₁ h₄ end) /- quasiequal a l l' means that l' is exactly l, with a added once somewhere -/ section qeq inductive qeq (a : α) : list α → list α → Prop | qhead : ∀ l, qeq l (a::l) | qcons : ∀ (b : α) {l l' : list α}, qeq l l' → qeq (b::l) (b::l') open qeq notation l' `≈`:50 a `|` l:50 := qeq a l l' lemma perm_of_qeq {a : α} {l₁ l₂ : list α} : l₁≈a|l₂ → l₁~a::l₂ := assume q, qeq.rec_on q (λ h, perm.refl (a :: h)) (λ b t₁ t₂ q₁ r₁, calc b::t₂ ~ b::a::t₁ : skip b r₁ ... ~ a::b::t₁ : swap a b t₁) theorem qeq_app : ∀ (l₁ : list α) (a : α) (l₂ : list α), l₁ ++ (a :: l₂) ≈ a | l₁ ++ l₂ | ([] : list α) b l₂ := qhead b l₂ | (a::ains) b l₂ := qcons a (qeq_app ains b l₂) theorem mem_head_of_qeq {a : α} : ∀ {l₁ l₂ : list α}, l₁ ≈ a | l₂ → a ∈ l₁ | ._ ._ (qhead .(a) l) := mem_cons_self a l | ._ ._ (@qcons .(α) .(a) b l l' q) := mem_cons_of_mem b (mem_head_of_qeq q) theorem mem_tail_of_qeq {a : α} : ∀ {l₁ l₂ : list α}, l₁ ≈ a | l₂ → ∀ {b}, b ∈ l₂ → b ∈ l₁ | ._ ._ (qhead .(a) l) b bl := mem_cons_of_mem a bl | ._ ._ (@qcons .(α) .(a) c l l' q) b bcl := or.elim (eq_or_mem_of_mem_cons bcl) (assume bc : b = c, begin rw bc, apply mem_cons_self end) (assume bl : b ∈ l, have bl' : b ∈ l', from mem_tail_of_qeq q bl, mem_cons_of_mem c bl') theorem mem_cons_of_qeq {a : α} : ∀ {l₁ l₂ : list α}, l₁≈a|l₂ → ∀ {b}, b ∈ l₁ → b ∈ a::l₂ | ._ ._ (qhead ._ l) b bal := bal | ._ ._ (@qcons ._ ._ c l l' q) b (bcl' : b ∈ c :: l') := show b ∈ a :: c :: l, from or.elim (eq_or_mem_of_mem_cons bcl') (assume bc : b = c, begin rw bc, apply mem_cons_of_mem, apply mem_cons_self end) (assume bl' : b ∈ l', have b ∈ a :: l, from mem_cons_of_qeq q bl', or.elim (eq_or_mem_of_mem_cons this) (assume ba : b = a, begin rw ba, apply mem_cons_self end) (assume bl : b ∈ l, mem_cons_of_mem a (mem_cons_of_mem c bl))) theorem length_eq_of_qeq {a : α} {l₁ l₂ : list α} : l₁ ≈ a | l₂ → length l₁ = nat.succ (length l₂) := begin intro q, induction q with l b l l' q ih, simp[nat.one_add], simp [*] end theorem qeq_of_mem {a : α} {l : list α} : a ∈ l → (∃ l', l ≈ a | l') := list.rec_on l (λ h : a ∈ ([] : list α), absurd h (not_mem_nil a)) (λ b bs r ainbbs, or.elim (eq_or_mem_of_mem_cons ainbbs) (λ aeqb : a = b, have ∃ l, b::bs ≈ b | l, from exists.intro bs (qhead b bs), begin rw aeqb, exact this end) (λ ainbs : a ∈ bs, have ∃ l', bs ≈ a|l', from r ainbs, exists.elim this (assume (l' : list α) (q : bs ≈ a|l'), have b::bs ≈ a | b::l', from qcons b q, exists.intro (b::l') this))) theorem qeq_split {a : α} : ∀ {l l' : list α}, l'≈a|l → ∃ l₁ l₂, l = l₁ ++ l₂ ∧ l' = l₁ ++ (a::l₂) | ._ ._ (qhead ._ l) := ⟨[], l, by simp⟩ | ._ ._ (@qcons ._ ._ c l l' q) := match (qeq_split q) with | ⟨l₁, l₂, h₁, h₂⟩ := ⟨c :: l₁, l₂, by simp [h₁, h₂]⟩ end --theorem subset_of_mem_of_subset_of_qeq {a : α} {l : list α} {u v : list α} : -- a ∉ l → a::l ⊆ v → v≈a|u → l ⊆ u := --λ (nainl : a ∉ l) (s : a::l ⊆ v) (q : v≈a|u) (b : α) (binl : b ∈ l), -- have b ∈ v, from s (or.inr binl), -- have b ∈ a::u, from mem_cons_of_qeq q this, -- or.elim (eq_or_mem_of_mem_cons this) -- (assume : b = a, begin subst b, contradiction end) -- (assume : b ∈ u, this) --end qeq theorem perm_inv_core {l₁ l₂ : list α} (p' : l₁ ~ l₂) : ∀ {a s₁ s₂}, l₁≈a|s₁ → l₂≈a|s₂ → s₁ ~ s₂ := perm_induction_on p' (λ a s₁ s₂ e₁ e₂, match e₁ with end) (λ x t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, match s₁, s₂, qeq_split e₁, qeq_split e₂ with ._, ._, ⟨s₁₁, s₁₂, rfl, C₁⟩, ⟨s₂₁, s₂₂, rfl, C₂⟩ := discr C₁ (λe₁ xa, match s₁₁, x, e₁, xa, C₂ with ._, ._, rfl, rfl, C₂ := discr C₂ (λe₁ _ e₂ e₃, match s₁₂, s₂₁, s₂₂, e₁, e₂, e₃ with | ._, ._, ._, rfl, rfl, rfl := p end) (λt₃ e₁ e₂ e₃, match s₂₁, s₁₂, t₂, e₁, e₂, e₃, p with | ._, ._, ._, rfl, rfl, rfl, p := trans p (perm_middle _ _ _).symm end) end) (λt₃ e₁ e₂, match s₁₁, t₁, e₁, e₂, C₂, p, @r with ._, ._, rfl, rfl, C₂, p, r := discr C₂ (λe₁ xa e₂, match x, s₂₁, s₂₂, xa, e₁, e₂ with | ._, ._, ._, rfl, rfl, rfl := trans (perm_middle _ _ _) p end) (λt₃ e₁ e₂, match s₂₁, t₂, e₁, e₂, @r with | ._, ._, rfl, rfl, r := skip x (r (qeq_app _ _ _) (qeq_app _ _ _)) end) end) end) (λ x y t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, match s₁, s₂, qeq_split e₁, qeq_split e₂ with ._, ._, ⟨s₁₁, s₁₂, rfl, C₁⟩, ⟨s₂₁, s₂₂, rfl, C₂⟩ := discr₂ C₁ (λe₁ e₂ ya, match s₁₁, s₁₂, y, e₁, e₂, ya, C₂ with ._, ._, ._, rfl, rfl, rfl, C₂ := discr₂ C₂ (λe₁ e₂ xa, match s₂₁, s₂₂, x, e₁, e₂, xa with | ._, ._, ._, rfl, rfl, rfl := skip a p end) (λe₁ _ e₂, match s₂₁, s₂₂, e₁, e₂ with | ._, ._, rfl, rfl := skip x p end) (λt₃ e₁ e₂, match s₂₁, t₂, e₁, e₂, p with | ._, ._, rfl, rfl, p := skip x (trans p (perm_middle _ _ _).symm) end) end) (λe₁ xa e₂, match s₁₁, s₁₂, x, e₁, e₂, xa, C₂ with ._, ._, ._, rfl, rfl, rfl, C₂ := discr₂ C₂ (λe₁ e₂ _, match s₂₁, s₂₂, e₁, e₂ with | ._, ._, rfl, rfl := skip y p end) (λe₁ ya e₂, match s₂₁, s₂₂, y, e₁, e₂, ya with | ._, ._, ._, rfl, rfl, rfl := skip a p end) (λt₃ e₁ e₂, match s₂₁, t₂, e₁, e₂, p with | ._, ._, rfl, rfl, p := trans (skip y $ trans p (perm_middle _ _ _).symm) (swap _ _ _) end) end) (λt₃ e₁ e₂, match s₁₁, t₁, e₁, e₂, C₂, p, @r with ._, ._, rfl, rfl, C₂, p, r := discr₂ C₂ (λe₁ e₂ xa, match s₂₁, s₂₂, x, e₁, e₂, xa with | ._, ._, ._, rfl, rfl, rfl := skip y (trans (perm_middle _ _ _) p) end) (λe₁ ya e₂, match s₂₁, s₂₂, y, e₁, e₂, ya with | ._, ._, ._, rfl, rfl, rfl := trans (swap _ _ _) (skip x $ trans (perm_middle _ _ _) p) end) (λt₄ e₁ e₂, match s₂₁, t₂, e₁, e₂, @r with | ._, ._, rfl, rfl, r := trans (swap _ _ _) (skip x $ skip y $ r (qeq_app _ _ _) (qeq_app _ _ _)) end) end) end) (λ t₁ t₂ t₃ p₁ p₂ (r₁ : ∀{a s₁ s₂}, t₁ ≈ a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) (r₂ : ∀{a s₁ s₂}, t₂ ≈ a|s₁ → t₃≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, let ⟨t₂', e₂'⟩ := qeq_of_mem $ mem_of_perm p₁ $ mem_head_of_qeq e₁ in trans (r₁ e₁ e₂') (r₂ e₂' e₂)) end qeq theorem perm_cons_inv {a : α} {l₁ l₂ : list α} (p : a::l₁ ~ a::l₂) : l₁ ~ l₂ := perm_inv_core p (qeq.qhead a l₁) (qeq.qhead a l₂) theorem perm_app_inv_left {l₁ l₂ : list α} : ∀ {l}, l++l₁ ~ l++l₂ → l₁ ~ l₂ | [] p := p | (a::l) p := perm_app_inv_left (perm_cons_inv p) theorem perm_app_inv_right {l₁ l₂ l : list α} (p : l₁++l ~ l₂++l) : l₁ ~ l₂ := perm_app_inv_left $ trans perm_app_comm $ trans p perm_app_comm theorem perm_app_inv {a : α} {l₁ l₂ l₃ l₄ : list α} (p : l₁++(a::l₂) ~ l₃++(a::l₄)) : l₁++l₂ ~ l₃++l₄ := perm_cons_inv $ trans (perm_middle _ _ _) $ trans p $ (perm_middle _ _ _).symm theorem foldl_eq_of_perm {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) : ∀ b, foldl f b l₁ = foldl f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, r (f b x)) (λ x y t₁ t₂ p r b, by simp; rw rcomm; exact r (f (f b x) y)) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b)) theorem foldr_eq_of_perm {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) : ∀ b, foldr f b l₁ = foldr f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, by simp; rw [r b]) (λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b]) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) -- attribute [congr] theorem erase_perm_erase_of_perm [decidable_eq α] (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁.erase a ~ l₂.erase a := if h₁ : a ∈ l₁ then have h₂ : a ∈ l₂, from mem_of_perm p h₁, perm_cons_inv $ trans (perm_erase h₁).symm $ trans p (perm_erase h₂) else have h₂ : a ∉ l₂, from not_mem_of_perm p h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p -- attribute [congr] theorem perm_erase_dup_of_perm [H : decidable_eq α] {l₁ l₂ : list α} : l₁ ~ l₂ → erase_dup l₁ ~ erase_dup l₂ := assume p, perm_induction_on p nil (λ x t₁ t₂ p r, by_cases (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup xint₁)), begin rw [erase_dup_cons_of_mem xint₁, erase_dup_cons_of_mem xint₂], exact r end) (λ nxint₁ : x ∉ t₁, have nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_of_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, begin rw [erase_dup_cons_of_not_mem nxint₂, erase_dup_cons_of_not_mem nxint₁], exact (skip x r) end)) (λ y x t₁ t₂ p r, by_cases (λ xinyt₁ : x ∈ y::t₁, by_cases (λ yint₁ : y ∈ t₁, have yint₂ : y ∈ t₂, from mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup yint₁)), have yinxt₂ : y ∈ x::t₂, from or.inr (yint₂), or.elim (eq_or_mem_of_mem_cons xinyt₁) (λ xeqy : x = y, have xint₂ : x ∈ t₂, begin rw [←xeqy] at yint₂, exact yint₂ end, begin rw [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end) (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup xint₁)), begin rw [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end)) (λ nyint₁ : y ∉ t₁, have nyint₂ : y ∉ t₂, from assume yint₂ : y ∈ t₂, absurd (mem_of_mem_erase_dup (mem_of_perm (perm.symm r) (mem_erase_dup yint₂))) nyint₁, by_cases (λ xeqy : x = y, have nxint₂ : x ∉ t₂, begin rw [←xeqy] at nyint₂, exact nyint₂ end, have yinxt₂ : y ∈ x::t₂, begin rw [xeqy], apply mem_cons_self end, begin rw [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂, xeqy], exact skip y r end) (λ xney : x ≠ y, have x ∈ t₁, from or_resolve_right xinyt₁ xney, have x ∈ t₂, from mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup this)), have y ∉ x::t₂, from assume : y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons this) (λ h, absurd h (ne.symm xney)) (λ h, absurd h nyint₂), begin rw [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_not_mem ‹y ∉ x::t₂›, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_mem ‹x ∈ t₂›], exact skip y r end))) (λ nxinyt₁ : x ∉ y::t₁, have xney : x ≠ y, from ne_of_not_mem_cons nxinyt₁, have nxint₁ : x ∉ t₁, from not_mem_of_not_mem_cons nxinyt₁, have nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_of_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, by_cases (λ yint₁ : y ∈ t₁, have yinxt₂ : y ∈ x::t₂, from or.inr (mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup yint₁))), begin rw [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_not_mem nxint₂], exact skip x r end) (λ nyint₁ : y ∉ t₁, have nyinxt₂ : y ∉ x::t₂, from assume yinxt₂ : y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons yinxt₂) (λ h, absurd h (ne.symm xney)) (λ h, absurd (mem_of_mem_erase_dup (mem_of_perm (r.symm) (mem_erase_dup h))) nyint₁), begin rw [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_not_mem nyinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂], exact xswap x y r end))) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂, trans r₁ r₂) section perm_union variable [decidable_eq α] theorem perm_union_left {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : (l₁ ∪ t₁) ~ (l₂ ∪ t₁) := begin induction t₁ with a t ih generalizing l₁ l₂, { exact h }, exact if ha₁ : a ∈ l₁ then have ha₂ : a ∈ l₂, from mem_of_perm h ha₁, begin simp [ha₁, ha₂], apply ih h end else have ha₂ : a ∉ l₂, from assume otherwise, ha₁ (mem_of_perm h.symm otherwise), begin simp [ha₁, ha₂], apply ih, apply perm_app_left, exact h end end lemma perm_insert_insert (x y : α) (l : list α) : insert x (insert y l) ~ insert y (insert x l) := if yl : y ∈ l then if xl : x ∈ l then by simp [xl, yl] else by simp [xl, yl] else if xl : x ∈ l then by simp [xl, yl] else if xy : x = y then by simp [xy, xl, yl] else have h₁ : x ∉ l ++ [y], begin intro h, simp at h, cases h, repeat { contradiction } end, have h₂ : y ∉ l ++ [x], begin intro h, simp at h, cases h with h₃, exact xy h₃.symm, contradiction end, begin simp [xl, yl, h₁, h₂], apply perm_app_right, apply perm.swap end theorem perm_union_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : (l ∪ t₁) ~ (l ∪ t₂) := begin induction h using list.perm.rec_on generalizing l, { refl }, { apply ih_1 }, { simp, apply perm_union_left, apply perm_insert_insert }, { exact perm.trans (ih_1 l) (ih_2 l) } end -- attribute [congr] theorem perm_union {l₁ l₂ t₁ t₂ : list α} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁ ∪ t₁) ~ (l₂ ∪ t₂) := assume p₁ p₂, trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂) end perm_union section perm_insert variable [H : decidable_eq α] include H -- attribute [congr] theorem perm_insert (a : α) {l₁ l₂ : list α} : l₁ ~ l₂ → (insert a l₁) ~ (insert a l₂) := assume p, if al₁ : a ∈ l₁ then have al₂ : a ∈ l₂, from mem_of_perm p al₁, begin simp [al₁, al₂], exact p end else have al₂ : a ∉ l₂, from assume otherwise, al₁ (mem_of_perm p.symm otherwise), begin simp [al₁, al₂], exact perm_app_left _ p end theorem perm_insert_cons_of_not_mem {a : α} {l : list α} : a ∉ l → perm (list.insert a l) (a :: l) := assume h, have list.insert a l = concat l a, from if_neg h, by rw this; apply perm.symm; rw concat_eq_append; apply perm_cons_app end perm_insert section perm_inter variable [decidable_eq α] theorem perm_inter_left {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → (l₁ ∩ t₁) ~ (l₂ ∩ t₁) := assume p, perm.rec_on p (perm.refl _) (λ x l₁ l₂ p₁ r₁, by_cases (λ xint₁ : x ∈ t₁, begin rw [inter_cons_of_mem _ xint₁, inter_cons_of_mem _ xint₁], exact (skip x r₁) end) (λ nxint₁ : x ∉ t₁, begin rw [inter_cons_of_not_mem _ nxint₁, inter_cons_of_not_mem _ nxint₁], exact r₁ end)) (λ x y l, by_cases (λ yint : y ∈ t₁, by_cases (λ xint : x ∈ t₁, begin rw [inter_cons_of_mem _ xint, inter_cons_of_mem _ yint, inter_cons_of_mem _ yint, inter_cons_of_mem _ xint], apply swap end) (λ nxint : x ∉ t₁, begin rw [inter_cons_of_mem _ yint, inter_cons_of_not_mem _ nxint, inter_cons_of_not_mem _ nxint, inter_cons_of_mem _ yint] end)) (λ nyint : y ∉ t₁, by_cases (λ xint : x ∈ t₁, by rw [inter_cons_of_mem _ xint, inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nyint, inter_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rw [inter_cons_of_not_mem _ nxint, inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nxint]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_inter_right (l : list α) {t₁ t₂ : list α} : t₁ ~ t₂ → (l ∩ t₁) ~ (l ∩ t₂) := list.rec_on l (λ p, by simp [inter_nil]) (λ x xs r p, by_cases (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_of_perm p xint₁, begin rw [inter_cons_of_mem _ xint₁, inter_cons_of_mem _ xint₂], exact (skip _ (r p)) end) (λ nxint₁ : x ∉ t₁, have nxint₂ : x ∉ t₂, from not_mem_of_perm p nxint₁, begin rw [inter_cons_of_not_mem _ nxint₁, inter_cons_of_not_mem _ nxint₂], exact (r p) end)) -- attribute [congr] theorem perm_inter {l₁ l₂ t₁ t₂ : list α} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁ ∩ t₁) ~ (l₂ ∩ t₂) := assume p₁ p₂, trans (perm_inter_left t₁ p₁) (perm_inter_right l₂ p₂) end perm_inter /- extensionality -/ section ext theorem perm_ext : ∀ {l₁ l₂ : list α}, nodup l₁ → nodup l₂ → (∀a, a ∈ l₁ ↔ a ∈ l₂) → l₁ ~ l₂ | [] [] d₁ d₂ e := perm.nil | [] (a₂::t₂) d₁ d₂ e := absurd (iff.mpr (e a₂) (mem_cons_self _ _)) (not_mem_nil a₂) | (a₁::t₁) [] d₁ d₂ e := absurd (iff.mp (e a₁) (mem_cons_self _ _)) (not_mem_nil a₁) | (a₁::t₁) (a₂::t₂) d₁ d₂ e := have a₁ ∈ a₂::t₂, from iff.mp (e a₁) (mem_cons_self _ _), have ∃ s₁ s₂, a₂::t₂ = s₁++(a₁::s₂), from mem_split this, -- obtain (s₁ s₂ : list α) (t₂_eq : a₂::t₂ = s₁++(a₁::s₂)), from this, match this with | ⟨ s₁, s₂, (t₂_eq : a₂::t₂ = s₁++(a₁::s₂)) ⟩ := have dt₂' : nodup (a₁::(s₁++s₂)), from nodup_head (begin rw [t₂_eq] at d₂, exact d₂ end), have eqv : ∀a, a ∈ t₁ ↔ a ∈ s₁++s₂, from assume a, iff.intro (assume : a ∈ t₁, have a ∈ a₂::t₂, from iff.mp (e a) (mem_cons_of_mem _ this), have a ∈ s₁++(a₁::s₂), begin rw [t₂_eq] at this, exact this end, or.elim (mem_or_mem_of_mem_append this) (assume : a ∈ s₁, mem_append_left s₂ this) (assume : a ∈ a₁::s₂, or.elim (eq_or_mem_of_mem_cons this) (assume : a = a₁, have a₁ ∉ t₁, from not_mem_of_nodup_cons d₁, begin subst a, contradiction end) (assume : a ∈ s₂, mem_append_right s₁ this))) (assume : a ∈ s₁ ++ s₂, or.elim (mem_or_mem_of_mem_append this) (assume : a ∈ s₁, have a ∈ a₂::t₂, from begin rw [t₂_eq], exact (mem_append_left _ this) end, have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (assume : a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', have a₁ ∉ s₁, from not_mem_of_not_mem_append_left this, begin subst a, contradiction end) (assume : a ∈ t₁, this)) (assume : a ∈ s₂, have a ∈ a₂::t₂, from begin rw [t₂_eq], exact (mem_append_right _ (mem_cons_of_mem _ this)) end, have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (assume : a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', have a₁ ∉ s₂, from not_mem_of_not_mem_append_right this, begin subst a, contradiction end) (assume : a ∈ t₁, this))), have ds₁s₂ : nodup (s₁++s₂), from nodup_of_nodup_cons dt₂', have nodup t₁, from nodup_of_nodup_cons d₁, calc a₁::t₁ ~ a₁::(s₁++s₂) : skip a₁ (perm_ext this ds₁s₂ eqv) ... ~ s₁++(a₁::s₂) : perm_middle _ _ _ ... = a₂::t₂ : by rw t₂_eq end end ext theorem nodup_of_perm_of_nodup {l₁ l₂ : list α} : l₁ ~ l₂ → nodup l₁ → nodup l₂ := assume h, perm.rec_on h (λ h, h) (λ a l₁ l₂ p ih nd, have nodup l₁, from nodup_of_nodup_cons nd, have nodup l₂, from ih this, have a ∉ l₁, from not_mem_of_nodup_cons nd, have a ∉ l₂, from assume : a ∈ l₂, absurd (mem_of_perm (perm.symm p) this) ‹a ∉ l₁›, nodup_cons ‹a ∉ l₂› ‹nodup l₂›) (λ x y l₁ nd, have nodup (x::l₁), from nodup_of_nodup_cons nd, have nodup l₁, from nodup_of_nodup_cons this, have x ∉ l₁, from not_mem_of_nodup_cons ‹nodup (x::l₁)›, have y ∉ x::l₁, from not_mem_of_nodup_cons nd, have x ≠ y, from assume : x = y, begin subst x, apply absurd (mem_cons_self _ _), apply ‹y ∉ y::l₁› end, -- this line used to be "exact absurd (mem_cons_self _ _) ‹y ∉ y::l₁›, but it's now a syntax error have y ∉ l₁, from not_mem_of_not_mem_cons ‹y ∉ x::l₁›, have x ∉ y::l₁, from not_mem_cons_of_ne_of_not_mem ‹x ≠ y› ‹x ∉ l₁›, have nodup (y::l₁), from nodup_cons ‹y ∉ l₁› ‹nodup l₁›, show nodup (x::y::l₁), from nodup_cons ‹x ∉ y::l₁› ‹nodup (y::l₁)›) (λ l₁ l₂ l₃ p₁ p₂ ih₁ ih₂ nd, ih₂ (ih₁ nd)) /- product -/ section product theorem perm_product_left {l₁ l₂ : list α} (t₁ : list β) : l₁ ~ l₂ → (product l₁ t₁) ~ (product l₂ t₁) := assume p : l₁ ~ l₂, perm.rec_on p (perm.refl _) (λ x l₁ l₂ p r, perm_app (perm.refl (map _ t₁)) r) (λ x y l, let m₁ := map (λ b, (x, b)) t₁ in let m₂ := map (λ b, (y, b)) t₁ in let c := product l t₁ in calc m₂ ++ (m₁ ++ c) = (m₂ ++ m₁) ++ c : by rw append.assoc ... ~ (m₁ ++ m₂) ++ c : perm_app perm_app_comm (perm.refl _) ... = m₁ ++ (m₂ ++ c) : by rw append.assoc) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_product_right (l : list α) {t₁ t₂ : list β} : t₁ ~ t₂ → (product l t₁) ~ (product l t₂) := list.rec_on l (λ p, by simp [nil_product]) (λ (a : α) (t : list α) (r : t₁ ~ t₂ → product t t₁ ~ product t t₂) (p : t₁ ~ t₂), perm_app (perm_map (λ b : β, (a, b)) p) (r p)) attribute [congr] theorem perm_product {l₁ l₂ : list α} {t₁ t₂ : list β} : l₁ ~ l₂ → t₁ ~ t₂ → (product l₁ t₁) ~ (product l₂ t₂) := assume p₁ p₂, trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂) end product /- filter -/ -- attribute [congr] theorem perm_filter {l₁ l₂ : list α} {p : α → Prop} [decidable_pred p] : l₁ ~ l₂ → (filter p l₁) ~ (filter p l₂) := assume u, perm.rec_on u perm.nil (assume x l₁' l₂', assume u' : l₁' ~ l₂', assume u'' : filter p l₁' ~ filter p l₂', decidable.by_cases (assume : p x, begin rw [filter_cons_of_pos _ this, filter_cons_of_pos _ this], apply perm.skip, apply u'' end) (assume : ¬ p x, begin rw [filter_cons_of_neg _ this, filter_cons_of_neg _ this], apply u'' end)) (assume x y l, decidable.by_cases (assume H1 : p x, decidable.by_cases (assume H2 : p y, begin rw [filter_cons_of_pos _ H1, filter_cons_of_pos _ H2, filter_cons_of_pos _ H2, filter_cons_of_pos _ H1], apply perm.swap end) (assume H2 : ¬ p y, by rw [filter_cons_of_pos _ H1, filter_cons_of_neg _ H2, filter_cons_of_neg _ H2, filter_cons_of_pos _ H1])) (assume H1 : ¬ p x, decidable.by_cases (assume H2 : p y, by rw [filter_cons_of_neg _ H1, filter_cons_of_pos _ H2, filter_cons_of_pos _ H2, filter_cons_of_neg _ H1]) (assume H2 : ¬ p y, by rw [filter_cons_of_neg _ H1, filter_cons_of_neg _ H2, filter_cons_of_neg _ H2, filter_cons_of_neg _ H1]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) /- permutation is decidable if α has decidable equality -/ section dec open decidable variable [Ha : decidable_eq α] include Ha def decidable_perm_aux : ∀ (n : nat) (l₁ l₂ : list α), length l₁ = n → length l₂ = n → decidable (l₁ ~ l₂) | 0 l₁ l₂ H₁ H₂ := have l₁n : l₁ = [], from eq_nil_of_length_eq_zero H₁, have l₂n : l₂ = [], from eq_nil_of_length_eq_zero H₂, begin rw [l₁n, l₂n], exact (is_true perm.nil) end | (n+1) (x::t₁) l₂ H₁ H₂ := by_cases (assume xinl₂ : x ∈ l₂, -- TODO(Jeremy): it seems the equation editor abstracts t₂, and loses the definition, so -- I had to expand it manually -- let t₂ : list α := erase x l₂ in have len_t₁ : length t₁ = n, begin simp at H₁, have H₁' : nat.succ (length t₁) = nat.succ n, repeat {rw ←nat.add_one_eq_succ}, simp, exact H₁, injection H₁' end, have length (l₂.erase x) = nat.pred (length l₂), from length_erase_of_mem xinl₂, have length (l₂.erase x) = n, begin rw [this, H₂], reflexivity end, match decidable_perm_aux n t₁ (l₂.erase x) len_t₁ this with | is_true p := is_true (calc x::t₁ ~ x::l₂.erase x : skip x p ... ~ l₂ : perm.symm (perm_erase xinl₂)) | is_false np := is_false (λ p : x::t₁ ~ l₂, have (x::t₁).erase x ~ l₂.erase x, from erase_perm_erase_of_perm x p, have t₁ ~ l₂.erase x, begin rw [erase_cons_head] at this, exact this end, absurd this np) end) (assume nxinl₂ : x ∉ l₂, is_false (λ p : x::t₁ ~ l₂, absurd (mem_of_perm p (mem_cons_self _ _)) nxinl₂)) instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) := λ l₁ l₂, by_cases (assume eql : length l₁ = length l₂, decidable_perm_aux (length l₂) l₁ l₂ eql rfl) (assume neql : length l₁ ≠ length l₂, is_false (λ p : l₁ ~ l₂, absurd (length_eq_length_of_perm p) neql)) end dec end perm end list
ee2b6380ed267aae8053a3f900564a21a26e5de5
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Parser/Tactic.lean
a68648cdfe157f183030e5c6461244087f392468
[ "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
3,065
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.Term namespace Lean namespace Parser namespace Tactic builtin_initialize register_parser_alias tacticSeq /-- This is a fallback tactic parser for any identifier which exists only to improve syntax error messages. ``` example : True := by foo -- unknown tactic ``` -/ @[builtinTacticParser] def «unknown» := leading_parser withPosition (ident >> errorAtSavedPos "unknown tactic" true) @[builtinTacticParser] def nestedTactic := tacticSeqBracketed def matchRhs := Term.hole <|> Term.syntheticHole <|> tacticSeq def matchAlts := Term.matchAlts (rhsParser := matchRhs) /-- `match` performs case analysis on one or more expressions. See [Induction and Recursion][tpil4]. The syntax for the `match` tactic is the same as term-mode `match`, except that the match arms are tactics instead of expressions. ``` example (n : Nat) : n = n := by match n with | 0 => rfl | i+1 => simp ``` [tpil4]: https://leanprover.github.io/theorem_proving_in_lean4/induction_and_recursion.html -/ @[builtinTacticParser] def «match» := leading_parser:leadPrec "match " >> optional Term.generalizingParam >> optional Term.motive >> sepBy1 Term.matchDiscr ", " >> " with " >> ppDedent matchAlts /-- The tactic ``` intro | pat1 => tac1 | pat2 => tac2 ``` is the same as: ``` intro x match x with | pat1 => tac1 | pat2 => tac2 ``` That is, `intro` can be followed by match arms and it introduces the values while doing a pattern match. This is equivalent to `fun` with match arms in term mode. -/ @[builtinTacticParser] def introMatch := leading_parser nonReservedSymbol "intro " >> matchAlts /-- `decide` will attempt to prove a goal of type `p` by synthesizing an instance of `Decidable p` and then evaluating it to `isTrue ..`. Because this uses kernel computation to evaluate the term, it may not work in the presence of definitions by well founded recursion, since this requires reducing proofs. ``` example : 2 + 2 ≠ 5 := by decide ``` -/ @[builtinTacticParser] def decide := leading_parser nonReservedSymbol "decide" /-- `native_decide` will attempt to prove a goal of type `p` by synthesizing an instance of `Decidable p` and then evaluating it to `isTrue ..`. Unlike `decide`, this uses `#eval` to evaluate the decidability instance. This should be used with care because it adds the entire lean compiler to the trusted part, and the axiom `ofReduceBool` will show up in `#print axioms` for theorems using this method or anything that transitively depends on them. Nevertheless, because it is compiled, this can be significantly more efficient than using `decide`, and for very large computations this is one way to run external programs and trust the result. ``` example : (List.range 1000).length = 1000 := by native_decide ``` -/ @[builtinTacticParser] def nativeDecide := leading_parser nonReservedSymbol "native_decide" end Tactic end Parser end Lean
bcf888e2b9cc78ca8888a8b7e3588c4c333e1eca
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/sheaves/stalks.lean
ea3a7426b187a817be053f932d38f11242030a97
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
26,785
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import topology.category.Top.open_nhds import topology.sheaves.presheaf import topology.sheaves.sheaf_condition.unique_gluing import category_theory.adjunction.evaluation import category_theory.limits.types import category_theory.limits.preserves.filtered import category_theory.limits.final import tactic.elementwise import algebra.category.Ring.colimits import category_theory.sites.pushforward /-! # Stalks > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F` at the point `x : X` is defined as the colimit of the composition of the inclusion of categories `(nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ` and the functor `F : (opens X)ᵒᵖ ⥤ C`. For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the canonical morphism into this colimit. Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`, sending presheaves on `X` to objects of `C`. Furthermore, for a map `f : X ⟶ Y` between topological spaces, we define `stalk_pushforward` as the induced map on the stalks `(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`. Some lemmas about stalks and germs only hold for certain classes of concrete categories. A basic property of forgetful functors of categories of algebraic structures (like `Mon`, `CommRing`,...) is that they preserve filtered colimits. Since stalks are filtered colimits, this ensures that the stalks of presheaves valued in these categories behave exactly as for `Type`-valued presheaves. For example, in `germ_exist` we prove that in such a category, every element of the stalk is the germ of a section. Furthermore, if we require the forgetful functor to reflect isomorphisms and preserve limits (as is the case for most algebraic structures), we have access to the unique gluing API and can prove further properties. Most notably, in `is_iso_iff_stalk_functor_map_iso`, we prove that in such a category, a morphism of sheaves is an isomorphism if and only if all of its stalk maps are isomorphisms. See also the definition of "algebraic structures" in the stacks project: https://stacks.math.columbia.edu/tag/007L -/ noncomputable theory universes v u v' u' open category_theory open Top open category_theory.limits open topological_space open opposite variables {C : Type u} [category.{v} C] variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl /-- The germ of a section of a presheaf over an open at a point of that open. -/ def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x := colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩) @[simp, elementwise] lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) : F.map i.op ≫ germ F x = germ F (i x : V) := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op /-- A morphism from the stalk of `F` at `x` to some object `Y` is completely determined by its composition with the `germ` morphisms. -/ lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y} (ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ := colimit.hom_ext $ λ U, by { induction U using opposite.rec, cases U with U hxU, exact ih U hxU } @[simp, reassoc, elementwise] lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U) (f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x := colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩) variables (C) /-- For a presheaf `F` on a space `X`, a continuous map `f : X ⟶ Y` induces a morphisms between the stalk of `f _ * F` at `f x` and the stalk of `F` at `x`. -/ def stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) (x : X) : (f _* F).stalk (f x) ⟶ F.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) F), end @[simp, elementwise, reassoc] lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y) (x : (opens.map f).obj U) : (f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x := begin rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app], erw [category_theory.functor.map_id, category.id_comp], refl, end -- Here are two other potential solutions, suggested by @fpvandoorn at -- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240> -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], ext1, tactic.op_induction', rcases j with ⟨⟨_, _⟩, _⟩, rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app, pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl], dsimp, -- FIXME A simp lemma which unfortunately doesn't fire: erw [category_theory.functor.map_id], end -- This proof is sadly not at all robust: -- having to use `erw` at all is a bad sign. @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor], ext U, induction U using opposite.rec, rcases U with ⟨⟨_, _⟩, _⟩, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, whisker_right_app, category.assoc], dsimp, -- FIXME: Some of these are simp lemmas, but don't fire successfully: erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp, colimit.ι_pre, colimit.ι_pre], refl, end lemma stalk_pushforward_iso_of_open_embedding {f : X ⟶ Y} (hf : open_embedding f) (F : X.presheaf C) (x : X) : is_iso (F.stalk_pushforward _ f x) := begin haveI := functor.initial_of_adjunction (hf.is_open_map.adjunction_nhds x), convert is_iso.of_iso ((functor.final.colimit_iso (hf.is_open_map.functor_nhds x).op ((open_nhds.inclusion (f x)).op ⋙ f _* F) : _).symm ≪≫ colim.map_iso _), swap, { fapply nat_iso.of_components, { intro U, refine F.map_iso (eq_to_iso _), dsimp only [functor.op], exact congr_arg op (opens.ext $ set.preimage_image_eq (unop U).1.1 hf.inj) }, { intros U V i, erw [← F.map_comp, ← F.map_comp], congr } }, { ext U, rw ← iso.comp_inv_eq, erw colimit.ι_map_assoc, rw [colimit.ι_pre, category.assoc], erw [colimit.ι_map_assoc, colimit.ι_pre, ← F.map_comp_assoc], apply colimit.w ((open_nhds.inclusion (f x)).op ⋙ f _* F) _, dsimp only [functor.op], refine ((hom_of_le _).op : op (unop U) ⟶ _), exact set.image_preimage_subset _ _ }, end end stalk_pushforward section stalk_pullback /-- The morphism `ℱ_{f x} ⟶ (f⁻¹ℱ)ₓ` that factors through `(f_*f⁻¹ℱ)_{f x}`. -/ def stalk_pullback_hom (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : F.stalk (f x) ⟶ (pullback_obj f F).stalk x := (stalk_functor _ (f x)).map ((pushforward_pullback_adjunction C f).unit.app F) ≫ stalk_pushforward _ _ _ x /-- The morphism `(f⁻¹ℱ)(U) ⟶ ℱ_{f(x)}` for some `U ∋ x`. -/ def germ_to_pullback_stalk (f : X ⟶ Y) (F : Y.presheaf C) (U : opens X) (x : U) : (pullback_obj f F).obj (op U) ⟶ F.stalk (f x) := colimit.desc (Lan.diagram (opens.map f).op F (op U)) { X := F.stalk (f x), ι := { app := λ V, F.germ ⟨f x, V.hom.unop.le x.2⟩, naturality' := λ _ _ i, by { erw category.comp_id, exact F.germ_res i.left.unop _ } } } /-- The morphism `(f⁻¹ℱ)ₓ ⟶ ℱ_{f(x)}`. -/ def stalk_pullback_inv (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : (pullback_obj f F).stalk x ⟶ F.stalk (f x) := colimit.desc ((open_nhds.inclusion x).op ⋙ presheaf.pullback_obj f F) { X := F.stalk (f x), ι := { app := λ U, F.germ_to_pullback_stalk _ f (unop U).1 ⟨x, (unop U).2⟩, naturality' := λ _ _ _, by { erw [colimit.pre_desc, category.comp_id], congr } } } /-- The isomorphism `ℱ_{f(x)} ≅ (f⁻¹ℱ)ₓ`. -/ def stalk_pullback_iso (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : F.stalk (f x) ≅ (pullback_obj f F).stalk x := { hom := stalk_pullback_hom _ _ _ _, inv := stalk_pullback_inv _ _ _ _, hom_inv_id' := begin delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward germ_to_pullback_stalk germ, ext j, induction j using opposite.rec, cases j, simp only [topological_space.open_nhds.inclusion_map_iso_inv, whisker_right_app, whisker_left_app, whiskering_left_obj_map, functor.comp_map, colimit.ι_map_assoc, nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app, category.assoc, colimit.ι_pre_assoc], erw [colimit.ι_desc, colimit.pre_desc, colimit.ι_desc, category.comp_id], simpa end, inv_hom_id' := begin delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward, ext U j, induction U using opposite.rec, cases U, cases j, rcases j_right with ⟨⟨⟩⟩, erw [colimit.map_desc, colimit.map_desc, colimit.ι_desc_assoc, colimit.ι_desc_assoc, colimit.ι_desc, category.comp_id], simp only [cocone.whisker_ι, colimit.cocone_ι, open_nhds.inclusion_map_iso_inv, cocones.precompose_obj_ι, whisker_right_app, whisker_left_app, nat_trans.comp_app, whiskering_left_obj_map, nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app], erw ←colimit.w _ (@hom_of_le (open_nhds x) _ ⟨_, U_property⟩ ⟨(opens.map f).obj (unop j_left), j_hom.unop.le U_property⟩ j_hom.unop.le).op, erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _), erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _), congr, simp only [category.assoc, costructured_arrow.map_mk], delta costructured_arrow.mk, congr, end } end stalk_pullback section stalk_specializes variables {C} /-- If `x` specializes to `y`, then there is a natural map `F.stalk y ⟶ F.stalk x`. -/ noncomputable def stalk_specializes (F : X.presheaf C) {x y : X} (h : x ⤳ y) : F.stalk y ⟶ F.stalk x := begin refine colimit.desc _ ⟨_,λ U, _,_⟩, { exact colimit.ι ((open_nhds.inclusion x).op ⋙ F) (op ⟨(unop U).1, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩) }, { intros U V i, dsimp, rw category.comp_id, let U' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩, let V' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop V).1.2 (unop V).2 : _)⟩, exact colimit.w ((open_nhds.inclusion x).op ⋙ F) (show V' ⟶ U', from i.unop).op } end @[simp, reassoc, elementwise] lemma germ_stalk_specializes (F : X.presheaf C) {U : opens X} {y : U} {x : X} (h : x ⤳ y) : F.germ y ≫ F.stalk_specializes h = F.germ (⟨x, h.mem_open U.is_open y.prop⟩ : U) := colimit.ι_desc _ _ @[simp, reassoc, elementwise] lemma germ_stalk_specializes' (F : X.presheaf C) {U : opens X} {x y : X} (h : x ⤳ y) (hy : y ∈ U) : F.germ ⟨y, hy⟩ ≫ F.stalk_specializes h = F.germ ⟨x, h.mem_open U.is_open hy⟩ := colimit.ι_desc _ _ @[simp] lemma stalk_specializes_refl {C : Type*} [category C] [limits.has_colimits C] {X : Top} (F : X.presheaf C) (x : X) : F.stalk_specializes (specializes_refl x) = 𝟙 _ := F.stalk_hom_ext $ λ _ _, by { dsimp, simpa } @[simp, reassoc, elementwise] lemma stalk_specializes_comp {C : Type*} [category C] [limits.has_colimits C] {X : Top} (F : X.presheaf C) {x y z : X} (h : x ⤳ y) (h' : y ⤳ z) : F.stalk_specializes h' ≫ F.stalk_specializes h = F.stalk_specializes (h.trans h') := F.stalk_hom_ext $ λ _ _, by simp @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_functor_map {F G : X.presheaf C} (f : F ⟶ G) {x y : X} (h : x ⤳ y) : F.stalk_specializes h ≫ (stalk_functor C x).map f = (stalk_functor C y).map f ≫ G.stalk_specializes h := by { ext, delta stalk_functor, simpa [stalk_specializes] } @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) {x y : X} (h : x ⤳ y) : (f _* F).stalk_specializes (f.map_specializes h) ≫ F.stalk_pushforward _ f x = F.stalk_pushforward _ f y ≫ F.stalk_specializes h := by { ext, delta stalk_pushforward, simpa [stalk_specializes] } /-- The stalks are isomorphic on inseparable points -/ @[simps] def stalk_congr {X : Top} {C : Type*} [category C] [has_colimits C] (F : X.presheaf C) {x y : X} (e : inseparable x y) : F.stalk x ≅ F.stalk y := ⟨F.stalk_specializes e.ge, F.stalk_specializes e.le, by simp, by simp⟩ end stalk_specializes section concrete variables {C} variables [concrete_category.{v} C] local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun @[ext] lemma germ_ext (F : X.presheaf C) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V} (W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)} (ih : F.map iWU.op sU = F.map iWV.op sV) : F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV := by erw [← F.germ_res iWU ⟨x, hxW⟩, ← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih] variables [preserves_filtered_colimits (forget C)] /-- For presheaves valued in a concrete category whose forgetful functor preserves filtered colimits, every element of the stalk is the germ of a section. -/ lemma germ_exist (F : X.presheaf C) (x : X) (t : stalk F x) : ∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t := begin obtain ⟨U, s, e⟩ := types.jointly_surjective.{v v} _ (is_colimit_of_preserves (forget C) (colimit.is_colimit _)) t, revert s e, rw [(show U = op (unop U), from rfl)], generalize : unop U = V, clear U, cases V with V m, intros s e, exact ⟨V, m, s, e⟩, end lemma germ_eq (F : X.presheaf C) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) (s : F.obj (op U)) (t : F.obj (op V)) (h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) : ∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t := begin obtain ⟨W, iU, iV, e⟩ := (types.filtered_colimit.is_colimit_eq_iff.{v v} _ (is_colimit_of_preserves _ (colimit.is_colimit ((open_nhds.inclusion x).op ⋙ F)))).mp h, exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩, end lemma stalk_functor_map_injective_of_app_injective {F G : presheaf C X} (f : F ⟶ G) (h : ∀ U : opens X, function.injective (f.app (op U))) (x : X) : function.injective ((stalk_functor C x).map f) := λ s t hst, begin rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩, rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩, simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst, obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst, rw [← comp_apply, ← comp_apply, ← f.naturality, ← f.naturality, comp_apply, comp_apply] at heq, replace heq := h W heq, convert congr_arg (F.germ ⟨x,hxW⟩) heq, exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm, (F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm], end variables [has_limits C] [preserves_limits (forget C)] [reflects_isomorphisms (forget C)] /-- Let `F` be a sheaf valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then two sections who agree on every stalk must be equal. -/ lemma section_ext (F : sheaf C X) (U : opens X) (s t : F.1.obj (op U)) (h : ∀ x : U, F.presheaf.germ x s = F.presheaf.germ x t) : s = t := begin -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide. choose V m i₁ i₂ heq using λ x : U, F.presheaf.germ_eq x.1 x.2 x.2 s t (h x), -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these -- neighborhoods form a cover of `U`. apply F.eq_of_locally_eq' V U i₁, { intros x hxU, rw [opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, { intro x, rw [heq, subsingleton.elim (i₁ x) (i₂ x)] } end /- Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism is an epi, but this fact is not yet formalized. -/ lemma app_injective_of_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) (U : opens X) (h : ∀ x : U, function.injective ((stalk_functor C x.val).map f)) : function.injective (f.app (op U)) := λ s t hst, section_ext F _ _ _ $ λ x, h x $ by rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst] lemma app_injective_iff_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) : (∀ x : X, function.injective ((stalk_functor C x).map f)) ↔ (∀ U : opens X, function.injective (f.app (op U))) := ⟨λ h U, app_injective_of_stalk_functor_map_injective f U (λ x, h x.1), stalk_functor_map_injective_of_app_injective f⟩ instance stalk_functor_preserves_mono (x : X) : functor.preserves_monomorphisms (sheaf.forget C X ⋙ stalk_functor C x) := ⟨λ 𝓐 𝓑 f m, concrete_category.mono_of_injective _ $ (app_injective_iff_stalk_functor_map_injective f.1).mpr (λ c, (@@concrete_category.mono_iff_injective_of_preserves_pullback _ _ (f.1.app (op c)) _).mp ((nat_trans.mono_iff_mono_app _ f.1).mp (@@category_theory.presheaf_mono_of_mono _ _ _ _ _ _ _ _ _ _ _ m) $ op c)) x⟩ lemma stalk_mono_of_mono {F G : sheaf C X} (f : F ⟶ G) [mono f] : Π x, mono $ (stalk_functor C x).map f.1 := λ x, by convert functor.map_mono (sheaf.forget.{v} C X ⋙ stalk_functor C x) f lemma mono_of_stalk_mono {F G : sheaf C X} (f : F ⟶ G) [Π x, mono $ (stalk_functor C x).map f.1] : mono f := (Sheaf.hom.mono_iff_presheaf_mono _ _ _).mpr $ (nat_trans.mono_iff_mono_app _ _).mpr $ λ U, (concrete_category.mono_iff_injective_of_preserves_pullback _).mpr $ app_injective_of_stalk_functor_map_injective f.1 U.unop $ λ ⟨x, hx⟩, (concrete_category.mono_iff_injective_of_preserves_pullback _).mp $ infer_instance lemma mono_iff_stalk_mono {F G : sheaf C X} (f : F ⟶ G) : mono f ↔ ∀ x, mono ((stalk_functor C x).map f.1) := ⟨by { introI m, exact stalk_mono_of_mono _ }, by { introI m, exact mono_of_stalk_mono _ }⟩ /-- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` agree on `V`. -/ lemma app_surjective_of_injective_of_locally_surjective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (hinj : ∀ x : U, function.injective ((stalk_functor C x.1).map f.1)) (hsurj : ∀ (t) (x : U), ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.1.obj (op V)), f.1.app (op V) s = G.1.map iVU.op t) : function.surjective (f.1.app (op U)) := begin intro t, -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a -- preimage under `f` on `V`. choose V mV iVU sf heq using hsurj t, -- These neighborhoods clearly cover all of `U`. have V_cover : U ≤ supr V, { intros x hxU, rw [opens.mem_supr], exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ }, -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage. obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _, { use s, apply G.eq_of_locally_eq' V U iVU V_cover, intro x, rw [← comp_apply, ← f.1.naturality, comp_apply, s_spec, heq] }, { intros x y, -- What's left to show here is that the secions `sf` are compatible, i.e. they agree on -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal. apply section_ext, intro z, -- Here, we need to use injectivity of the stalk maps. apply (hinj ⟨z, (iVU x).le ((inf_le_left : V x ⊓ V y ≤ V x) z.2)⟩), dsimp only, erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply], simp_rw [← comp_apply, f.1.naturality, comp_apply, heq, ← comp_apply, ← G.1.map_comp], refl } end lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f.1)) : function.surjective (f.1.app (op U)) := begin refine app_surjective_of_injective_of_locally_surjective f U (λ x, (h x).1) (λ t x, _), -- Now we need to prove our initial claim: That we can find preimages of `t` locally. -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x` obtain ⟨s₀,hs₀⟩ := (h x).2 (G.presheaf.germ x t), -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁` obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.presheaf.germ_exist x.1 s₀, subst hs₁, rename hs₀ hs₁, erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f.1 s₁ at hs₁, -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on -- some open neighborhood `V₂`. obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.presheaf.germ_eq x.1 hxV₁ x.2 _ _ hs₁, -- The restriction of `s₁` to that neighborhood is our desired local preimage. use [V₂, hxV₂, iV₂U, F.1.map iV₂V₁.op s₁], rw [← comp_apply, f.1.naturality, comp_apply, heq], end lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f.1)) : function.bijective (f.1.app (op U)) := ⟨app_injective_of_stalk_functor_map_injective f.1 U (λ x, (h x).1), app_surjective_of_stalk_functor_map_bijective f U h⟩ lemma app_is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) (U : opens X) [∀ x : U, is_iso ((stalk_functor C x.val).map f.1)] : is_iso (f.1.app (op U)) := begin -- Since the forgetful functor of `C` reflects isomorphisms, it suffices to see that the -- underlying map between types is an isomorphism, i.e. bijective. suffices : is_iso ((forget C).map (f.1.app (op U))), { exactI is_iso_of_reflects_iso (f.1.app (op U)) (forget C) }, rw is_iso_iff_bijective, apply app_bijective_of_stalk_functor_map_bijective, intro x, apply (is_iso_iff_bijective _).mp, exact functor.map_is_iso (forget C) ((stalk_functor C x.1).map f.1) end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then if the stalk maps of a morphism `f : F ⟶ G` are all isomorphisms, `f` must be an isomorphism. -/ -- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso` lemma is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) [∀ x : X, is_iso ((stalk_functor C x).map f.1)] : is_iso f := begin -- Since the inclusion functor from sheaves to presheaves is fully faithful, it suffices to -- show that `f`, as a morphism between _presheaves_, is an isomorphism. suffices : is_iso ((sheaf.forget C X).map f), { exactI is_iso_of_fully_faithful (sheaf.forget C X) f }, -- We show that all components of `f` are isomorphisms. suffices : ∀ U : (opens X)ᵒᵖ, is_iso (f.1.app U), { exact @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.1 G.1 f.1 this, }, intro U, induction U using opposite.rec, apply app_is_iso_of_stalk_functor_map_iso end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then a morphism `f : F ⟶ G` is an isomorphism if and only if all of its stalk maps are isomorphisms. -/ lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) : is_iso f ↔ ∀ x : X, is_iso ((stalk_functor C x).map f.1) := begin split, { intros h x, resetI, exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor C x) f.1 ((sheaf.forget C X).map_is_iso f) }, { intro h, exactI is_iso_of_stalk_functor_map_iso f } end end concrete instance (F : X.presheaf CommRing) {U : opens X} (x : U) : algebra (F.obj $ op U) (F.stalk x) := (F.germ x).to_algebra @[simp] lemma stalk_open_algebra_map {X : Top} (F : X.presheaf CommRing) {U : opens X} (x : U) : algebra_map (F.obj $ op U) (F.stalk x) = F.germ x := rfl end Top.presheaf
1c7a87583417e092dd814a3f19e0013f59fb26f2
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/equiv/encodable/lattice.lean
8d46703fdb4cd1e6df118004e5d5490b176f16ba
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
1,940
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import data.equiv.encodable.basic import data.finset.basic import data.set.pairwise /-! # Lattice operations on encodable types Lemmas about lattice and set operations on encodable types ## Implementation Notes This is a separate file, to avoid unnecessary imports in basic files. Previously some of these results were in the `measure_theory` folder. -/ open set namespace encodable variables {α : Type*} {β : Type*} [encodable β] lemma supr_decode₂ [complete_lattice α] (f : β → α) : (⨆ (i : ℕ) (b ∈ decode₂ β i), f b) = (⨆ b, f b) := by { rw [supr_comm], simp [mem_decode₂] } lemma Union_decode₂ (f : β → set α) : (⋃ (i : ℕ) (b ∈ decode₂ β i), f b) = (⋃ b, f b) := supr_decode₂ f @[elab_as_eliminator] lemma Union_decode₂_cases {f : β → set α} {C : set α → Prop} (H0 : C ∅) (H1 : ∀ b, C (f b)) {n} : C (⋃ b ∈ decode₂ β n, f b) := match decode₂ β n with | none := by { simp, apply H0 } | (some b) := by { convert H1 b, simp [ext_iff] } end theorem Union_decode₂_disjoint_on {f : β → set α} (hd : pairwise (disjoint on f)) : pairwise (disjoint on λ i, ⋃ b ∈ decode₂ β i, f b) := begin rintro i j ij x, suffices : ∀ a, encode a = i → x ∈ f a → ∀ b, encode b = j → x ∉ f b, by simpa [decode₂_eq_some], rintro a rfl ha b rfl hb, exact hd a b (mt (congr_arg encode) ij) ⟨ha, hb⟩ end end encodable namespace finset lemma nonempty_encodable {α} (t : finset α) : nonempty $ encodable {i // i ∈ t} := begin classical, induction t using finset.induction with x t hx ih, { refine ⟨⟨λ _, 0, λ _, none, λ ⟨x,y⟩, y.rec _⟩⟩ }, { cases ih with ih, exactI ⟨encodable.of_equiv _ (finset.subtype_insert_equiv_option hx)⟩ } end end finset
5059879216a4b62a5d2dd79489ff65966154586d
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/algebra/category/constructions/functor.hlean
2b5dd3c54ed644e0bd151c88ad637ed99f9964d6
[ "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
9,504
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Functor precategory and category -/ import ..nat_trans ..category open eq functor is_trunc nat_trans iso is_equiv namespace category definition precategory_functor [instance] [reducible] [constructor] (D C : Precategory) : precategory (functor C D) := precategory.mk (λa b, nat_trans a b) (λ a b c g f, nat_trans.compose g f) (λ a, nat_trans.id) (λ a b c d h g f, !nat_trans.assoc) (λ a b f, !nat_trans.id_left) (λ a b f, !nat_trans.id_right) definition Precategory_functor [reducible] [constructor] (D C : Precategory) : Precategory := precategory.Mk (precategory_functor D C) infixr ` ^c `:35 := Precategory_functor section /- we prove that if a natural transformation is pointwise an iso, then it is an iso -/ variables {C D : Precategory} {F G : C ⇒ D} (η : F ⟹ G) [iso : Π(a : C), is_iso (η a)] include iso definition nat_trans_inverse [constructor] : G ⟹ F := nat_trans.mk (λc, (η c)⁻¹) (λc d f, begin apply comp_inverse_eq_of_eq_comp, transitivity (natural_map η d)⁻¹ ∘ to_fun_hom G f ∘ natural_map η c, {apply eq_inverse_comp_of_comp_eq, symmetry, apply naturality}, {apply assoc} end) definition nat_trans_left_inverse : nat_trans_inverse η ∘n η = nat_trans.id := begin fapply (apd011 nat_trans.mk), apply eq_of_homotopy, intro c, apply left_inverse, apply eq_of_homotopy, intros, apply eq_of_homotopy, intros, apply eq_of_homotopy, intros, apply is_hset.elim end definition nat_trans_right_inverse : η ∘n nat_trans_inverse η = nat_trans.id := begin fapply (apd011 nat_trans.mk), apply eq_of_homotopy, intro c, apply right_inverse, apply eq_of_homotopy, intros, apply eq_of_homotopy, intros, apply eq_of_homotopy, intros, apply is_hset.elim end definition is_iso_nat_trans [constructor] [instance] : is_iso η := is_iso.mk (nat_trans_left_inverse η) (nat_trans_right_inverse η) variable (iso) definition functor_iso [constructor] : F ≅ G := @(iso.mk η) !is_iso_nat_trans end section /- and conversely, if a natural transformation is an iso, it is componentwise an iso -/ variables {A B C D : Precategory} {F G : D ^c C} (η : hom F G) [isoη : is_iso η] (c : C) include isoη definition componentwise_is_iso [instance] : is_iso (η c) := @is_iso.mk _ _ _ _ _ (natural_map η⁻¹ c) (ap010 natural_map ( left_inverse η) c) (ap010 natural_map (right_inverse η) c) local attribute componentwise_is_iso [instance] variable {isoη} definition natural_map_inverse : natural_map η⁻¹ c = (η c)⁻¹ := idp variable [isoη] definition naturality_iso {c c' : C} (f : c ⟶ c') : G f = η c' ∘ F f ∘ (η c)⁻¹ := calc G f = (G f ∘ η c) ∘ (η c)⁻¹ : by rewrite comp_inverse_cancel_right ... = (η c' ∘ F f) ∘ (η c)⁻¹ : by rewrite naturality ... = η c' ∘ F f ∘ (η c)⁻¹ : by rewrite assoc definition naturality_iso' {c c' : C} (f : c ⟶ c') : (η c')⁻¹ ∘ G f ∘ η c = F f := calc (η c')⁻¹ ∘ G f ∘ η c = (η c')⁻¹ ∘ η c' ∘ F f : by rewrite naturality ... = F f : by rewrite inverse_comp_cancel_left omit isoη definition componentwise_iso (η : F ≅ G) (c : C) : F c ≅ G c := @iso.mk _ _ _ _ (natural_map (to_hom η) c) (@componentwise_is_iso _ _ _ _ (to_hom η) (struct η) c) definition componentwise_iso_id (c : C) : componentwise_iso (iso.refl F) c = iso.refl (F c) := iso_eq (idpath (ID (F c))) definition componentwise_iso_iso_of_eq (p : F = G) (c : C) : componentwise_iso (iso_of_eq p) c = iso_of_eq (ap010 to_fun_ob p c) := eq.rec_on p !componentwise_iso_id definition natural_map_hom_of_eq (p : F = G) (c : C) : natural_map (hom_of_eq p) c = hom_of_eq (ap010 to_fun_ob p c) := eq.rec_on p idp definition natural_map_inv_of_eq (p : F = G) (c : C) : natural_map (inv_of_eq p) c = hom_of_eq (ap010 to_fun_ob p c)⁻¹ := eq.rec_on p idp definition hom_of_eq_compose_right {H : C ^c B} (p : F = G) : hom_of_eq (ap (λx, x ∘f H) p) = hom_of_eq p ∘nf H := eq.rec_on p idp definition inv_of_eq_compose_right {H : C ^c B} (p : F = G) : inv_of_eq (ap (λx, x ∘f H) p) = inv_of_eq p ∘nf H := eq.rec_on p idp definition hom_of_eq_compose_left {H : B ^c D} (p : F = G) : hom_of_eq (ap (λx, H ∘f x) p) = H ∘fn hom_of_eq p := by induction p; exact !fn_id⁻¹ definition inv_of_eq_compose_left {H : B ^c D} (p : F = G) : inv_of_eq (ap (λx, H ∘f x) p) = H ∘fn inv_of_eq p := by induction p; exact !fn_id⁻¹ definition assoc_natural [constructor] (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) : H ∘f (G ∘f F) ⟹ (H ∘f G) ∘f F := change_natural_map (hom_of_eq !functor.assoc) (λa, id) (λa, !natural_map_hom_of_eq ⬝ ap hom_of_eq !ap010_assoc) definition assoc_natural_rev [constructor] (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) : (H ∘f G) ∘f F ⟹ H ∘f (G ∘f F) := change_natural_map (inv_of_eq !functor.assoc) (λa, id) (λa, !natural_map_inv_of_eq ⬝ ap (λx, hom_of_eq x⁻¹) !ap010_assoc) definition id_left_natural [constructor] (F : C ⇒ D) : functor.id ∘f F ⟹ F := change_natural_map (hom_of_eq !functor.id_left) (λc, id) (λc, by induction F; exact !natural_map_hom_of_eq ⬝ ap hom_of_eq !ap010_functor_mk_eq_constant) definition id_left_natural_rev [constructor] (F : C ⇒ D) : F ⟹ functor.id ∘f F := change_natural_map (inv_of_eq !functor.id_left) (λc, id) (λc, by induction F; exact !natural_map_inv_of_eq ⬝ ap (λx, hom_of_eq x⁻¹) !ap010_functor_mk_eq_constant) definition id_right_natural [constructor] (F : C ⇒ D) : F ∘f functor.id ⟹ F := change_natural_map (hom_of_eq !functor.id_right) (λc, id) (λc, by induction F; exact !natural_map_hom_of_eq ⬝ ap hom_of_eq !ap010_functor_mk_eq_constant) definition id_right_natural_rev [constructor] (F : C ⇒ D) : F ⟹ F ∘f functor.id := change_natural_map (inv_of_eq !functor.id_right) (λc, id) (λc, by induction F; exact !natural_map_inv_of_eq ⬝ ap (λx, hom_of_eq x⁻¹) !ap010_functor_mk_eq_constant) end namespace functor variables {C : Precategory} {D : Category} {F G : D ^c C} definition eq_of_iso_ob (η : F ≅ G) (c : C) : F c = G c := by apply eq_of_iso; apply componentwise_iso; exact η local attribute functor.to_fun_hom [quasireducible] definition eq_of_iso (η : F ≅ G) : F = G := begin fapply functor_eq, {exact (eq_of_iso_ob η)}, {intro c c' f, esimp [eq_of_iso_ob, inv_of_eq, hom_of_eq, eq_of_iso], rewrite [*right_inv iso_of_eq], symmetry, apply @naturality_iso _ _ _ _ _ (iso.struct _) } end definition iso_of_eq_eq_of_iso (η : F ≅ G) : iso_of_eq (eq_of_iso η) = η := begin apply iso_eq, apply nat_trans_eq, intro c, rewrite natural_map_hom_of_eq, esimp [eq_of_iso], rewrite ap010_functor_eq, esimp [hom_of_eq,eq_of_iso_ob], rewrite (right_inv iso_of_eq), end definition eq_of_iso_iso_of_eq (p : F = G) : eq_of_iso (iso_of_eq p) = p := begin apply functor_eq2, intro c, esimp [eq_of_iso], rewrite ap010_functor_eq, esimp [eq_of_iso_ob], rewrite componentwise_iso_iso_of_eq, rewrite (left_inv iso_of_eq) end definition is_univalent (D : Category) (C : Precategory) : is_univalent (D ^c C) := λF G, adjointify _ eq_of_iso iso_of_eq_eq_of_iso eq_of_iso_iso_of_eq end functor definition category_functor [instance] [constructor] (D : Category) (C : Precategory) : category (D ^c C) := category.mk (D ^c C) (functor.is_univalent D C) definition Category_functor [constructor] (D : Category) (C : Precategory) : Category := category.Mk (D ^c C) !category_functor --this definition is only useful if the exponent is a category, -- and the elaborator has trouble with inserting the coercion definition Category_functor' [constructor] (D C : Category) : Category := Category_functor D C namespace ops infixr ` ^c2 `:35 := Category_functor end ops namespace functor variables {C : Precategory} {D : Category} {F G : D ^c C} definition eq_of_pointwise_iso (η : F ⟹ G) (iso : Π(a : C), is_iso (η a)) : F = G := eq_of_iso (functor_iso η iso) definition iso_of_eq_eq_of_pointwise_iso (η : F ⟹ G) (iso : Π(c : C), is_iso (η c)) : iso_of_eq (eq_of_pointwise_iso η iso) = functor_iso η iso := !iso_of_eq_eq_of_iso definition hom_of_eq_eq_of_pointwise_iso (η : F ⟹ G) (iso : Π(c : C), is_iso (η c)) : hom_of_eq (eq_of_pointwise_iso η iso) = η := !hom_of_eq_eq_of_iso definition inv_of_eq_eq_of_pointwise_iso (η : F ⟹ G) (iso : Π(c : C), is_iso (η c)) : inv_of_eq (eq_of_pointwise_iso η iso) = nat_trans_inverse η := !inv_of_eq_eq_of_iso end functor end category
4223a72310822bf555d80d368da6eae541c108a3
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/totient.lean
3bbaa9ae91f5d14f3759df46599818577005a0d9
[ "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
14,785
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.big_operators.basic import data.nat.prime import data.zmod.basic import ring_theory.multiplicity import data.nat.periodic import algebra.char_p.two /-! # Euler's totient function This file defines [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function) `nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`. We prove the divisor sum formula, namely that `n` equals `φ` summed over the divisors of `n`. See `sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and `totient_prime_pow`. -/ open finset open_locale big_operators namespace nat /-- Euler's totient function. This counts the number of naturals strictly less than `n` which are coprime with `n`. -/ def totient (n : ℕ) : ℕ := ((range n).filter n.coprime).card localized "notation `φ` := nat.totient" in nat @[simp] theorem totient_zero : φ 0 = 0 := rfl @[simp] theorem totient_one : φ 1 = 1 := by simp [totient] lemma totient_eq_card_coprime (n : ℕ) : φ n = ((range n).filter n.coprime).card := rfl lemma totient_le (n : ℕ) : φ n ≤ n := ((range n).card_filter_le _).trans_eq (card_range n) lemma totient_lt (n : ℕ) (hn : 1 < n) : φ n < n := (card_lt_card (filter_ssubset.2 ⟨0, by simp [hn.ne', pos_of_gt hn]⟩)).trans_eq (card_range n) lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 := dec_trivial | 1 := by simp [totient] | (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩ lemma filter_coprime_Ico_eq_totient (a n : ℕ) : ((Ico n (n+a)).filter (coprime a)).card = totient a := begin rw [totient, filter_Ico_card_eq_of_periodic, count_eq_card_filter_range], exact periodic_coprime a, end lemma Ico_filter_coprime_le {a : ℕ} (k n : ℕ) (a_pos : 0 < a) : ((Ico k (k + n)).filter (coprime a)).card ≤ totient a * (n / a + 1) := begin conv_lhs { rw ←nat.mod_add_div n a }, induction n / a with i ih, { rw ←filter_coprime_Ico_eq_totient a k, simp only [add_zero, mul_one, mul_zero, le_of_lt (mod_lt n a_pos)], mono, refine monotone_filter_left a.coprime _, simp only [finset.le_eq_subset], exact Ico_subset_Ico rfl.le (add_le_add_left (le_of_lt (mod_lt n a_pos)) k), }, simp only [mul_succ], simp_rw ←add_assoc at ih ⊢, calc (filter a.coprime (Ico k (k + n % a + a * i + a))).card = (filter a.coprime (Ico k (k + n % a + a * i) ∪ Ico (k + n % a + a * i) (k + n % a + a * i + a))).card : begin congr, rw Ico_union_Ico_eq_Ico, rw add_assoc, exact le_self_add, exact le_self_add, end ... ≤ (filter a.coprime (Ico k (k + n % a + a * i))).card + a.totient : begin rw [filter_union, ←filter_coprime_Ico_eq_totient a (k + n % a + a * i)], apply card_union_le, end ... ≤ a.totient * i + a.totient + a.totient : add_le_add_right ih (totient a), end open zmod /-- Note this takes an explicit `fintype ((zmod n)ˣ)` argument to avoid trouble with instance diamonds. -/ @[simp] lemma _root_.zmod.card_units_eq_totient (n : ℕ) [fact (0 < n)] [fintype ((zmod n)ˣ)] : fintype.card ((zmod n)ˣ) = φ n := calc fintype.card ((zmod n)ˣ) = fintype.card {x : zmod n // x.val.coprime n} : fintype.card_congr zmod.units_equiv_coprime ... = φ n : begin apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val), { intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} }, { intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, }, { intros b hb, rw [finset.mem_filter, finset.mem_range] at hb, refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩, { let u := unit_of_coprime b hb.2.symm, exact val_coe_unit_coprime u }, { show zmod.val (b : zmod n) = b, rw [val_nat_cast, nat.mod_eq_of_lt hb.1], } } end lemma totient_even {n : ℕ} (hn : 2 < n) : even n.totient := begin haveI : fact (1 < n) := ⟨one_lt_two.trans hn⟩, suffices : 2 = order_of (-1 : (zmod n)ˣ), { rw [← zmod.card_units_eq_totient, even_iff_two_dvd, this], exact order_of_dvd_card_univ }, rw [←order_of_units, units.coe_neg_one, order_of_neg_one, ring_char.eq (zmod n) n, if_neg hn.ne'], end lemma totient_mul {m n : ℕ} (h : m.coprime n) : φ (m * n) = φ m * φ n := if hmn0 : m * n = 0 then by cases nat.mul_eq_zero.1 hmn0 with h h; simp only [totient_zero, mul_zero, zero_mul, h] else begin haveI : fact (0 < (m * n)) := ⟨nat.pos_of_ne_zero hmn0⟩, haveI : fact (0 < m) := ⟨nat.pos_of_ne_zero $ left_ne_zero_of_mul hmn0⟩, haveI : fact (0 < n) := ⟨nat.pos_of_ne_zero $ right_ne_zero_of_mul hmn0⟩, simp only [← zmod.card_units_eq_totient], rw [fintype.card_congr (units.map_equiv (zmod.chinese_remainder h).to_mul_equiv).to_equiv, fintype.card_congr (@mul_equiv.prod_units (zmod m) (zmod n) _ _).to_equiv, fintype.card_prod] end lemma sum_totient (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n := if hn0 : n = 0 then by simp [hn0] else calc ∑ m in (range n.succ).filter (∣ n), φ m = ∑ d in (range n.succ).filter (∣ n), ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card : eq.symm $ sum_bij (λ d _, n / d) (λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩) (λ _ _, rfl) (λ a b ha hb h, have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2, have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *), by rw [← nat.mul_left_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2]) (λ b hb, have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb, have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩, have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn, ⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩, by rw [← nat.mul_left_inj (nat.pos_of_ne_zero hnb0), nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩) ... = ∑ d in (range n.succ).filter (∣ n), ((range n).filter (λ m, gcd n m = d)).card : sum_congr rfl (λ d hd, have hd : d ∣ n, from (mem_filter.1 hd).2, have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)), card_congr (λ m hm, d * m) (λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm, mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸ (mul_lt_mul_left hd0).2 hm.1, by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩) (λ a b ha hb h, (nat.mul_right_inj hd0).1 h) (λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb, ⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1 (by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _), nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)), hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩, hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩)) ... = ((filter (∣ n) (range n.succ)).bUnion (λ d, (range n).filter (λ m, gcd n m = d))).card : (card_bUnion (by intros; apply disjoint_filter.2; cc)).symm ... = (range n).card : congr_arg card (finset.ext (λ m, ⟨by simp, λ hm, have h : m < n, from mem_range.1 hm, mem_bUnion.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (zero_le _) h) (gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩)) ... = n : card_range _ /-- When `p` is prime, then the totient of `p ^ (n + 1)` is `p ^ n * (p - 1)` -/ lemma totient_prime_pow_succ {p : ℕ} (hp : p.prime) (n : ℕ) : φ (p ^ (n + 1)) = p ^ n * (p - 1) := calc φ (p ^ (n + 1)) = ((range (p ^ (n + 1))).filter (coprime (p ^ (n + 1)))).card : totient_eq_card_coprime _ ... = (range (p ^ (n + 1)) \ ((range (p ^ n)).image (* p))).card : congr_arg card begin rw [sdiff_eq_filter], apply filter_congr, simp only [mem_range, mem_filter, coprime_pow_left_iff n.succ_pos, mem_image, not_exists, hp.coprime_iff_not_dvd], intros a ha, split, { rintros hap b _ rfl, exact hap (dvd_mul_left _ _) }, { rintros h ⟨b, rfl⟩, rw [pow_succ] at ha, exact h b (lt_of_mul_lt_mul_left ha (zero_le _)) (mul_comm _ _) } end ... = _ : have h1 : set.inj_on (* p) (range (p ^ n)), from λ x _ y _, (nat.mul_left_inj hp.pos).1, have h2 : (range (p ^ n)).image (* p) ⊆ range (p ^ (n + 1)), from λ a, begin simp only [mem_image, mem_range, exists_imp_distrib], rintros b h rfl, rw [pow_succ'], exact (mul_lt_mul_right hp.pos).2 h end, begin rw [card_sdiff h2, card_image_of_inj_on h1, card_range, card_range, ← one_mul (p ^ n), pow_succ, ← tsub_mul, one_mul, mul_comm] end /-- When `p` is prime, then the totient of `p ^ n` is `p ^ (n - 1) * (p - 1)` -/ lemma totient_prime_pow {p : ℕ} (hp : p.prime) {n : ℕ} (hn : 0 < n) : φ (p ^ n) = p ^ (n - 1) * (p - 1) := by rcases exists_eq_succ_of_ne_zero (pos_iff_ne_zero.1 hn) with ⟨m, rfl⟩; exact totient_prime_pow_succ hp _ lemma totient_prime {p : ℕ} (hp : p.prime) : φ p = p - 1 := by rw [← pow_one p, totient_prime_pow hp]; simp lemma totient_mul_of_prime_of_dvd {p n : ℕ} (hp : p.prime) (h : p ∣ n) : (p * n).totient = p * n.totient := begin by_cases hzero : n = 0, { simp [hzero] }, { have hfin := (multiplicity.finite_nat_iff.2 ⟨hp.ne_one, zero_lt_iff.2 hzero⟩), have h0 : 0 < (multiplicity p n).get hfin := multiplicity.pos_of_dvd hfin h, obtain ⟨m, hm, hndiv⟩ := multiplicity.exists_eq_pow_mul_and_not_dvd hfin, rw [hm, ← mul_assoc, ← pow_succ, nat.totient_mul (coprime_comm.mp (hp.coprime_pow_of_not_dvd hndiv)), nat.totient_mul (coprime_comm.mp (hp.coprime_pow_of_not_dvd hndiv)), ← mul_assoc], congr, rw [ ← succ_pred_eq_of_pos h0, totient_prime_pow_succ hp, totient_prime_pow_succ hp, succ_pred_eq_of_pos h0, ← mul_assoc p, ← pow_succ, ← succ_pred_eq_of_pos h0, nat.pred_succ] } end lemma totient_eq_iff_prime {p : ℕ} (hp : 0 < p) : p.totient = p - 1 ↔ p.prime := begin refine ⟨λ h, _, totient_prime⟩, replace hp : 1 < p, { apply lt_of_le_of_ne, { rwa succ_le_iff }, { rintro rfl, rw [totient_one, tsub_self] at h, exact one_ne_zero h } }, rw [totient_eq_card_coprime, range_eq_Ico, ←Ico_insert_succ_left hp.le, finset.filter_insert, if_neg (not_coprime_of_dvd_of_dvd hp (dvd_refl p) (dvd_zero p)), ←nat.card_Ico 1 p] at h, refine p.prime_of_coprime hp (λ n hn hnz, finset.filter_card_eq h n $ finset.mem_Ico.mpr ⟨_, hn⟩), rwa [succ_le_iff, pos_iff_ne_zero], end lemma card_units_zmod_lt_sub_one {p : ℕ} (hp : 1 < p) [fintype ((zmod p)ˣ)] : fintype.card ((zmod p)ˣ) ≤ p - 1 := begin haveI : fact (0 < p) := ⟨zero_lt_one.trans hp⟩, rw zmod.card_units_eq_totient p, exact nat.le_pred_of_lt (nat.totient_lt p hp), end lemma prime_iff_card_units (p : ℕ) [fintype ((zmod p)ˣ)] : p.prime ↔ fintype.card ((zmod p)ˣ) = p - 1 := begin by_cases hp : p = 0, { substI hp, simp only [zmod, not_prime_zero, false_iff, zero_tsub], -- the substI created an non-defeq but subsingleton instance diamond; resolve it suffices : fintype.card ℤˣ ≠ 0, { convert this }, simp }, haveI : fact (0 < p) := ⟨nat.pos_of_ne_zero hp⟩, rw [zmod.card_units_eq_totient, nat.totient_eq_iff_prime (fact.out (0 < p))], end @[simp] lemma totient_two : φ 2 = 1 := (totient_prime prime_two).trans rfl lemma totient_eq_one_iff : ∀ {n : ℕ}, n.totient = 1 ↔ n = 1 ∨ n = 2 | 0 := by simp | 1 := by simp | 2 := by simp | (n+3) := begin have : 3 ≤ n + 3 := le_add_self, simp only [succ_succ_ne_one, false_or], exact ⟨λ h, not_even_one.elim $ h ▸ totient_even this, by rintro ⟨⟩⟩, end /-! ### Euler's product formula for the totient function We prove several different statements of this formula. -/ /-- Euler's product formula for the totient function. -/ theorem totient_eq_prod_factorization {n : ℕ} (hn : n ≠ 0) : φ n = n.factorization.prod (λ p k, p ^ (k - 1) * (p - 1)) := begin rw multiplicative_factorization φ @totient_mul totient_one hn, apply finsupp.prod_congr (λ p hp, _), have h := zero_lt_iff.mpr (finsupp.mem_support_iff.mp hp), rw [totient_prime_pow (prime_of_mem_factorization hp) h], end /-- Euler's product formula for the totient function. -/ theorem totient_mul_prod_factors (n : ℕ) : φ n * ∏ p in n.factors.to_finset, p = n * ∏ p in n.factors.to_finset, (p - 1) := begin by_cases hn : n = 0, { simp [hn] }, rw totient_eq_prod_factorization hn, nth_rewrite 2 ←factorization_prod_pow_eq_self hn, simp only [←prod_factorization_eq_prod_factors, ←finsupp.prod_mul], refine finsupp.prod_congr (λ p hp, _), rw [finsupp.mem_support_iff, ← zero_lt_iff] at hp, rw [mul_comm, ←mul_assoc, ←pow_succ, nat.sub_add_cancel hp], end /-- Euler's product formula for the totient function. -/ theorem totient_eq_div_factors_mul (n : ℕ) : φ n = n / (∏ p in n.factors.to_finset, p) * (∏ p in n.factors.to_finset, (p - 1)) := begin rw [← mul_div_left n.totient, totient_mul_prod_factors, mul_comm, nat.mul_div_assoc _ (prod_prime_factors_dvd n), mul_comm], simpa [prod_factorization_eq_prod_factors] using prod_pos (λ p, pos_of_mem_factorization), end /-- Euler's product formula for the totient function. -/ theorem totient_eq_mul_prod_factors (n : ℕ) : (φ n : ℚ) = n * ∏ p in n.factors.to_finset, (1 - p⁻¹) := begin by_cases hn : n = 0, { simp [hn] }, have hn' : (n : ℚ) ≠ 0, { simp [hn] }, have hpQ : ∏ p in n.factors.to_finset, (p : ℚ) ≠ 0, { rw [←cast_prod, cast_ne_zero, ←zero_lt_iff, ←prod_factorization_eq_prod_factors], exact prod_pos (λ p hp, pos_of_mem_factorization hp) }, simp only [totient_eq_div_factors_mul n, prod_prime_factors_dvd n, cast_mul, cast_prod, cast_div_char_zero, mul_comm_div, mul_right_inj' hn', div_eq_iff hpQ, ←prod_mul_distrib], refine prod_congr rfl (λ p hp, _), have hp := pos_of_mem_factors (list.mem_to_finset.mp hp), have hp' : (p : ℚ) ≠ 0 := cast_ne_zero.mpr hp.ne.symm, rw [sub_mul, one_mul, mul_comm, mul_inv_cancel hp', cast_pred hp], end end nat
7aa35fbbb7219f5cea76af126d836238fcf3ecfb
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/topology/metric_space/emetric_space.lean
7cf2000d8f47ea87c172ab2316336d0d9fbfe0d4
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
37,649
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.real.nnreal data.real.ennreal import topology.uniform_space.separation topology.uniform_space.uniform_embedding topology.uniform_space.pi import topology.bases /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open lattice set filter classical noncomputable theory open_locale uniformity topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /- Design note: one could define an `emetric_space` just by giving `edist`, and then derive an instance of `uniform_space` by taking the natural uniform structure associated to the distance. This creates diamonds problem for products, as the uniform structure on the product of two emetric spaces could be obtained first by obtaining two uniform spaces and then taking their products, or by taking the product of the emetric spaces and then the associated uniform structure. The two uniform structure we have just described are equal, but not defeq, which creates a lot of problem. The idea is to add, in the very definition of an `emetric_space`, a uniform structure with a uniformity which equal to the one given by the distance, but maybe not defeq. And the instance from `emetric_space` to `uniform_space` uses this uniformity. In this way, when we create the product of emetric spaces, we put in the product the uniformity corresponding to the product of the uniformities. There is one more proof obligation, that this product uniformity is equal to the uniformity corresponding to the product metric. But the diamond problem disappears. The same trick is used in the definition of a metric space, where one stores as well a uniform structure and an edistance. -/ /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, this ▸ ennreal.nat_ne_top 2⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], 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 [edist_comm] } section prio set_option default_priority 100 -- see Note [default priority] /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric 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 an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is finally proving in `topology.instances.ennreal` -/ class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) end prio /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space α export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := le_zero_iff_eq.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z) /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, edist (f i) (f (i + 1))) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ennreal) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ (finset.Ico m n).sum _ + _ : add_le_add' hrec (le_refl _) ... = (finset.Ico m (n+1)).sum _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ (finset.range n).sum (λ i, edist (f i) (f (i + 1))) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ (finset.Ico m n).sum d := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ (finset.range n).sum d := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε, ε > 0 → edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist' : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) := emetric_space.uniformity_edist _ /-- Reformulation of the uniform structure in terms of the extended distance on a subtype -/ theorem uniformity_edist'' : 𝓤 α = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) := by { simp only [infi_subtype], exact uniformity_edist' } /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := begin rw [uniformity_edist'', mem_infi], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩, exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ end /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniformity_edist_nnreal : 𝓤 α = (⨅(ε:nnreal) (h : ε > 0), principal {p:α×α | edist p.1 p.2 < ε}) := begin rw [uniformity_edist', ennreal.infi_ennreal, inf_of_le_left], { congr, funext ε, refine infi_congr_Prop ennreal.coe_pos _, assume h, refl }, refine le_infi (assume h, infi_le_of_le 1 $ infi_le_of_le ennreal.zero_lt_one $ _), exact principal_mono.2 (assume p h, lt_of_lt_of_le h le_top) end theorem mem_uniformity_edist_inv_nat {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃n:ℕ, ∀ a b : α, edist a b < n⁻¹ → (a, b) ∈ s) := begin refine mem_uniformity_edist.trans ⟨λ hs, _, λ hs, _⟩, { rcases hs with ⟨ε, ε_pos, hε⟩, rcases ennreal.exists_inv_nat_lt (ne_of_gt ε_pos) with ⟨n, hn⟩, exact ⟨n, λ a b hab, hε (lt_trans hab hn)⟩ }, { rcases hs with ⟨n, hn⟩, exact ⟨n⁻¹, ennreal.inv_pos.2 ennreal.coe_nat_ne_top, hn⟩ } end theorem uniformity_edist_inv_nat : 𝓤 α = (⨅ n:ℕ, principal {p:α×α | edist p.1 p.2 < n⁻¹}) := begin refine eq_infi_of_mem_sets_iff_exists_mem (λ s, mem_uniformity_edist_inv_nat.trans _), exact exists_congr (λn, by simp only [prod.forall, mem_principal_sets, subset_def, mem_set_of_eq]) end namespace emetric theorem uniformity_has_countable_basis : has_countable_basis (𝓤 α) := has_countable_basis_of_seq _ _ uniformity_edist_inv_nat /-- ε-δ characterization of uniform continuity on emetric spaces -/ theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_edist.1 $ H _ $ edist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_edist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ /-- ε-δ characterization of uniform embeddings on emetric spaces -/ theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist 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 : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (edist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (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 complete_of_convergent_controlled_sequences (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ (emetric_space.to_uniform_space α)) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced subtype.val (λ x y, subtype.eq) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist x.1 y.1 := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, 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 } section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [ext_iff, εpos] end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := lattice.ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ theorem nhds_eq : 𝓝 x = (⨅ε:{ε:ennreal // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_edist'', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, edist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := begin rw [nhds_eq, mem_infi], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right, (≥)] }, { exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ } end theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_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 : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ theorem mem_closure_iff' : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := ⟨begin intros hx ε hε, have A : ball x ε ∩ s ≠ ∅ := mem_closure_iff.1 hx _ is_open_ball (mem_ball_self hε), cases ne_empty_iff_exists_mem.1 A with y hy, simp, exact ⟨y, ⟨hy.2, by have B := hy.1; simpa [mem_ball'] using B⟩⟩ end, begin intros H, apply mem_closure_iff.2, intros o ho xo, rcases is_open_iff.1 ho x xo with ⟨ε, ⟨εpos, hε⟩⟩, rcases H ε εpos with ⟨y, ⟨ys, ydist⟩⟩, have B : y ∈ o ∩ s := ⟨hε (by simpa [edist_comm]), ys⟩, apply ne_empty_of_mem B end⟩ theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, edist (u x) a < ε := ⟨λ H ε ε0, ⟨u⁻¹' (ball a ε), H (ball_mem_nhds _ ε0), by simp⟩, λ H s hs, let ⟨ε, ε0, hε⟩ := mem_nhds_iff.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in f.sets_of_superset δ0 (λx xδ, hε (hδ x xδ))⟩ theorem tendsto_at_top [inhabited β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := begin rw tendsto_nhds, apply forall_congr, intro ε, apply forall_congr, intro hε, simp, exact ⟨λ ⟨s, ⟨N, hN⟩, hs⟩, ⟨N, λn hn, hs _ (hN _ hn)⟩, λ ⟨N, hN⟩, ⟨{n | n ≥ N}, ⟨⟨N, by simp⟩, hN⟩⟩⟩, end /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ theorem cauchy_seq_iff [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u n) (u m) < ε := begin simp only [cauchy_seq, emetric.cauchy_iff, true_and, exists_prop, filter.mem_at_top_sets, filter.at_top_ne_bot, filter.mem_map, ne.def, filter.map_eq_bot_iff, not_false_iff, set.mem_set_of_eq], split, { intros H ε εpos, rcases H ε εpos with ⟨t, ⟨N, hN⟩, ht⟩, exact ⟨N, λm n hm hn, ht _ _ (hN _ hn) (hN _ hm)⟩ }, { intros H ε εpos, rcases H (ε/2) (ennreal.half_pos εpos) with ⟨N, hN⟩, existsi ball (u N) (ε/2), split, { exact ⟨N, λx hx, hN _ _ (le_refl N) hx⟩ }, { exact λx y hx hy, calc edist x y ≤ edist x (u N) + edist y (u N) : edist_triangle_right _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add hx hy ... = ε : ennreal.add_halves _ } } end /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := begin rw cauchy_seq_iff, split, { intros H ε εpos, rcases H ε εpos with ⟨N, hN⟩, exact ⟨N, λn hn, hN _ _ (le_refl N) hn⟩ }, { intros H ε εpos, rcases H (ε/2) (ennreal.half_pos εpos) with ⟨N, hN⟩, exact ⟨N, λ m n hm hn, calc edist (u n) (u m) ≤ edist (u n) (u N) + edist (u m) (u N) : edist_triangle_right _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add (hN _ hn) (hN _ hm) ... = ε : ennreal.add_halves _⟩ } end /-- A variation of the emetric characterization of Cauchy sequences that deals with `nnreal` upper bounds. -/ theorem cauchy_seq_iff_nnreal [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u N) (u n) < ε := begin refine cauchy_seq_iff'.trans ⟨λ H ε εpos, (H ε (ennreal.coe_pos.2 εpos)).imp $ λ N hN n hn, edist_comm (u n) (u N) ▸ hN n hn, λ H ε εpos, _⟩, specialize H ((min 1 ε).to_nnreal) (ennreal.to_nnreal_pos_iff.2 ⟨lt_min ennreal.zero_lt_one εpos, ennreal.lt_top_iff_ne_top.1 $ min_lt_iff.2 $ or.inl ennreal.coe_lt_top⟩), refine H.imp (λ N hN n hn, edist_comm (u N) (u n) ▸ lt_of_lt_of_le (hN n hn) _), refine ennreal.coe_le_iff.2 _, rintros ε rfl, rw [← ennreal.coe_one, ← ennreal.coe_min, ennreal.to_nnreal_coe], apply min_le_right end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, countable_finite], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff'.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : closure_eq_of_is_closed (closed_of_compact _ hs), exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ α in ⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, { apply countable_bUnion S_countable, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space α = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.half_pos εpos, /- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and then `x` in `S` at distance at most `n⁻¹` of `a` -/ rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff'.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := Sup ((λp : α × α, edist p.1 p.2) '' (set.prod s s)) /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := le_Sup ((mem_image _ _ _).2 ⟨(⟨x, y⟩ : α × α), by simp [hx, hy]⟩) /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀x y ∈ s, edist x y ≤ d) : diam s ≤ d := begin apply Sup_le _, simp only [and_imp, set.mem_image, set.mem_prod, exists_imp_distrib, prod.exists], assume b x y xs ys dxy, rw ← dxy, exact h x y xs ys end /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := by simp [diam] /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := by simp [diam] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := begin refine Sup_le_Sup (λp hp, _), simp only [set.mem_image, set.mem_prod, prod.exists] at hp, rcases hp with ⟨x, y, ⟨⟨xs, ys⟩, dxy⟩⟩, exact (mem_image _ _ _).2 ⟨⟨x, y⟩, ⟨⟨h xs, h ys⟩, dxy⟩⟩ end /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa b ha hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := ne_empty_iff_exists_mem.1 h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa b ha hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add' ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
fa70b8662add27767dfaac25766478632b31d899
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/prime_ideal.lean
9757bbb43ad66509c4e7dac796615167bbbbde54
[ "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
6,213
lean
/- Copyright (c) 2021 Noam Atar. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Noam Atar -/ import order.ideal import order.pfilter /-! # Prime ideals ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `order.ideal.prime_pair`: A pair of an `ideal` and a `pfilter` which form a partition of `P`. This is useful as giving the data of a prime ideal is the same as giving the data of a prime filter. - `order.ideal.is_prime`: a predicate for prime ideals. Dual to the notion of a prime filter. - `order.pfilter.is_prime`: a predicate for prime filters. Dual to the notion of a prime ideal. ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> ## Tags ideal, prime -/ open order.pfilter namespace order variables {P : Type*} namespace ideal /-- A pair of an `ideal` and a `pfilter` which form a partition of `P`. -/ @[nolint has_inhabited_instance] structure prime_pair (P : Type*) [preorder P] := (I : ideal P) (F : pfilter P) (is_compl_I_F : is_compl (I : set P) F) namespace prime_pair variables [preorder P] (IF : prime_pair P) lemma compl_I_eq_F : (IF.I : set P)ᶜ = IF.F := IF.is_compl_I_F.compl_eq lemma compl_F_eq_I : (IF.F : set P)ᶜ = IF.I := IF.is_compl_I_F.eq_compl.symm lemma I_is_proper : is_proper IF.I := begin cases IF.F.nonempty, apply is_proper_of_not_mem (_ : w ∉ IF.I), rwa ← IF.compl_I_eq_F at h, end lemma disjoint : disjoint (IF.I : set P) IF.F := IF.is_compl_I_F.disjoint lemma I_union_F : (IF.I : set P) ∪ IF.F = set.univ := IF.is_compl_I_F.sup_eq_top lemma F_union_I : (IF.F : set P) ∪ IF.I = set.univ := IF.is_compl_I_F.symm.sup_eq_top end prime_pair /-- An ideal `I` is prime if its complement is a filter. -/ @[mk_iff] class is_prime [preorder P] (I : ideal P) extends is_proper I : Prop := (compl_filter : is_pfilter (I : set P)ᶜ) section preorder variable [preorder P] /-- Create an element of type `order.ideal.prime_pair` from an ideal satisfying the predicate `order.ideal.is_prime`. -/ def is_prime.to_prime_pair {I : ideal P} (h : is_prime I) : prime_pair P := { I := I, F := h.compl_filter.to_pfilter, is_compl_I_F := is_compl_compl } lemma prime_pair.I_is_prime (IF : prime_pair P) : is_prime IF.I := { compl_filter := by { rw IF.compl_I_eq_F, exact IF.F.is_pfilter }, ..IF.I_is_proper } end preorder section semilattice_inf variables [semilattice_inf P] {x y : P} {I : ideal P} lemma is_prime.mem_or_mem (hI : is_prime I) {x y : P} : x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := begin contrapose!, let F := hI.compl_filter.to_pfilter, show x ∈ F ∧ y ∈ F → x ⊓ y ∈ F, exact λ h, inf_mem _ h.1 _ h.2, end lemma is_prime.of_mem_or_mem [is_proper I] (hI : ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I) : is_prime I := begin rw is_prime_iff, use ‹_›, apply is_pfilter.of_def, { exact set.nonempty_compl.2 (I.is_proper_iff.1 ‹_›) }, { intros x _ y _, refine ⟨x ⊓ y, _, inf_le_left, inf_le_right⟩, have := mt hI, tauto! }, { exact @mem_compl_of_ge _ _ _ } end lemma is_prime_iff_mem_or_mem [is_proper I] : is_prime I ↔ ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := ⟨is_prime.mem_or_mem, is_prime.of_mem_or_mem⟩ end semilattice_inf section distrib_lattice variables [distrib_lattice P] {I : ideal P} @[priority 100] instance is_maximal.is_prime [is_maximal I] : is_prime I := begin rw is_prime_iff_mem_or_mem, intros x y, contrapose!, rintro ⟨hx, hynI⟩ hxy, apply hynI, let J := I ⊔ principal x, have hJuniv : (J : set P) = set.univ := is_maximal.maximal_proper (lt_sup_principal_of_not_mem ‹_›), have hyJ : y ∈ ↑J := set.eq_univ_iff_forall.mp hJuniv y, rw coe_sup_eq at hyJ, rcases hyJ with ⟨a, ha, b, hb, hy⟩, rw hy, apply sup_mem _ ha _, refine I.mem_of_le (le_inf hb _) hxy, rw hy, exact le_sup_right end end distrib_lattice section boolean_algebra variables [boolean_algebra P] {x : P} {I : ideal P} lemma is_prime.mem_or_compl_mem (hI : is_prime I) : x ∈ I ∨ xᶜ ∈ I := begin apply hI.mem_or_mem, rw inf_compl_eq_bot, exact bot_mem, end lemma is_prime.mem_compl_of_not_mem (hI : is_prime I) (hxnI : x ∉ I) : xᶜ ∈ I := hI.mem_or_compl_mem.resolve_left hxnI lemma is_prime_of_mem_or_compl_mem [is_proper I] (h : ∀ {x : P}, x ∈ I ∨ xᶜ ∈ I) : is_prime I := begin simp only [is_prime_iff_mem_or_mem, or_iff_not_imp_left], intros x y hxy hxI, have hxcI : xᶜ ∈ I := h.resolve_left hxI, have ass : (x ⊓ y) ⊔ (y ⊓ xᶜ) ∈ I := sup_mem _ hxy _ (mem_of_le I inf_le_right hxcI), rwa [inf_comm, sup_inf_inf_compl] at ass end lemma is_prime_iff_mem_or_compl_mem [is_proper I] : is_prime I ↔ ∀ {x : P}, x ∈ I ∨ xᶜ ∈ I := ⟨λ h _, h.mem_or_compl_mem, is_prime_of_mem_or_compl_mem⟩ @[priority 100] instance is_prime.is_maximal [is_prime I] : is_maximal I := begin simp only [is_maximal_iff, set.eq_univ_iff_forall, is_prime.to_is_proper, true_and], intros J hIJ x, rcases set.exists_of_ssubset hIJ with ⟨y, hyJ, hyI⟩, suffices ass : (x ⊓ y) ⊔ (x ⊓ yᶜ) ∈ J, { rwa sup_inf_inf_compl at ass }, exact sup_mem _ (J.mem_of_le inf_le_right hyJ) _ (hIJ.le $ I.mem_of_le inf_le_right $ is_prime.mem_compl_of_not_mem ‹_› hyI), end end boolean_algebra end ideal namespace pfilter variable [preorder P] /-- A filter `F` is prime if its complement is an ideal. -/ @[mk_iff] class is_prime (F : pfilter P) : Prop := (compl_ideal : is_ideal (F : set P)ᶜ) /-- Create an element of type `order.ideal.prime_pair` from a filter satisfying the predicate `order.pfilter.is_prime`. -/ def is_prime.to_prime_pair {F : pfilter P} (h : is_prime F) : ideal.prime_pair P := { I := h.compl_ideal.to_ideal, F := F, is_compl_I_F := is_compl_compl.symm } lemma _root_.order.ideal.prime_pair.F_is_prime (IF : ideal.prime_pair P) : is_prime IF.F := { compl_ideal := by { rw IF.compl_F_eq_I, exact IF.I.is_ideal } } end pfilter end order
77c5ceee66819bdf3df5302f05510f2f0d712228
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_topology/dold_kan/functor_n.lean
74f4d58a98df47f3358e4133c11fdd701007fdcd
[ "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
2,557
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.p_infty /-! # Construction of functors N for the Dold-Kan correspondence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. TODO (@joelriou) continue adding the various files referenced below In this file, we construct functors `N₁ : simplicial_object C ⥤ karoubi (chain_complex C ℕ)` and `N₂ : karoubi (simplicial_object C) ⥤ karoubi (chain_complex C ℕ)` for any preadditive category `C`. (The indices of these functors are the number of occurrences of `karoubi` at the source or the target.) In the case `C` is additive, the functor `N₂` shall be the functor of the equivalence `category_theory.preadditive.dold_kan.equivalence` defined in `equivalence_additive.lean`. In the case the category `C` is pseudoabelian, the composition of `N₁` with the inverse of the equivalence `chain_complex C ℕ ⥤ karoubi (chain_complex C ℕ)` will be the functor `category_theory.idempotents.dold_kan.N` of the equivalence of categories `category_theory.idempotents.dold_kan.equivalence : simplicial_object C ≌ chain_complex C ℕ` defined in `equivalence_pseudoabelian.lean`. When the category `C` is abelian, a relation between `N₁` and the normalized Moore complex functor shall be obtained in `normalized.lean`. (See `equivalence.lean` for the general strategy of proof of the Dold-Kan equivalence.) -/ open category_theory open category_theory.category open category_theory.idempotents noncomputable theory namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] /-- The functor `simplicial_object C ⥤ karoubi (chain_complex C ℕ)` which maps `X` to the formal direct factor of `K[X]` defined by `P_infty`. -/ @[simps] def N₁ : simplicial_object C ⥤ karoubi (chain_complex C ℕ) := { obj := λ X, { X := alternating_face_map_complex.obj X, p := P_infty, idem := P_infty_idem, }, map := λ X Y f, { f := P_infty ≫ alternating_face_map_complex.map f, comm := by { ext, simp }, }, map_id' := λ X, by { ext, dsimp, simp }, map_comp' := λ X Y Z f g, by { ext, simp } } /-- The extension of `N₁` to the Karoubi envelope of `simplicial_object C`. -/ @[simps] def N₂ : karoubi (simplicial_object C) ⥤ karoubi (chain_complex C ℕ) := (functor_extension₁ _ _).obj N₁ end dold_kan end algebraic_topology
5fa5dbcca2afc4fec0f49d95840e6ffc0be94437
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/fintype/intervals.lean
5c4774433eedd2c41a25942e9dd09592bc91c778
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,593
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.set.intervals import data.set.finite import data.pnat.intervals /-! # fintype instances for intervals We provide `fintype` instances for `Ico l u`, for `l u : ℕ`, and for `l u : ℤ`. -/ namespace set instance Ico_ℕ_fintype (l u : ℕ) : fintype (Ico l u) := fintype.of_finset (finset.Ico l u) $ (λ n, by { simp only [mem_Ico, finset.Ico.mem], }) @[simp] lemma Ico_ℕ_card (l u : ℕ) : fintype.card (Ico l u) = u - l := calc fintype.card (Ico l u) = (finset.Ico l u).card : fintype.card_of_finset _ _ ... = u - l : finset.Ico.card l u instance Ico_pnat_fintype (l u : ℕ+) : fintype (Ico l u) := fintype.of_finset (pnat.Ico l u) $ (λ n, by { simp only [mem_Ico, pnat.Ico.mem], }) @[simp] lemma Ico_pnat_card (l u : ℕ+) : fintype.card (Ico l u) = u - l := calc fintype.card (Ico l u) = (pnat.Ico l u).card : fintype.card_of_finset _ _ ... = u - l : pnat.Ico.card l u instance Ico_ℤ_fintype (l u : ℤ) : fintype (Ico l u) := fintype.of_finset (finset.Ico_ℤ l u) $ (λ n, by { simp only [mem_Ico, finset.Ico_ℤ.mem], }) instance Ioo_ℤ_fintype (l u : ℤ) : fintype (Ioo l u) := fintype.of_finset (finset.Ico_ℤ (l+1) u) $ λ n, by simp only [mem_Ioo, finset.Ico_ℤ.mem, int.add_one_le_iff, iff_self, implies_true_iff] instance Icc_ℤ_fintype (l u : ℤ) : fintype (Icc l u) := fintype.of_finset (finset.Ico_ℤ l (u+1)) $ λ n, by simp only [mem_Icc, finset.Ico_ℤ.mem, int.lt_add_one_iff, iff_self, implies_true_iff] instance Ioc_ℤ_fintype (l u : ℤ) : fintype (Ioc l u) := fintype.of_finset (finset.Ico_ℤ (l+1) (u+1)) $ λ n, by simp only [mem_Ioc, finset.Ico_ℤ.mem, int.add_one_le_iff, int.lt_add_one_iff, iff_self, implies_true_iff] lemma Ico_ℤ_finite (l u : ℤ) : set.finite (Ico l u) := ⟨set.Ico_ℤ_fintype l u⟩ lemma Ioo_ℤ_finite (l u : ℤ) : set.finite (Ioo l u) := ⟨set.Ioo_ℤ_fintype l u⟩ lemma Icc_ℤ_finite (l u : ℤ) : set.finite (Icc l u) := ⟨set.Icc_ℤ_fintype l u⟩ lemma Ioc_ℤ_finite (l u : ℤ) : set.finite (Ioc l u) := ⟨set.Ioc_ℤ_fintype l u⟩ @[simp] lemma Ico_ℤ_card (l u : ℤ) : fintype.card (Ico l u) = (u - l).to_nat := calc fintype.card (Ico l u) = (finset.Ico_ℤ l u).card : fintype.card_of_finset _ _ ... = (u - l).to_nat : finset.Ico_ℤ.card l u @[simp] lemma Ioo_ℤ_card (l u : ℤ) : fintype.card (Ioo l u) = (u - l - 1).to_nat := calc fintype.card (Ioo l u) = (finset.Ico_ℤ (l+1) u).card : fintype.card_of_finset _ _ ... = (u - (l+1)).to_nat : finset.Ico_ℤ.card (l+1) u ... = (u - l - 1).to_nat : congr_arg _ $ sub_add_eq_sub_sub u l 1 @[simp] lemma Icc_ℤ_card (l u : ℤ) : fintype.card (Icc l u) = (u + 1 - l).to_nat := calc fintype.card (Icc l u) = (finset.Ico_ℤ l (u+1)).card : fintype.card_of_finset _ _ ... = (u + 1 - l).to_nat : finset.Ico_ℤ.card l (u+1) @[simp] lemma Ioc_ℤ_card (l u : ℤ) : fintype.card (Ioc l u) = (u - l).to_nat := calc fintype.card (Ioc l u) = (finset.Ico_ℤ (l+1) (u+1)).card : fintype.card_of_finset _ _ ... = ((u+1) - (l+1)).to_nat : finset.Ico_ℤ.card (l+1) (u+1) ... = (u - l).to_nat : congr_arg _ $ add_sub_add_right_eq_sub u l 1 -- TODO other useful instances: fin n, zmod? end set
38aaa938306a67c32942494d2a3d48aa5923d1b1
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/category/Semigroup/basic.lean
d198ca8535ebd346b04667886688b978e5907ee6
[ "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
7,106
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import algebra.pempty_instances import category_theory.concrete_category.bundled_hom import category_theory.reflects_isomorphisms /-! # Category instances for has_mul, has_add, semigroup and add_semigroup We introduce the bundled categories: * `Magma` * `AddMagma` * `Semigroup` * `AddSemigroup` along with the relevant forgetful functors between them. This closely follows `algebra.category.Mon.basic`. ## TODO * Limits in these categories * free/forgetful adjunctions -/ universes u v open category_theory /-- The category of magmas and magma morphisms. -/ @[to_additive AddMagma] def Magma : Type (u+1) := bundled has_mul /-- The category of additive magmas and additive magma morphisms. -/ add_decl_doc AddMagma namespace Magma @[to_additive] instance bundled_hom : bundled_hom @mul_hom := ⟨@mul_hom.to_fun, @mul_hom.id, @mul_hom.comp, @mul_hom.coe_inj⟩ attribute [derive [large_category, concrete_category]] Magma attribute [to_additive] Magma.large_category Magma.concrete_category @[to_additive] instance : has_coe_to_sort Magma Type* := bundled.has_coe_to_sort /-- Construct a bundled `Magma` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [has_mul M] : Magma := bundled.of M /-- Construct a bundled `AddMagma` from the underlying type and typeclass. -/ add_decl_doc AddMagma.of /-- Typecheck a `mul_hom` as a morphism in `Magma`. -/ @[to_additive] def of_hom {X Y : Type u} [has_mul X] [has_mul Y] (f : mul_hom X Y) : of X ⟶ of Y := f /-- Typecheck a `add_hom` as a morphism in `AddMagma`. -/ add_decl_doc AddMagma.of_hom @[to_additive] instance : inhabited Magma := ⟨Magma.of pempty⟩ @[to_additive] instance (M : Magma) : has_mul M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [has_mul R] : (Magma.of R : Type u) = R := rfl end Magma /-- The category of semigroups and semigroup morphisms. -/ @[to_additive AddSemigroup] def Semigroup : Type (u+1) := bundled semigroup /-- The category of additive semigroups and semigroup morphisms. -/ add_decl_doc AddSemigroup namespace Semigroup @[to_additive] instance : bundled_hom.parent_projection semigroup.to_has_mul := ⟨⟩ attribute [derive [large_category, concrete_category]] Semigroup attribute [to_additive] Semigroup.large_category Semigroup.concrete_category @[to_additive] instance : has_coe_to_sort Semigroup Type* := bundled.has_coe_to_sort /-- Construct a bundled `Semigroup` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [semigroup M] : Semigroup := bundled.of M /-- Construct a bundled `AddSemigroup` from the underlying type and typeclass. -/ add_decl_doc AddSemigroup.of /-- Typecheck a `mul_hom` as a morphism in `Semigroup`. -/ @[to_additive] def of_hom {X Y : Type u} [semigroup X] [semigroup Y] (f : mul_hom X Y) : of X ⟶ of Y := f /-- Typecheck a `add_hom` as a morphism in `AddSemigroup`. -/ add_decl_doc AddSemigroup.of_hom @[to_additive] instance : inhabited Semigroup := ⟨Semigroup.of pempty⟩ @[to_additive] instance (M : Semigroup) : semigroup M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [semigroup R] : (Semigroup.of R : Type u) = R := rfl @[to_additive has_forget_to_AddMagma] instance has_forget_to_Magma : has_forget₂ Semigroup Magma := bundled_hom.forget₂ _ _ end Semigroup variables {X Y : Type u} section variables [has_mul X] [has_mul Y] /-- Build an isomorphism in the category `Magma` from a `mul_equiv` between `has_mul`s. -/ @[to_additive add_equiv.to_AddMagma_iso "Build an isomorphism in the category `AddMagma` from an `add_equiv` between `has_add`s.", simps] def mul_equiv.to_Magma_iso (e : X ≃* Y) : Magma.of X ≅ Magma.of Y := { hom := e.to_mul_hom, inv := e.symm.to_mul_hom } end section variables [semigroup X] [semigroup Y] /-- Build an isomorphism in the category `Semigroup` from a `mul_equiv` between `semigroup`s. -/ @[to_additive add_equiv.to_AddSemigroup_iso "Build an isomorphism in the category `AddSemigroup` from an `add_equiv` between `add_semigroup`s.", simps] def mul_equiv.to_Semigroup_iso (e : X ≃* Y) : Semigroup.of X ≅ Semigroup.of Y := { hom := e.to_mul_hom, inv := e.symm.to_mul_hom } end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Magma`. -/ @[to_additive AddMagma_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMagma`."] def Magma_iso_to_mul_equiv {X Y : Magma} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := begin rw function.left_inverse, simp end, right_inv := begin rw function.right_inverse, rw function.left_inverse, simp end, map_mul' := by simp } /-- Build a `mul_equiv` from an isomorphism in the category `Semigroup`. -/ @[to_additive "Build an `add_equiv` from an isomorphism in the category `AddSemigroup`."] def Semigroup_iso_to_mul_equiv {X Y : Semigroup} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := begin rw function.left_inverse, simp end, right_inv := begin rw function.right_inverse, rw function.left_inverse, simp end, map_mul' := by simp } end category_theory.iso /-- multiplicative equivalences between `has_mul`s are the same as (isomorphic to) isomorphisms in `Magma` -/ @[to_additive add_equiv_iso_AddMagma_iso "additive equivalences between `has_add`s are the same as (isomorphic to) isomorphisms in `AddMagma`"] def mul_equiv_iso_Magma_iso {X Y : Type u} [has_mul X] [has_mul Y] : (X ≃* Y) ≅ (Magma.of X ≅ Magma.of Y) := { hom := λ e, e.to_Magma_iso, inv := λ i, i.Magma_iso_to_mul_equiv } /-- multiplicative equivalences between `semigroup`s are the same as (isomorphic to) isomorphisms in `Semigroup` -/ @[to_additive add_equiv_iso_AddSemigroup_iso "additive equivalences between `add_semigroup`s are the same as (isomorphic to) isomorphisms in `AddSemigroup`"] def mul_equiv_iso_Semigroup_iso {X Y : Type u} [semigroup X] [semigroup Y] : (X ≃* Y) ≅ (Semigroup.of X ≅ Semigroup.of Y) := { hom := λ e, e.to_Semigroup_iso, inv := λ i, i.Semigroup_iso_to_mul_equiv } @[to_additive] instance Magma.forget_reflects_isos : reflects_isomorphisms (forget Magma.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Magma).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_Magma_iso).1⟩, end } @[to_additive] instance Semigroup.forget_reflects_isos : reflects_isomorphisms (forget Semigroup.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Semigroup).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_Semigroup_iso).1⟩, end } /-! Once we've shown that the forgetful functors to type reflect isomorphisms, we automatically obtain that the `forget₂` functors between our concrete categories reflect isomorphisms. -/ example : reflects_isomorphisms (forget₂ Semigroup Magma) := by apply_instance
c3af7fba3cda0694fac68761d0ad12f86d73fb3f
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/hhg/group.lean
856d7d06f1feb6b90639820a368eb6780f273760
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
10,411
lean
open tactic.interactive inductive ℤ₂ : Type | zero | one def ℤ₂.add : ℤ₂ → ℤ₂ → ℤ₂ | ℤ₂.zero x := x | x ℤ₂.zero := x | ℤ₂.one ℤ₂.one := ℤ₂.zero -- figure out what you need to provide to define an add_group instance #print add_group lemma ℤ₂.add_assoc : ∀ (x y z : ℤ₂), ℤ₂.add (ℤ₂.add x y) z = ℤ₂.add x (ℤ₂.add y z) := begin intros x y z, cases x; cases y; cases z; unfold ℤ₂.add end lemma ℤ₂.zero_add : ∀ (x : ℤ₂), ℤ₂.add ℤ₂.zero x = x := begin intros x, cases x; unfold ℤ₂.add end lemma ℤ₂.add_zero : ∀ (x : ℤ₂), ℤ₂.add x ℤ₂.zero = x := begin intros x, cases x; unfold ℤ₂.add end def ℤ₂.neg : ℤ₂ → ℤ₂ | x := x lemma ℤ₂.add_left_neg : ∀ (x : ℤ₂), ℤ₂.add (ℤ₂.neg x) x = ℤ₂.zero := begin intros x, unfold ℤ₂.neg, cases x; unfold ℤ₂.add end @[instance] def ℤ₂.add_group : add_group ℤ₂ := { add := ℤ₂.add , add_assoc := ℤ₂.add_assoc , zero := ℤ₂.zero , zero_add := ℤ₂.zero_add , add_zero := ℤ₂.add_zero , neg := ℤ₂.neg , add_left_neg := ℤ₂.add_left_neg } lemma ℤ₂.L₁ : ∀ (x y z : ℤ₂), (x + y) + z = x + (y + z) := begin intros x y z, apply add_assoc end lemma ℤ₂.L₂ : ∀ (x : ℤ₂), 0 + x = x := begin intros x, apply zero_add end lemma ℤ₂.L₃ : ∀ (x : ℤ₂), x + 0 = x := begin intros x, apply add_zero end lemma ℤ₂.L₄ : ∀ (x : ℤ₂), (-x) + x = 0 := begin intros x, apply add_left_neg end def ℤ₂.mul : ℤ₂ → ℤ₂ → ℤ₂ | ℤ₂.one x := x | x ℤ₂.one := x | ℤ₂.zero ℤ₂.zero := ℤ₂.zero #print ring lemma ℤ₂.add_comm : ∀ (a b : ℤ₂), a + b = b + a := begin intros x y, cases x; cases y; refl end lemma ℤ₂.mul_assoc : ∀ (x y z : ℤ₂), ℤ₂.mul (ℤ₂.mul x y) z = ℤ₂.mul x (ℤ₂.mul y z) := begin intros x y z, cases x; cases y; cases z; refl end lemma ℤ₂.one_mul : ∀ (x : ℤ₂), ℤ₂.mul ℤ₂.one x = x := begin intros x, cases x; refl end lemma ℤ₂.mul_one : ∀ (x : ℤ₂), ℤ₂.mul x ℤ₂.one = x := begin intros x, cases x; refl end lemma ℤ₂.left_distrib : ∀ (x y z : ℤ₂), ℤ₂.mul x (y + z) = ℤ₂.mul x y + ℤ₂.mul x z := begin intros x y z, cases x; cases y; cases z; refl end lemma ℤ₂.right_distrib : ∀ (x y z : ℤ₂), ℤ₂.mul (x + y) z = ℤ₂.mul x z + ℤ₂.mul y z := begin intros x y z, cases x; cases y; cases z; refl end @[instance] def ℤ₂.ring : ring ℤ₂ := { add := ℤ₂.add , add_assoc := ℤ₂.add_assoc , zero := ℤ₂.zero , zero_add := ℤ₂.zero_add , add_zero := ℤ₂.add_zero , neg := ℤ₂.neg , add_left_neg := ℤ₂.add_left_neg , add_comm := ℤ₂.add_comm , mul := ℤ₂.mul , mul_assoc := ℤ₂.mul_assoc , one := ℤ₂.one , one_mul := ℤ₂.one_mul , mul_one := ℤ₂.mul_one , left_distrib := ℤ₂.left_distrib , right_distrib := ℤ₂.right_distrib } #print field def ℤ₂.inv : ℤ₂ → ℤ₂ := λ x, x lemma ℤ₂.zero_ne_one : ℤ₂.zero ≠ ℤ₂.one := begin intros H₁, cases H₁ end lemma ℤ₂.mul_inv_cancel : ∀ (x : ℤ₂), x ≠ 0 → x * ℤ₂.inv x = 1 := begin intros x H₁, cases x, { exfalso, apply H₁, refl }, { refl } end lemma ℤ₂.inv_mul_cancel : ∀ (x : ℤ₂), x ≠ 0 → ℤ₂.inv x * x = 1 := begin intros x H₁, cases x, { exfalso, apply H₁, refl }, { refl } end lemma ℤ₂.mul_comm : ∀ (x y : ℤ₂), x * y = y * x := begin intros x y, cases x; cases y; refl end @[instance] def ℤ₂.field : field ℤ₂ := { add := ℤ₂.add , add_assoc := ℤ₂.add_assoc , zero := ℤ₂.zero , zero_add := ℤ₂.zero_add , add_zero := ℤ₂.add_zero , neg := ℤ₂.neg , add_left_neg := ℤ₂.add_left_neg , add_comm := ℤ₂.add_comm , mul := ℤ₂.mul , mul_assoc := ℤ₂.mul_assoc , one := ℤ₂.one , one_mul := ℤ₂.one_mul , mul_one := ℤ₂.mul_one , left_distrib := ℤ₂.left_distrib , right_distrib := ℤ₂.right_distrib , inv := ℤ₂.inv , zero_ne_one := ℤ₂.zero_ne_one , mul_inv_cancel := ℤ₂.mul_inv_cancel , inv_mul_cancel := ℤ₂.inv_mul_cancel , mul_comm := ℤ₂.mul_comm } #reduce (1 : ℤ₂) * 0 / (0 - 1) #reduce (3 : ℤ₂) def ℤ₂.pow (x : ℤ₂) : ℕ → ℤ₂ | 0 := ℤ₂.one | (n + 1) := x * ℤ₂.pow n @[instance] def ℤ₂.has_pow : has_pow ℤ₂ ℕ := { pow := ℤ₂.pow } lemma ring_x_x : ∀ (x : ℤ₂), x + x = 2 * x := begin intros x, cases x; refl end lemma ring_xx : ∀ (x : ℤ₂), x*x = x^2 := begin intros x, cases x; refl end lemma ring_ex2 : ∀ (x y : ℤ₂), (x + y)^2 = x^2 + 2*x*y + y^2 := begin intros x y, calc (x + y)^2 = (x + y) * (x + y) : by rw ring_xx ... = x*(x + y) + y*(x + y) : by rw right_distrib ... = x*x + x*y + y*(x + y) : by rw left_distrib ... = x*x + x*y + (y*x + y*y) : by rw left_distrib ... = x*x + (x*y + (y*x + y*y)) : by rw add_assoc ... = x*x + (x*y + y*x + y*y) : by rw add_assoc ... = x*x + (x*y + x*y + y*y) : by rw (mul_comm y x) ... = x*x + (2*(x*y) + y*y) : by rw ring_x_x ... = x*x + (2*x*y + y*y) : by rw mul_assoc ... = x*x + 2*x*y + y*y : by rw add_assoc ... = x^2 + 2*x*y + y*y : by rw ring_xx ... = x^2 + 2*x*y + y^2 : by rw ring_xx end lemma ring_ex3 : ∀ (x y : ℤ₂), (x + y)^3 = x^3 + 3*x^2*y + 3*x*y^2 + y^3 := begin intros x y, calc (x + y)^3 = (x + y)*(x + y)^2 : by refl ... = (x + y)*(x^2 + 2*x*y + y^2) : by rw ring_ex2 ... = x*(x^2 + 2*x*y + y^2) + y*(x^2 + 2*x*y + y^2) : by rw right_distrib ... = (x*(x^2 + (2*x*y)) + x*y^2) + y*(x^2 + 2*x*y + y^2) : by rw left_distrib ... = (x*x^2 + x*(2*x*y) + x*y^2) + y*(x^2 + 2*x*y + y^2) : by rw left_distrib ... = (x^3 + x*(2*x*y) + x*y^2) + y*(x^2 + 2*x*y + y^2) : by refl ... = (x^3 + x*(2*x)*y + x*y^2) + y*(x^2 + 2*x*y + y^2) : by rw (mul_assoc x (2*x) y) ... = (x^3 + x*2*x*y + x*y^2) + y*(x^2 + 2*x*y + y^2) : by rw (mul_assoc x 2 x) ... = (x^3 + 2*x*x*y + x*y^2) + y*(x^2 + 2*x*y + y^2) : by rw (mul_comm x 2) ... = (x^3 + 2*(x*x)*y + x*y^2) + y*(x^2 + 2*x*y + y^2) : by rw (mul_assoc 2 x x) ... = (x^3 + 2*x^2*y + x*y^2) + y*(x^2 + 2*x*y + y^2) : by rw ring_xx ... = (x^3 + 2*x^2*y + x*y^2) + (y*(x^2 + 2*x*y) + y*y^2) : by rw left_distrib ... = (x^3 + 2*x^2*y + x*y^2) + (y*(x^2 + 2*x*y) + y^3) : by refl ... = (x^3 + 2*x^2*y + x*y^2) + (y*x^2 + y*(2*x*y) + y^3) : by rw left_distrib ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + y*(2*x*y) + y^3) : by rw (mul_comm y (x^2)) ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + y*(2*x)*y + y^3) : by rw (mul_assoc y (2*x) y) ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + y*2*x*y + y^3) : by rw (mul_assoc y 2 x) ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + 2*y*x*y + y^3) : by rw (mul_comm y 2) ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + 2*(y*x)*y + y^3) : by rw (mul_assoc 2 y x) ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + 2*(x*y)*y + y^3) : by rw (mul_comm y x) ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + 2*(x*y*y) + y^3) : by rw (mul_assoc 2 (x*y) y) ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + 2*(x*(y*y)) + y^3) : by rw (mul_assoc x y y) ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + 2*(x*y^2) + y^3) : by rw ring_xx ... = (x^3 + 2*x^2*y + x*y^2) + (x^2*y + 2*x*y^2 + y^3) : by rw (mul_assoc 2 x (y^2)) ... = x^3 + 2*x^2*y + x*y^2 + (x^2*y + 2*x*y^2) + y^3 : by rw (add_assoc (x^3 + 2*x^2*y + x*y^2)) ... = x^3 + 2*x^2*y + x*y^2 + x^2*y + 2*x*y^2 + y^3 : by rw (add_assoc (x^3 + 2*x^2*y + x*y^2) (x^2*y)) ... = x^3 + 2*x^2*y + (x*y^2 + x^2*y) + 2*x*y^2 + y^3 : by rw (add_assoc (x^3 + 2*x^2*y) (x*y^2) (x^2*y)) ... = x^3 + 2*x^2*y + (x^2*y + x*y^2) + 2*x*y^2 + y^3 : by rw (add_comm (x*y^2) (x^2*y)) ... = x^3 + 2*x^2*y + x^2*y + x*y^2 + 2*x*y^2 + y^3 : by rw (add_assoc (x^3 + 2*x^2*y) (x^2*y) (x*y^2)) ... = x^3 + (2*x^2*y + x^2*y) + x*y^2 + 2*x*y^2 + y^3 : by rw (add_assoc (x^3) (2*x^2*y) (x^2*y)) ... = x^3 + (2*x^2*y + 1*x^2*y) + x*y^2 + 2*x*y^2 + y^3 : by rw one_mul ... = x^3 + (2*(x^2*y) + 1*x^2*y) + x*y^2 + 2*x*y^2 + y^3 : by rw (mul_assoc 2 (x^2) y) ... = x^3 + (2*(x^2*y) + 1*(x^2*y)) + x*y^2 + 2*x*y^2 + y^3 : by rw (mul_assoc 1 (x^2) y) ... = x^3 + (2 + 1)*(x^2*y) + x*y^2 + 2*x*y^2 + y^3 : by rw right_distrib ... = x^3 + (2 + 1)*x^2*y + x*y^2 + 2*x*y^2 + y^3 : by rw (mul_assoc (2 + 1) (x^2) y) ... = x^3 + 3*x^2*y + x*y^2 + 2*x*y^2 + y^3 : by refl ... = x^3 + 3*x^2*y + 1*(x*y^2) + 2*x*y^2 + y^3 : by rw one_mul ... = x^3 + 3*x^2*y + 1*(x*y^2) + 2*(x*y^2) + y^3 : by rw (mul_assoc 2 x (y^2)) ... = x^3 + 3*x^2*y + (1*(x*y^2) + 2*(x*y^2)) + y^3 : by rw (add_assoc (x^3 + 3*x^2*y) (1*(x*y^2)) (2*(x*y^2))) ... = x^3 + 3*x^2*y + (1 + 2)*(x*y^2) + y^3 : by rw right_distrib ... = x^3 + 3*x^2*y + 3*(x*y^2) + y^3 : by refl ... = x^3 + 3*x^2*y + 3*x*y^2 + y^3 : by rw (mul_assoc 3 x (y^2)) end lemma neg_mul_neg_nat : ∀ (n : ℕ) (z : ℤ), (- z) * (- n) = z * n := sorry lemma norm_cast_ex1 : ∀ (n m : ℕ), (m : ℤ) = (n : ℤ) → m = n := begin intros n m H₁, norm_cast at H₁, -- where is this defined ? end
e1e922836eb67378afe2a76eefc7c08d62807f1d
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/category_theory/opposites.lean
4d4d2233eeea8a80b3c02ca4c69279076db857b7
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,531
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.types import category_theory.equivalence import data.opposite universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory open opposite variables {C : Type u₁} section has_hom variables [has_hom.{v₁} C] /-- The hom types of the opposite of a category (or graph). As with the objects, we'll make this irreducible below. Use `f.op` and `f.unop` to convert between morphisms of C and morphisms of Cᵒᵖ. -/ instance has_hom.opposite : has_hom Cᵒᵖ := { hom := λ X Y, unop Y ⟶ unop X } /-- The opposite of a morphism in `C`. -/ def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f /-- Given a morphism in `Cᵒᵖ`, we can take the "unopposite" back in `C`. -/ def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f attribute [irreducible] has_hom.opposite lemma has_hom.hom.op_inj {X Y : C} : function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) := λ _ _ H, congr_arg has_hom.hom.unop H lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} : function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) := λ _ _ H, congr_arg has_hom.hom.op H @[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl @[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl end has_hom variables [category.{v₁} C] /-- The opposite category. See https://stacks.math.columbia.edu/tag/001M. -/ instance category.opposite : category.{v₁} Cᵒᵖ := { comp := λ _ _ _ f g, (g.unop ≫ f.unop).op, id := λ X, (𝟙 (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl @[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl @[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl section variables (C) /-- The functor from the double-opposite of a category to the underlying category. -/ @[simps] def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, unop (unop X), map := λ X Y f, f.unop.unop } /-- The functor from a category to its double-opposite. -/ @[simps] def unop_unop : C ⥤ Cᵒᵖᵒᵖ := { obj := λ X, op (op X), map := λ X Y f, f.op.op } /-- The double opposite category is equivalent to the original. -/ @[simps] def op_op_equivalence : Cᵒᵖᵒᵖ ≌ C := { functor := op_op C, inverse := unop_unop C, unit_iso := iso.refl (𝟭 Cᵒᵖᵒᵖ), counit_iso := iso.refl (unop_unop C ⋙ op_op C) } end /-- If `f.op` is an isomorphism `f` must be too. (This cannot be an instance as it would immediately loop!) -/ lemma is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f := ⟨⟨(inv (f.op)).unop, ⟨has_hom.hom.op_inj (by simp), has_hom.hom.op_inj (by simp)⟩⟩⟩ namespace functor section variables {D : Type u₂} [category.{v₂} D] variables {C D} /-- The opposite of a functor, i.e. considering a functor `F : C ⥤ D` as a functor `Cᵒᵖ ⥤ Dᵒᵖ`. In informal mathematics no distinction is made between these. -/ @[simps] protected def op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (unop X)), map := λ X Y f, (F.map f.unop).op } /-- Given a functor `F : Cᵒᵖ ⥤ Dᵒᵖ` we can take the "unopposite" functor `F : C ⥤ D`. In informal mathematics no distinction is made between these. -/ @[simps] protected def unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, unop (F.obj (op X)), map := λ X Y f, (F.map f.op).unop } /-- The isomorphism between `F.op.unop` and `F`. -/ def op_unop_iso (F : C ⥤ D) : F.op.unop ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) /-- The isomorphism between `F.unop.op` and `F`. -/ def unop_op_iso (F : Cᵒᵖ ⥤ Dᵒᵖ) : F.unop.op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) variables (C D) /-- Taking the opposite of a functor is functorial. -/ @[simps] def op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, (unop F).op, map := λ F G α, { app := λ X, (α.unop.app (unop X)).op, naturality' := λ X Y f, has_hom.hom.unop_inj (α.unop.naturality f.unop).symm } } /-- Take the "unopposite" of a functor is functorial. -/ @[simps] def op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F, op F.unop, map := λ F G α, has_hom.hom.op { app := λ X, (α.app (op X)).unop, naturality' := λ X Y f, has_hom.hom.op_inj $ (α.naturality f.op).symm } } -- TODO show these form an equivalence variables {C D} /-- Another variant of the opposite of functor, turning a functor `C ⥤ Dᵒᵖ` into a functor `Cᵒᵖ ⥤ D`. In informal mathematics no distinction is made. -/ @[simps] protected def left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D := { obj := λ X, unop (F.obj (unop X)), map := λ X Y f, (F.map f.unop).unop } /-- Another variant of the opposite of functor, turning a functor `Cᵒᵖ ⥤ D` into a functor `C ⥤ Dᵒᵖ`. In informal mathematics no distinction is made. -/ @[simps] protected def right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (op X)), map := λ X Y f, (F.map f.op).op } -- TODO show these form an equivalence instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, (F.preimage f.unop).op } instance {F : C ⥤ D} [faithful F] : faithful F.op := { map_injective' := λ X Y f g h, has_hom.hom.unop_inj $ by simpa using map_injective F (has_hom.hom.op_inj h) } /-- If F is faithful then the right_op of F is also faithful. -/ instance right_op_faithful {F : Cᵒᵖ ⥤ D} [faithful F] : faithful F.right_op := { map_injective' := λ X Y f g h, has_hom.hom.op_inj (map_injective F (has_hom.hom.op_inj h)) } /-- If F is faithful then the left_op of F is also faithful. -/ instance left_op_faithful {F : C ⥤ Dᵒᵖ} [faithful F] : faithful F.left_op := { map_injective' := λ X Y f g h, has_hom.hom.unop_inj (map_injective F (has_hom.hom.unop_inj h)) } end end functor namespace nat_trans variables {D : Type u₂} [category.{v₂} D] section variables {F G : C ⥤ D} local attribute [semireducible] has_hom.opposite /-- The opposite of a natural transformation. -/ @[simps] protected def op (α : F ⟶ G) : G.op ⟶ F.op := { app := λ X, (α.app (unop X)).op, naturality' := begin tidy, erw α.naturality, refl, end } @[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl /-- The "unopposite" of a natural transformation. -/ @[simps] protected def unop {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) : G.unop ⟶ F.unop := { app := λ X, (α.app (op X)).unop, naturality' := begin tidy, erw α.naturality, refl, end } @[simp] lemma unop_id (F : Cᵒᵖ ⥤ Dᵒᵖ) : nat_trans.unop (𝟙 F) = 𝟙 (F.unop) := rfl /-- Given a natural transformation `α : F.op ⟶ G.op`, we can take the "unopposite" of each component obtaining a natural transformation `G ⟶ F`. -/ @[simps] protected def remove_op (α : F.op ⟶ G.op) : G ⟶ F := { app := λ X, (α.app (op X)).unop, naturality' := begin intros X Y f, have := congr_arg has_hom.hom.op (α.naturality f.op), dsimp at this, erw this, refl, end } @[simp] lemma remove_op_id (F : C ⥤ D) : nat_trans.remove_op (𝟙 F.op) = 𝟙 F := rfl end section variables {F G : C ⥤ Dᵒᵖ} local attribute [semireducible] has_hom.opposite /-- Given a natural transformation `α : F ⟶ G`, for `F G : C ⥤ Dᵒᵖ`, taking `unop` of each component gives a natural transformation `G.left_op ⟶ F.left_op`. -/ @[simps] protected def left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op := { app := λ X, (α.app (unop X)).unop, naturality' := begin tidy, erw α.naturality, refl, end } /-- Given a natural transformation `α : F.left_op ⟶ G.left_op`, for `F G : C ⥤ Dᵒᵖ`, taking `op` of each component gives a natural transformation `G ⟶ F`. -/ @[simps] protected def remove_left_op (α : F.left_op ⟶ G.left_op) : G ⟶ F := { app := λ X, (α.app (op X)).op, naturality' := begin intros X Y f, have := congr_arg has_hom.hom.op (α.naturality f.op), dsimp at this, erw this end } end end nat_trans namespace iso variables {X Y : C} /-- The opposite isomorphism. -/ @[simps] protected def op (α : X ≅ Y) : op Y ≅ op X := { hom := α.hom.op, inv := α.inv.op, hom_inv_id' := has_hom.hom.unop_inj α.inv_hom_id, inv_hom_id' := has_hom.hom.unop_inj α.hom_inv_id } end iso namespace nat_iso variables {D : Type u₂} [category.{v₂} D] variables {F G : C ⥤ D} /-- The natural isomorphism between opposite functors `G.op ≅ F.op` induced by a natural isomorphism between the original functors `F ≅ G`. -/ @[simps] protected def op (α : F ≅ G) : G.op ≅ F.op := { hom := nat_trans.op α.hom, inv := nat_trans.op α.inv, hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw α.hom_inv_id_app, refl, end } /-- The natural isomorphism between functors `G ≅ F` induced by a natural isomorphism between the opposite functors `F.op ≅ G.op`. -/ @[simps] protected def remove_op (α : F.op ≅ G.op) : G ≅ F := { hom := nat_trans.remove_op α.hom, inv := nat_trans.remove_op α.inv, hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end } /-- The natural isomorphism between functors `G.unop ≅ F.unop` induced by a natural isomorphism between the original functors `F ≅ G`. -/ @[simps] protected def unop {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ≅ G) : G.unop ≅ F.unop := { hom := nat_trans.unop α.hom, inv := nat_trans.unop α.inv, hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end } end nat_iso namespace equivalence variables {D : Type u₂} [category.{v₂} D] /-- An equivalence between categories gives an equivalence between the opposite categories. -/ @[simps] def op (e : C ≌ D) : Cᵒᵖ ≌ Dᵒᵖ := { functor := e.functor.op, inverse := e.inverse.op, unit_iso := (nat_iso.op e.unit_iso).symm, counit_iso := (nat_iso.op e.counit_iso).symm, functor_unit_iso_comp' := λ X, by { apply has_hom.hom.unop_inj, dsimp, simp, }, } /-- An equivalence between opposite categories gives an equivalence between the original categories. -/ @[simps] def unop (e : Cᵒᵖ ≌ Dᵒᵖ) : C ≌ D := { functor := e.functor.unop, inverse := e.inverse.unop, unit_iso := (nat_iso.unop e.unit_iso).symm, counit_iso := (nat_iso.unop e.counit_iso).symm, functor_unit_iso_comp' := λ X, by { apply has_hom.hom.op_inj, dsimp, simp, }, } end equivalence /-- The equivalence between arrows of the form `A ⟶ B` and `B.unop ⟶ A.unop`. Useful for building adjunctions. Note that this (definitionally) gives variants ``` def op_equiv' (A : C) (B : Cᵒᵖ) : (opposite.op A ⟶ B) ≃ (B.unop ⟶ A) := op_equiv _ _ def op_equiv'' (A : Cᵒᵖ) (B : C) : (A ⟶ opposite.op B) ≃ (B ⟶ A.unop) := op_equiv _ _ def op_equiv''' (A B : C) : (opposite.op A ⟶ opposite.op B) ≃ (B ⟶ A) := op_equiv _ _ ``` -/ @[simps] def op_equiv (A B : Cᵒᵖ) : (A ⟶ B) ≃ (B.unop ⟶ A.unop) := { to_fun := λ f, f.unop, inv_fun := λ g, g.op, left_inv := λ _, rfl, right_inv := λ _, rfl } instance subsingleton_of_unop (A B : Cᵒᵖ) [subsingleton (unop B ⟶ unop A)] : subsingleton (A ⟶ B) := (op_equiv A B).subsingleton instance decidable_eq_of_unop (A B : Cᵒᵖ) [decidable_eq (unop B ⟶ unop A)] : decidable_eq (A ⟶ B) := (op_equiv A B).decidable_eq universes v variables {α : Type v} [preorder α] /-- Construct a morphism in the opposite of a preorder category from an inequality. -/ def op_hom_of_le {U V : αᵒᵖ} (h : unop V ≤ unop U) : U ⟶ V := has_hom.hom.op (hom_of_le h) lemma le_of_op_hom {U V : αᵒᵖ} (h : U ⟶ V) : unop V ≤ unop U := le_of_hom (h.unop) end category_theory
2acdb86b29e60925694d36eb5e3b23ff0ff0d25c
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/topology/uniform_space/separation.lean
ba549672ca7406a9a93026def2d9e8943fa08282
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,659
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot -/ import topology.uniform_space.basic import tactic.apply_fun import data.set.pairwise /-! # Hausdorff properties of uniform spaces. Separation quotient. This file studies uniform spaces whose underlying topological spaces are separated (also known as Hausdorff or T₂). This turns out to be equivalent to asking that the intersection of all entourages is the diagonal only. This condition actually implies the stronger separation property that the space is regular (T₃), hence those conditions are equivalent for topologies coming from a uniform structure. More generally, the intersection `𝓢 X` of all entourages of `X`, which has type `set (X × X)` is an equivalence relation on `X`. Points which are equivalent under the relation are basically undistinguishable from the point of view of the uniform structure. For instance any uniformly continuous function will send equivalent points to the same value. The quotient `separation_quotient X` of `X` by `𝓢 X` has a natural uniform structure which is separated, and satisfies a universal property: every uniformly continuous function from `X` to a separated uniform space uniquely factors through `separation_quotient X`. As usual, this allows to turn `separation_quotient` into a functor (but we don't use the category theory library in this file). These notions admit relative versions, one can ask that `s : set X` is separated, this is equivalent to asking that the uniform structure induced on `s` is separated. ## Main definitions * `separation_relation X : set (X × X)`: the separation relation * `separated_space X`: a predicate class asserting that `X` is separated * `is_separated s`: a predicate asserting that `s : set X` is separated * `separation_quotient X`: the maximal separated quotient of `X`. * `separation_quotient.lift f`: factors a map `f : X → Y` through the separation quotient of `X`. * `separation_quotient.map f`: turns a map `f : X → Y` into a map between the separation quotients of `X` and `Y`. ## Main results * `separated_iff_t2`: the equivalence between being separated and being Hausdorff for uniform spaces. * `separation_quotient.uniform_continuous_lift`: factoring a uniformly continuous map through the separation quotient gives a uniformly continuous map. * `separation_quotient.uniform_continuous_map`: maps induced between separation quotients are uniformly continuous. ## Notations Localized in `uniformity`, we have the notation `𝓢 X` for the separation relation on a uniform space `X`, ## Implementation notes The separation setoid `separation_setoid` is not declared as a global instance. It is made a local instance while building the theory of `separation_quotient`. The factored map `separation_quotient.lift f` is defined without imposing any condition on `f`, but returns junk if `f` is not uniformly continuous (constant junk hence it is always uniformly continuous). -/ open filter topological_space set classical function uniform_space open_locale classical topological_space uniformity filter noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] /-! ### Separated uniform spaces -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets localized "notation `𝓢` := separation_rel" in uniformity lemma separated_equiv : equivalence (λx y, (x, y) ∈ 𝓢 α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ 𝓢 α) (hyz : (y, z) ∈ 𝓢 α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ /-- A uniform space is separated if its separation relation is trivial (each point is related only to itself). -/ class separated_space (α : Type u) [uniform_space α] : Prop := (out : 𝓢 α = id_rel) theorem separated_space_iff {α : Type u} [uniform_space α] : separated_space α ↔ 𝓢 α = id_rel := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem separated_def {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated_space_iff, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [not_forall] lemma eq_of_uniformity {α : Type*} [uniform_space α] [separated_space α] {x y : α} (h : ∀ {V}, V ∈ 𝓤 α → (x, y) ∈ V) : x = y := separated_def.mp ‹separated_space α› x y (λ _, h) lemma eq_of_uniformity_basis {α : Type*} [uniform_space α] [separated_space α] {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (hs : (𝓤 α).has_basis p s) {x y : α} (h : ∀ {i}, p i → (x, y) ∈ s i) : x = y := eq_of_uniformity (λ V V_in, let ⟨i, hi, H⟩ := hs.mem_iff.mp V_in in H (h hi)) lemma eq_of_forall_symmetric {α : Type*} [uniform_space α] [separated_space α] {x y : α} (h : ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (x, y) ∈ V) : x = y := eq_of_uniformity_basis has_basis_symmetric (by simpa [and_imp] using λ _, h) lemma id_rel_sub_separation_relation (α : Type*) [uniform_space α] : id_rel ⊆ 𝓢 α := begin unfold separation_rel, rw id_rel_subset, intros x, suffices : ∀ t ∈ 𝓤 α, (x, x) ∈ t, by simpa only [refl_mem_uniformity], exact λ t, refl_mem_uniformity, end lemma separation_rel_comap {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓢 α = (prod.map f f) ⁻¹' 𝓢 β := begin dsimp [separation_rel], simp_rw [uniformity_comap h, (filter.comap_has_basis (prod.map f f) (𝓤 β)).sInter_sets, ← preimage_Inter, sInter_eq_bInter], refl, end protected lemma filter.has_basis.separation_rel {ι : Sort*} {p : ι → Prop} {s : ι → set (α × α)} (h : has_basis (𝓤 α) p s) : 𝓢 α = ⋂ i (hi : p i), s i := by { unfold separation_rel, rw h.sInter_sets } lemma separation_rel_eq_inter_closure : 𝓢 α = ⋂₀ (closure '' (𝓤 α).sets) := by simp [uniformity_has_basis_closure.separation_rel] lemma is_closed_separation_rel : is_closed (𝓢 α) := begin rw separation_rel_eq_inter_closure, apply is_closed_sInter, rintros _ ⟨t, t_in, rfl⟩, exact is_closed_closure, end lemma separated_iff_t2 : separated_space α ↔ t2_space α := begin classical, split ; introI h, { rw [t2_iff_is_closed_diagonal, ← show 𝓢 α = diagonal α, from h.1], exact is_closed_separation_rel }, { rw separated_def', intros x y hxy, rcases t2_separation hxy with ⟨u, v, uo, vo, hx, hy, h⟩, rcases is_open_iff_ball_subset.1 uo x hx with ⟨r, hrU, hr⟩, exact ⟨r, hrU, λ H, disjoint_iff.2 h ⟨hr H, hy⟩⟩ } end @[priority 100] -- see Note [lower instance priority] instance separated_regular [separated_space α] : regular_space α := { t0 := by { haveI := separated_iff_t2.mp ‹_›, exact t1_space.t0_space.t0 }, regular := λs a hs ha, have sᶜ ∈ 𝓝 a, from is_open.mem_nhds hs.is_open_compl ha, have {p : α × α | p.1 = a → p.2 ∈ sᶜ} ∈ 𝓤 α, from mem_nhds_uniformity_iff_right.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ sᶜ, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ 𝓟 (closure e)ᶜ = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (𝓟 (closure e)ᶜ) (𝓟 (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨(closure e)ᶜ, is_closed_closure.is_open_compl, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..@t2_space.t1_space _ _ (separated_iff_t2.mp ‹_›) } lemma is_closed_of_spaced_out [separated_space α] {V₀ : set (α × α)} (V₀_in : V₀ ∈ 𝓤 α) {s : set α} (hs : pairwise_on s (λ x y, (x, y) ∉ V₀)) : is_closed s := begin rcases comp_symm_mem_uniformity_sets V₀_in with ⟨V₁, V₁_in, V₁_symm, h_comp⟩, apply is_closed_of_closure_subset, intros x hx, rw mem_closure_iff_ball at hx, rcases hx V₁_in with ⟨y, hy, hy'⟩, suffices : x = y, by rwa this, apply eq_of_forall_symmetric, intros V V_in V_symm, rcases hx (inter_mem V₁_in V_in) with ⟨z, hz, hz'⟩, obtain rfl : z = y, { by_contra hzy, exact hs z hz' y hy' hzy (h_comp $ mem_comp_of_mem_ball V₁_symm (ball_inter_left x _ _ hz) hy) }, exact ball_inter_right x _ _ hz end lemma is_closed_range_of_spaced_out {ι} [separated_space α] {V₀ : set (α × α)} (V₀_in : V₀ ∈ 𝓤 α) {f : ι → α} (hf : pairwise (λ x y, (f x, f y) ∉ V₀)) : is_closed (range f) := is_closed_of_spaced_out V₀_in $ by { rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ h, exact hf x y (mt (congr_arg f) h) } /-! ### Separated sets -/ /-- A set `s` in a uniform space `α` is separated if the separation relation `𝓢 α` induces the trivial relation on `s`. -/ def is_separated (s : set α) : Prop := ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y lemma is_separated_def (s : set α) : is_separated s ↔ ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y := iff.rfl lemma is_separated_def' (s : set α) : is_separated s ↔ (s.prod s) ∩ 𝓢 α ⊆ id_rel := begin rw is_separated_def, split, { rintros h ⟨x, y⟩ ⟨⟨x_in, y_in⟩, H⟩, simp [h x y x_in y_in H] }, { intros h x y x_in y_in xy_in, rw ← mem_id_rel, exact h ⟨mk_mem_prod x_in y_in, xy_in⟩ } end lemma univ_separated_iff : is_separated (univ : set α) ↔ separated_space α := begin simp only [is_separated, mem_univ, true_implies_iff, separated_space_iff], split, { intro h, exact subset.antisymm (λ ⟨x, y⟩ xy_in, h x y xy_in) (id_rel_sub_separation_relation α), }, { intros h x y xy_in, rwa h at xy_in }, end lemma is_separated_of_separated_space [separated_space α] (s : set α) : is_separated s := begin rw [is_separated, separated_space.out], tauto, end lemma is_separated_iff_induced {s : set α} : is_separated s ↔ separated_space s := begin rw separated_space_iff, change _ ↔ 𝓢 {x // x ∈ s} = _, rw [separation_rel_comap rfl, is_separated_def'], split; intro h, { ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, suffices : (x, y) ∈ 𝓢 α ↔ x = y, by simpa only [mem_id_rel], refine ⟨λ H, h ⟨mk_mem_prod x_in y_in, H⟩, _⟩, rintro rfl, exact id_rel_sub_separation_relation α rfl }, { rintros ⟨x, y⟩ ⟨⟨x_in, y_in⟩, hS⟩, have A : (⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩ : ↥s × ↥s) ∈ prod.map (coe : s → α) (coe : s → α) ⁻¹' 𝓢 α, from hS, simpa using h.subset A } end lemma eq_of_uniformity_inf_nhds_of_is_separated {s : set α} (hs : is_separated s) : ∀ {x y : α}, x ∈ s → y ∈ s → cluster_pt (x, y) (𝓤 α) → x = y := begin intros x y x_in y_in H, have : ∀ V ∈ 𝓤 α, (x, y) ∈ closure V, { intros V V_in, rw mem_closure_iff_cluster_pt, have : 𝓤 α ≤ 𝓟 V, by rwa le_principal_iff, exact H.mono this }, apply hs x y x_in y_in, simpa [separation_rel_eq_inter_closure], end lemma eq_of_uniformity_inf_nhds [separated_space α] : ∀ {x y : α}, cluster_pt (x, y) (𝓤 α) → x = y := begin have : is_separated (univ : set α), { rw univ_separated_iff, assumption }, introv, simpa using eq_of_uniformity_inf_nhds_of_is_separated this, end /-! ### Separation quotient -/ namespace uniform_space /-- The separation relation of a uniform space seen as a setoid. -/ def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ 𝓢 α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ 𝓢 α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ 𝓢 α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ 𝓢 α → (c, d) ∈ 𝓢 β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated_space (quotient (separation_setoid α)) := ⟨set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated_space β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h /-- The maximal separated quotient of a uniform space `α`. -/ def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance [inhabited α] : inhabited (separation_quotient α) := by unfold separation_quotient; apply_instance /-- Factoring functions to a separated space through the separation quotient. -/ def lift [separated_space β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (nonempty.some ⟨x.out⟩) lemma lift_mk [separated_space β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated_space β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end /-- The separation quotient functor acting on functions. -/ def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, rfl⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated_space α] [separated_space β] : separated_space (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space
9e07b6c3efd6f28c4e66c32c5b79492082a2a004
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/simp_options.lean
dec3fbadd4363767701b904ca4c64b21fd0cdcd6
[ "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,310
lean
lemma simp_rule : forall (A B C : Type) (xs : list A) (f: A → B) (g: B → C), (list.map g $ (list.map f) xs) = list.map (g ∘ f) xs := begin intros, induction xs, simp [list.map], simp [list.map], end lemma simp_wildcard : forall (A B C : Type) (a b : list A) (a' b' : list C) (f : A → B) (g h : B → C), (list.map g $ list.map f a) = a' -> (list.map h $ list.map f b) = b' -> a' = list.map (g ∘ f) a ∧ b' = list.map (h ∘ f) b := begin intros A B C a b a' b' f g h a₁ a₂, simp [simp_rule] at *, rw [a₁, a₂], split; reflexivity end run_cmd mk_simp_attr `foo run_cmd mk_simp_attr `bar constants (f : ℕ → ℕ) (a b c : ℕ) (fab : f a = f b) (fbc : f b = f c) constants (p : ℕ → Prop) (pfa : p (f a)) (pfb : p (f b)) (pfc :p (f c)) attribute [simp, foo] fbc example : p (f a) := by simp [fab]; exact pfc example : p (f a) := by simp only [fab]; exact pfb example : p (f a) := by simp only [fab] with foo bar; exact pfc example (h : p (f a)) : p (f c) := by simp [fab] at h; assumption example (h : p (f a)) : p (f b) := by simp only [fab] at h; assumption example (h₁ : p (f a)) (h₂ : p (f a)) : p (f a) := begin simp only [fab] at h₁ ⊢, tactic.fail_if_success `[exact h₂], exact h₁ end
e8cc4deed51a14aac7e5cde20218cc2f6145e512
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world7/level7.lean
d3611cc4803c55cf85a64c327e4d9009392e01b2
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
841
lean
import game.world7.level6 -- hide /- # Advanced proposition world. ## Level 7: `or_symm` Proving that $(P\lor Q)\implies(Q\lor P)$ involves an element of danger. `intro h,` is the obvious start. But now, even though the goal is an `∨` statement, both `left` and `right` put you in a situation with an impossible goal. Fortunately, after `intro h,` you can do `cases h with p q`. Then something new happens: because there are two ways to prove `P ∨ Q` (namely, proving `P` or proving `Q`), the `cases` tactic turns one goal into two, one for each case. You should be able to make it home from there. -/ /- Lemma If $P$ and $Q$ are true/false statements, then $$P\lor Q\implies Q\lor P.$$ -/ lemma or_symm (P Q : Prop) : P ∨ Q → Q ∨ P := begin intro h, cases h with p q, right, exact p, left, exact q, end
84a427f1d60e64206d91e620241784151ed52b4a
4e0d7c3132ce31edc5829849735dd25db406b144
/lean/love02_backward_proofs_exercise_sheet.lean
4b8d706c498eb722f3245fb75ba41c33ab44a552
[]
no_license
gonzalgu/logical_verification_2020
a0013a6c22ea254e9f4d245f2948f0f4d44df4bb
724d0457dff2c3ff10f9ab2170388f4c5e958b75
refs/heads/master
1,660,886,374,533
1,589,859,641,000
1,589,859,641,000
256,069,971
0
0
null
1,586,997,430,000
1,586,997,429,000
null
UTF-8
Lean
false
false
4,474
lean
import .love02_backward_proofs_demo /-! # LoVe Exercise 2: Backward Proofs -/ set_option pp.beta true namespace LoVe /-! ## Question 1: Connectives and Quantifiers 1.1. Carry out the following proofs using basic tactics. Hint: Some strategies for carrying out such proofs are described at the end of Section 2.3 in the Hitchhiker's Guide. -/ lemma I (a : Prop) : a → a := begin intro ha, assumption, end lemma K (a b : Prop) : a → b → b := begin intros ha hb, assumption, end lemma C (a b c : Prop) : (a → b → c) → b → a → c := begin intros f hb ha, exact f ha hb, end lemma proj_1st (a : Prop) : a → a → a := begin intros ha₁ ha₂, exact ha₁, end /-! Please give a different answer than for `proj_1st`: -/ lemma proj_2nd (a : Prop) : a → a → a := begin intros ha₁ ha₂, exact ha₂, end lemma some_nonsense (a b c : Prop) : (a → b → c) → a → (a → c) → b → c := begin intros f ha g hb, exact f ha hb, end /-! 1.2. Prove the contraposition rule using basic tactics. -/ lemma contrapositive (a b : Prop) : (a → b) → ¬ b → ¬ a := begin intros f hnb hna, apply hnb, exact f hna, end /-! 1.3. Prove the distributivity of `∀` over `∧` using basic tactics. Hint: This exercise is tricky, especially the right-to-left direction. Some forward reasoning, like in the proof of `and_swap₂` in the lecture, might be necessary. -/ lemma forall_and {α : Type} (p q : α → Prop) : (∀x, p x ∧ q x) ↔ (∀x, p x) ∧ (∀x, q x) := begin split, intro h1, split, intro hx, apply (h1 hx).left, intro hx, apply (h1 hx).right, intro h2, intro hx, split, exact h2.left hx, exact h2.right hx, end /-! ## Question 2: Natural Numbers 2.1. Prove the following recursive equations on the first argument of the `mul` operator defined in lecture 1. -/ #check mul lemma mul_zero (n : ℕ) : mul 0 n = 0 := begin induction n, refl, simp [add,mul,n_ih], end lemma mul_succ (m n : ℕ) : mul (nat.succ m) n = add (mul m n) n := begin induction n with d hd, refl, simp [add,mul, hd], sorry, end /-! 2.2. Prove commutativity and associativity of multiplication using the `induction` tactic. Choose the induction variable carefully. -/ lemma mul_comm (m n : ℕ) : mul m n = mul n m := begin induction n with d hd, rw mul_zero, refl, simp [add,mul,hd], rw mul_succ, rw add_comm, end lemma mul_assoc (l m n : ℕ) : mul (mul l m) n = mul l (mul m n) := begin induction n with d hd, refl, simp [add,mul], rw mul_add, rw hd, end /-! 2.3. Prove the symmetric variant of `mul_add` using `rewrite`. To apply commutativity at a specific position, instantiate the rule by passing some arguments (e.g., `mul_comm _ l`). -/ lemma add_mul (l m n : ℕ) : mul (add l m) n = add (mul n l) (mul n m) := begin rw mul_comm, rw mul_add, end /-! ## Question 3 (**optional**): Intuitionistic Logic Intuitionistic logic is extended to classical logic by assuming a classical axiom. There are several possibilities for the choice of axiom. In this question, we are concerned with the logical equivalence of three different axioms: -/ def excluded_middle := ∀a : Prop, a ∨ ¬ a def peirce := ∀a b : Prop, ((a → b) → a) → a def double_negation := ∀a : Prop, (¬¬ a) → a /-! For the proofs below, please avoid using lemmas from Lean's `classical` namespace, because this would defeat the purpose of the exercise. 3.1 (**optional**). Prove the following implication using tactics. Hint: You will need `or.elim` and `false.elim`. You can use `simp [excluded_middle, peirce]` to unfold the definitions of `excluded_middle` and `peirce`. -/ lemma peirce_of_em : excluded_middle → peirce := begin simp [excluded_middle, peirce], intro em, intros a b, intro f, apply or.elim (em a), intro ha, assumption, intro hna, cc, end --#print peirce_of_em /-! 3.2 (**optional**). Prove the following implication using tactics. -/ lemma dn_of_peirce : peirce → double_negation := begin simp [peirce, double_negation], intro p, intro a, intro hnna, cc, end --#print dn_of_peirce /-! We leave the missing implication for the homework: -/ namespace sorry_lemmas lemma em_of_dn : double_negation → excluded_middle := begin simp [double_negation,excluded_middle], intro dn, intro a, have dna, from dn a, sorry, end end sorry_lemmas end LoVe
9eb5f0958004d2f1010bdc690669d857e803cdd3
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/compiler/closedtermcache.lean
e45850537501d375bb90ba8f7b5508266439e288
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
1,129
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.lean.environment namespace Lean abbrev ClosedTermCache := SMap Expr Name Expr.quickLt def mkClosedTermCacheExtension : IO (SimplePersistentEnvExtension (Expr × Name) ClosedTermCache) := registerSimplePersistentEnvExtension { name := `closedTermCache, addImportedFn := fun as => let cache : ClosedTermCache := mkStateFromImportedEntries (fun s (p : Expr × Name) => s.insert p.1 p.2) {} as; cache.switch, addEntryFn := fun s ⟨e, n⟩ => s.insert e n } @[init mkClosedTermCacheExtension] constant closedTermCacheExt : SimplePersistentEnvExtension (Expr × Name) ClosedTermCache := default _ @[export lean.cache_closed_term_name_core] def cacheClosedTermName (env : Environment) (e : Expr) (n : Name) : Environment := closedTermCacheExt.addEntry env (e, n) @[export lean.get_closed_term_name_core] def getClosedTermName (env : Environment) (e : Expr) : Option Name := (closedTermCacheExt.getState env).find e end Lean
a9dbb03631d5ce45988bb45a0f6054e30d067112
649957717d58c43b5d8d200da34bf374293fe739
/src/algebra/module.lean
e2fb4288329f7c978e4f7b7acb2ab314556b7d4b
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
14,907
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro Modules over a ring. -/ import algebra.ring algebra.big_operators group_theory.subgroup group_theory.group_action open function universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} -- /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ -- class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) -- infixr ` • `:73 := has_scalar.smul /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class semimodule (α : Type u) (β : Type v) [semiring α] [add_comm_monoid β] extends distrib_mul_action α β := (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (zero_smul : ∀x : β, (0 : α) • x = 0) section semimodule variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β) include R theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (α) @[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul α x lemma smul_smul : r • s • x = (r * s) • x := (mul_smul _ _ _).symm instance smul.is_add_monoid_hom {r : α} : is_add_monoid_hom (λ x : β, r • x) := { map_add := smul_add _, map_zero := smul_zero _ } lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : x = 0 := by rw [←one_smul α x, ←zero_eq_one, zero_smul] end semimodule /-- A module is a generalization of vector spaces to a scalar ring. It consists of a scalar ring `α` and an additive group of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β := by letI := M.to_has_scalar; exact { zero_smul := λ x, have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp, add_left_cancel this, smul_zero := λ r, have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp, add_left_cancel this, ..M } section module variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (α) theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp variables {α} @[simp] theorem smul_neg : r • (-x) = -(r • x) := by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by simp [smul_add]; rw smul_neg theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y := by simp [add_smul] end module instance semiring.to_semimodule [r : semiring α] : semimodule α α := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero, ..r } @[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl instance ring.to_module [r : ring α] : module α α := { ..semiring.to_semimodule } def is_ring_hom.to_module [ring α] [ring β] (f : α → β) [h : is_ring_hom f] : module α β := module.of_core { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [h.map_one, one_mul] } class is_linear_map (α : Type u) {β : Type v} {γ : Type w} [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] (f : β → γ) : Prop := (add : ∀x y, f (x + y) = f x + f y) (smul : ∀(c : α) x, f (c • x) = c • f x) structure linear_map (α : Type u) (β : Type v) (γ : Type w) [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] := (to_fun : β → γ) (add : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation β ` →ₗ[`:25 α:25 `] `:0 γ:0 := linear_map α β γ namespace linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] variables [module α β] [module α γ] [module α δ] variables (f g : β →ₗ[α] γ) include α instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩ theorem is_linear : is_linear_map α f := {..f} @[extensionality] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x := ⟨by rintro rfl; simp, ext⟩ @[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y @[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul α, map_smul f 0 0, zero_smul] instance : is_add_group_hom f := ⟨map_add f⟩ @[simp] lemma map_neg (x : β) : f (- x) = - f x := by rw [← neg_one_smul α, map_smul, neg_one_smul] @[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y := by simp [map_neg, map_add] @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} : f (t.sum g) = t.sum (λi, f (g i)) := (finset.sum_hom f).symm def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl def id : β →ₗ[α] β := ⟨id, by simp, by simp⟩ @[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl end linear_map namespace is_linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] include α def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H} @[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) : mk' f H x = f x := rfl lemma is_linear_map_neg : is_linear_map α (λ (z : β), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) lemma is_linear_map_smul {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (c : R) : is_linear_map R (λ (z : α), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp [smul_smul], ac_refl end --TODO: move lemma is_linear_map_smul' {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (a : α) : is_linear_map R (λ (c : R), c • a) := begin refine is_linear_map.mk (λ x y, add_smul x y a) _, intros _ _, simp [smul_smul] end variables {f : β → γ} (lin : is_linear_map α f) include β γ lin @[simp] lemma map_zero : f (0 : β) = (0 : γ) := by rw [← zero_smul α (0 : β), lin.smul, zero_smul] @[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := by rw [lin.add] @[simp] lemma map_neg (x : β) : f (- x) = - f x := by rw [← neg_one_smul α, lin.smul, neg_one_smul] @[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y := by simp [lin.map_neg, lin.map_add] end is_linear_map /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (α : Type u) (β : Type v) [ring α] [add_comm_group β] [module α β] : Type v := (carrier : set β) (zero : (0:β) ∈ carrier) (add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier) (smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier) namespace submodule variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩ instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩ @[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t := by cases s; cases t; congr' protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t := ⟨ext', λ h, h ▸ rfl⟩ @[extensionality] theorem ext {s t : submodule α β} (h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h @[simp] lemma zero_mem : (0 : β) ∈ p := p.zero lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂ lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy) lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by simpa using neg_mem p h, neg_mem p⟩ lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩ lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩ lemma sum_mem {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} : (∀c∈t, f c ∈ p) → t.sum f ∈ p := finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt}) instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ @[simp] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl @[simp] lemma coe_zero : ((0 : p) : β) = 0 := rfl @[simp] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl @[simp] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl instance : add_comm_group p := by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply set_coe.ext, simp } instance submodule_is_add_subgroup : is_add_subgroup (p : set β) := { zero_mem := p.zero, add_mem := p.add, neg_mem := λ _, p.neg_mem } lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := by simp instance : module α p := by refine {smul := (•), ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } protected def subtype : p →ₗ[α] β := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val (p : submodule α β) : ((submodule.subtype p) : p → β) = subtype.val := rfl end submodule @[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _ lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h end ideal /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ class vector_space (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] extends module α β instance discrete_field.to_vector_space {α : Type*} [discrete_field α] : vector_space α α := { .. ring.to_module } /-- Subspace of a vector space. Defined to equal `submodule`. -/ @[reducible] def subspace (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] [vector_space α β] : Type v := submodule α β instance subspace.vector_space {α β} {f : discrete_field α} [add_comm_group β] [vector_space α β] (p : subspace α β) : vector_space α p := {..submodule.module p} namespace submodule variables {R:discrete_field α} [add_comm_group β] [add_comm_group γ] variables [vector_space α β] [vector_space α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} include R set_option class.instance_max_depth 36 theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := ⟨λ h, by simpa [smul_smul, inv_mul_cancel r0] using p.smul_mem (r⁻¹) h, p.smul_mem r⟩ end submodule namespace add_comm_monoid open add_monoid variables {M : Type*} [add_comm_monoid M] instance : semimodule ℕ M := { smul := smul, smul_add := λ _ _ _, smul_add _ _ _, add_smul := λ _ _ _, add_smul _ _ _, mul_smul := λ _ _ _, mul_smul _ _ _, one_smul := one_smul, zero_smul := zero_smul, smul_zero := smul_zero } end add_comm_monoid namespace add_comm_group variables {M : Type*} [add_comm_group M] instance : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } end add_comm_group def is_add_group_hom.to_linear_map [add_comm_group α] [add_comm_group β] (f : α → β) [is_add_group_hom f] : α →ₗ[ℤ] β := { to_fun := f, add := is_add_group_hom.map_add f, smul := λ i x, int.induction_on i (by rw [zero_smul, zero_smul, is_add_group_hom.map_zero f]) (λ i ih, by rw [add_smul, add_smul, is_add_group_hom.map_add f, ih, one_smul, one_smul]) (λ i ih, by rw [sub_smul, sub_smul, is_add_group_hom.map_sub f, ih, one_smul, one_smul]) }
27d375b693162ad2b5b9531aa73d01f3ec0eb2ad
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/elabCmd.lean
dffe3312a4c6fe1e2874185c78b2b55f8304cef6
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
704
lean
import Lean open Lean open Lean.Elab open Lean.Elab.Term def getCtors (c : Name) : TermElabM (List Name) := do let env ← getEnv; (match env.find? c with | some (ConstantInfo.inductInfo val) => pure val.ctors | _ => pure []) def elabAnonCtor (args : Syntax) (τ : Expr) : TermElabM Expr := match τ.getAppFn with | Expr.const C _ _ => do let ctors ← getCtors C; (match ctors with | [c] => do let stx ← `($(Lean.mkIdent c) $(Array.getSepElems args.getArgs)*); elabTerm stx τ -- error handling | _ => unreachable!) | _ => unreachable! elab "foo⟨" args:sepBy(term, ", ") "⟩" : term <= τ => do elabAnonCtor args τ example : Nat × Nat := foo⟨1, 2⟩
12c1242dfddd0c86833a835307b492246b1baa83
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/1685.lean
02fe0f40726a4fbbe640b0a8fb14152684bf3546
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
2,622
lean
/- This test assumes the total order on terms used by simp compares local constants using the order they appear in the local context. -/ example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end
d003edb4d6b023c680e1c406d4e6b48b16c9197d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/sheaves/sheafify.lean
9b7f8594f1b29850e56b87c3753313ba2b090b24
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,398
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.local_predicate import topology.sheaves.stalks /-! # Sheafification of `Type` valued presheaves We construct the sheafification of a `Type` valued presheaf, as the subsheaf of dependent functions into the stalks consisting of functions which are locally germs. We show that the stalks of the sheafification are isomorphic to the original stalks, via `stalk_to_fiber` which evaluates a germ of a dependent function at a point. We construct a morphism `to_sheafify` from a presheaf to (the underlying presheaf of) its sheafification, given by sending a section to its collection of germs. ## Future work Show that the map induced on stalks by `to_sheafify` is the inverse of `stalk_to_fiber`. Show sheafification is a functor from presheaves to sheaves, and that it is the left adjoint of the forgetful functor, following https://stacks.math.columbia.edu/tag/007X. -/ universes v noncomputable theory open Top open opposite open topological_space variables {X : Top.{v}} (F : presheaf (Type v) X) namespace Top.presheaf namespace sheafify /-- The prelocal predicate on functions into the stalks, asserting that the function is equal to a germ. -/ def is_germ : prelocal_predicate (λ x, F.stalk x) := { pred := λ U f, ∃ (g : F.obj (op U)), ∀ x : U, f x = F.germ x g, res := λ V U i f ⟨g, p⟩, ⟨F.map i.op g, λ x, (p (i x)).trans (F.germ_res_apply _ _ _).symm⟩, } /-- The local predicate on functions into the stalks, asserting that the function is locally equal to a germ. -/ def is_locally_germ : local_predicate (λ x, F.stalk x) := (is_germ F).sheafify end sheafify /-- The sheafification of a `Type` valued presheaf, defined as the functions into the stalks which are locally equal to germs. -/ def sheafify : sheaf (Type v) X := subsheaf_to_Types (sheafify.is_locally_germ F) /-- The morphism from a presheaf to its sheafification, sending each section to its germs. (This forms the unit of the adjunction.) -/ def to_sheafify : F ⟶ F.sheafify.1 := { app := λ U f, ⟨λ x, F.germ x f, prelocal_predicate.sheafify_of ⟨f, λ x, rfl⟩⟩, naturality' := λ U U' f, by { ext x ⟨u, m⟩, exact germ_res_apply F f.unop ⟨u, m⟩ x } } /-- The natural morphism from the stalk of the sheafification to the original stalk. In `sheafify_stalk_iso` we show this is an isomorphism. -/ def stalk_to_fiber (x : X) : F.sheafify.1.stalk x ⟶ F.stalk x := stalk_to_fiber (sheafify.is_locally_germ F) x lemma stalk_to_fiber_surjective (x : X) : function.surjective (F.stalk_to_fiber x) := begin apply stalk_to_fiber_surjective, intro t, obtain ⟨U, m, s, rfl⟩ := F.germ_exist _ t, { use ⟨U, m⟩, fsplit, { exact λ y, F.germ y s, }, { exact ⟨prelocal_predicate.sheafify_of ⟨s, (λ _, rfl)⟩, rfl⟩, }, }, end lemma stalk_to_fiber_injective (x : X) : function.injective (F.stalk_to_fiber x) := begin apply stalk_to_fiber_injective, intros, rcases hU ⟨x, U.2⟩ with ⟨U', mU, iU, gU, wU⟩, rcases hV ⟨x, V.2⟩ with ⟨V', mV, iV, gV, wV⟩, have wUx := wU ⟨x, mU⟩, dsimp at wUx, erw wUx at e, clear wUx, have wVx := wV ⟨x, mV⟩, dsimp at wVx, erw wVx at e, clear wVx, rcases F.germ_eq x mU mV gU gV e with ⟨W, mW, iU', iV', e'⟩, dsimp at e', use ⟨W ⊓ (U' ⊓ V'), ⟨mW, mU, mV⟩⟩, refine ⟨_, _, _⟩, { change W ⊓ (U' ⊓ V') ⟶ U.val, exact (opens.inf_le_right _ _) ≫ (opens.inf_le_left _ _) ≫ iU, }, { change W ⊓ (U' ⊓ V') ⟶ V.val, exact (opens.inf_le_right _ _) ≫ (opens.inf_le_right _ _) ≫ iV, }, { intro w, dsimp, specialize wU ⟨w.1, w.2.2.1⟩, dsimp at wU, specialize wV ⟨w.1, w.2.2.2⟩, dsimp at wV, erw [wU, ←F.germ_res iU' ⟨w, w.2.1⟩, wV, ←F.germ_res iV' ⟨w, w.2.1⟩, category_theory.types_comp_apply, category_theory.types_comp_apply, e'] }, end /-- The isomorphism betweeen a stalk of the sheafification and the original stalk. -/ def sheafify_stalk_iso (x : X) : F.sheafify.1.stalk x ≅ F.stalk x := (equiv.of_bijective _ ⟨stalk_to_fiber_injective _ _, stalk_to_fiber_surjective _ _⟩).to_iso -- PROJECT functoriality, and that sheafification is the left adjoint of the forgetful functor. end Top.presheaf
8ebe5b9fa12c909d4e32f2fb4aea2b0c5bf1193d
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/data/nat/basic.lean
3e3cd60af9c576d2eee91c6617eebc72d81a7ad8
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
50,111
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro Basic operations on the natural numbers. -/ import logic.basic algebra.ordered_ring data.option.basic universes u v namespace nat variables {m n k : ℕ} -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ_inj, congr_arg _⟩ theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ lemma zero_max {m : nat} : max 0 m = m := max_eq_right (zero_le _) theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := nat.lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, nat.lt_succ_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := (lt_or_eq_of_le H).imp le_of_lt_succ id @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] theorem pos_iff_ne_zero : 0 < n ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ theorem pos_iff_ne_zero' : 0 < n ↔ n ≠ 0 := pos_iff_ne_zero lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial 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)) protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by rw [add_comm, add_mul_mod_self_left, mul_mod_right]; exact dec_trivial) @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (decidable.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin revert x, refine nat.strong_rec' _ y, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { rw succ_mul, exact iff_of_false (not_succ_le_zero _) (not_le_of_lt $ lt_of_lt_of_le h (le_add_left _ _)) } }, { rw [div_eq_sub_div k0 h], cases x with x, { simp [zero_mul, zero_le] }, { rw [← add_one, nat.add_le_add_iff_le_right, succ_mul, IH _ (sub_lt_of_pos_le _ _ k0 h), add_le_to_le_sub _ h] } } end theorem div_mul_le_self' (m n : ℕ) : m / n * n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0, zero_le]) $ λ n0, (le_div_iff_mul_le' n0).1 (le_refl _) theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self' _ _) h lemma lt_of_div_lt_div {m n k : ℕ} (h : m / k < n / k) : m < n := by_contradiction $ λ h₁, absurd h (not_lt_of_ge (nat.div_le_div_right (not_lt.1 h₁))) protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_right_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_left_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc] else by conv {to_rhs, rw ← mod_add_div a (b * c)}; rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))] lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] /- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/ lemma triangle_succ (n : ℕ) : (n + 1) * ((n + 1) - 1) / 2 = n * (n - 1) / 2 + n := begin rw [← add_mul_div_left, mul_comm 2 n, ← mul_add, nat.add_sub_cancel, mul_comm], cases n; refl, apply zero_lt_succ end @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm /-- A natural number m divides the sum m + n if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number m divides the sum n + m if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_left_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_right_inj hc] @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], by clear_aux_decl; finish⟩ lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_left_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) /- partial subtraction -/ /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := by dsimp; apply option.bind_eq_some.trans; simp [psub_eq_some] theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] /- pow -/ attribute [simp] nat.pow_zero nat.pow_one @[simp] lemma one_pow : ∀ n : ℕ, 1 ^ n = 1 | 0 := rfl | (k+1) := show 1^k * 1 = 1, by rw [mul_one, one_pow] theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, pow_succ, mul_assoc] theorem pow_two (a : ℕ) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right theorem pow_dvd_pow_of_dvd {a b : ℕ} (h : a ∣ b) : ∀ n:ℕ, a^n ∣ b^n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul (pow_dvd_pow_of_dvd n) h theorem mul_pow (a b n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm] protected theorem pow_mul (a b n : ℕ) : n ^ (a * b) = (n ^ a) ^ b := by induction b; simp [*, nat.succ_eq_add_one, nat.pow_add, mul_add, mul_comm] theorem pow_pos {p : ℕ} (hp : 0 < p) : ∀ n : ℕ, 0 < p ^ n | 0 := by simp | (k+1) := mul_pos (pow_pos _) hp lemma pow_eq_mul_pow_sub (p : ℕ) {m n : ℕ} (h : m ≤ n) : p ^ m * p ^ (n - m) = p ^ n := by rw [←nat.pow_add, nat.add_sub_cancel' h] lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) := suffices p^n*1 < p^n*p, by simpa, nat.mul_lt_mul_of_pos_left h (nat.pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have (succ p)^k * succ p ∣ 1 * succ p, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_right (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 < 1, by rwa [this] at hk, absurd this dec_trivial @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /- iterate -/ section variables {α : Sort*} (op : α → α) @[simp] theorem iterate_zero (a : α) : op^[0] a = a := rfl @[simp] theorem iterate_succ (n : ℕ) (a : α) : op^[succ n] a = (op^[n]) (op a) := rfl theorem iterate_add : ∀ (m n : ℕ) (a : α), op^[m + n] a = (op^[m]) (op^[n] a) | m 0 a := rfl | m (succ n) a := iterate_add m n _ theorem iterate_succ' (n : ℕ) (a : α) : op^[succ n] a = op (op^[n] a) := by rw [← one_add, iterate_add]; refl theorem iterate₀ {α : Type u} {op : α → α} {x : α} (H : op x = x) {n : ℕ} : op^[n] x = x := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate₁ {α : Type u} {β : Type v} {op : α → α} {op' : β → β} {op'' : α → β} (H : ∀ x, op' (op'' x) = op'' (op x)) {n : ℕ} {x : α} : op'^[n] (op'' x) = op'' (op^[n] x) := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate₂ {α : Type u} {op : α → α} {op' : α → α → α} (H : ∀ x y, op (op' x y) = op' (op x) (op y)) {n : ℕ} {x y : α} : op^[n] (op' x y) = op' (op^[n] x) (op^[n] y) := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate_cancel {α : Type u} {op op' : α → α} (H : ∀ x, op (op' x) = x) {n : ℕ} {x : α} : op^[n] (op'^[n] x) = x := by induction n; [refl, rwa [iterate_succ, iterate_succ', H]] theorem iterate_inj {α : Type u} {op : α → α} (Hinj : function.injective op) (n : ℕ) (x y : α) (H : (op^[n] x) = (op^[n] y)) : x = y := by induction n with n ih; simp only [iterate_zero, iterate_succ'] at H; [exact H, exact ih (Hinj H)] end /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, refl end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero'] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ /-- `fact n` is the factorial of `n`. -/ @[simp] def fact : nat → nat | 0 := 1 | (succ n) := succ n * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl theorem fact_pos : ∀ n, 0 < fact n | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : ∀ {m n}, 0 < m → m ≤ n → m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) lemma fact_mul_pow_le_fact : ∀ {m n : ℕ}, m.fact * m.succ ^ n ≤ (m + n).fact | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.fact_succ, mul_comm (nat.succ _), nat.pow_succ, ← mul_assoc]; exact mul_le_mul fact_mul_pow_le_fact (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_fact : monotone fact := λ n m, fact_le lemma fact_lt (h0 : 0 < n) : n.fact < m.fact ↔ n < m := begin split; intro h, { rw [← not_le], intro hmn, apply not_le_of_lt h (fact_le hmn) }, { have : ∀(n : ℕ), 0 < n → n.fact < n.succ.fact, { intros k hk, rw [fact_succ, succ_mul, lt_add_iff_pos_left], apply mul_pos hk (fact_pos k) }, induction h generalizing h0, { exact this _ h0, }, { refine lt_trans (h_ih h0) (this _ _), exact lt_trans h0 (lt_of_succ_le h_a) }} end lemma one_lt_fact : 1 < n.fact ↔ 1 < n := by { convert fact_lt _, refl, exact one_pos } lemma fact_eq_one : n.fact = 1 ↔ n ≤ 1 := begin split; intro h, { rw [← not_lt, ← one_lt_fact, h], apply lt_irrefl }, { cases h with h h, refl, cases h, refl } end lemma fact_inj (h0 : 1 < n.fact) : n.fact = m.fact ↔ n = m := begin split; intro h, { rcases lt_trichotomy n m with hnm|hnm|hnm, { exfalso, rw [← fact_lt, h] at hnm, exact lt_irrefl _ hnm, rw [one_lt_fact] at h0, exact lt_trans one_pos h0 }, { exact hnm }, { exfalso, rw [← fact_lt, h] at hnm, exact lt_irrefl _ hnm, rw [h, one_lt_fact] at h0, exact lt_trans one_pos h0 }}, { rw h } end /- choose -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (succ k) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose] /-- `choose n 2` is the `n`-th triangle number. -/ lemma choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := by { induction n, simp, simpa [n_ih, choose, add_one] using (triangle_succ n_n).symm } lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_fact_mul_fact : ∀ {n k}, k ≤ n → choose n k * fact k * fact (n - k) = fact n | 0 _ hk := by simp [eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * fact (succ k) * fact (n - k) = succ k * fact n := by rw ← choose_mul_fact_mul_fact (le_of_succ_le_succ hk); simp [fact_succ, mul_comm, mul_left_comm], have h₁ : fact (n - k) = (n - k) * fact (n - succ k) := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), fact_succ], have h₂ : choose n (succ k) * fact (succ k) * ((n - k) * fact (n - succ k)) = (n - k) * fact n := by rw ← choose_mul_fact_mul_fact (le_of_lt_succ hk₁); simp [fact_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * fact n ≤ n * fact n := mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, ← add_one, add_mul, nat.mul_sub_right_distrib, fact_succ, ← nat.add_sub_assoc h₃, add_assoc, ← add_mul, nat.add_sub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, nat.sub_self] } end theorem choose_eq_fact_div_fact {n k : ℕ} (hk : k ≤ n) : choose n k = fact n / (fact k * fact (n - k)) := begin have : fact n = choose n k * (fact k * fact (n - k)) := by rw ← mul_assoc; exact (choose_mul_fact_mul_fact hk).symm, exact (nat.div_eq_of_eq_mul_left (mul_pos (fact_pos _) (fact_pos _)) this).symm end theorem fact_mul_fact_dvd_fact {n k : ℕ} (hk : k ≤ n) : fact k * fact (n - k) ∣ fact n := by rw [←choose_mul_fact_mul_fact hk, mul_assoc]; exact dvd_mul_left _ _ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_spec_and_le : ∀{b m}, m ≤ b → P m → P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b | 0 m hm hP := have m = 0, from le_antisymm hm (nat.zero_le _), show P 0 ∧ m ≤ 0, from this ▸ ⟨hP, le_refl _⟩ | (b + 1) m hm hP := begin by_cases h : P (b + 1), { simp [h, hm] }, { have : m ≠ b + 1 := assume this, h $ this ▸ hP, have : m ≤ b := (le_of_not_gt $ assume h : b + 1 ≤ m, this $ le_antisymm hm h), have : P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b := find_greatest_spec_and_le this hP, simp [h, this] } end lemma find_greatest_spec {b} : (∃m, m ≤ b ∧ P m) → P (nat.find_greatest P b) | ⟨m, hmb, hm⟩ := (find_greatest_spec_and_le hmb hm).1 lemma find_greatest_le : ∀ {b}, nat.find_greatest P b ≤ b | 0 := le_refl _ | (b + 1) := have nat.find_greatest P b ≤ b + 1, from le_trans find_greatest_le (nat.le_succ b), by by_cases P (b + 1); simp [h, this] lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := (find_greatest_spec_and_le hmb hm).2 lemma find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b} : (∃ m, m ≤ b ∧ P m) → ∀ k, nat.find_greatest P b < k ∧ k ≤ b → ¬ P k | ⟨m, hmb, hP⟩ k ⟨hk, hkb⟩ hPk := lt_irrefl k $ lt_of_le_of_lt (le_find_greatest hkb hPk) hk lemma find_greatest_eq_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b}, (∀ n ≤ b, ¬ P n) → nat.find_greatest P b = 0 | 0 h := find_greatest_zero | (n + 1) h := begin have := nat.find_greatest_of_not (h (n + 1) (le_refl _)), rw this, exact find_greatest_eq_zero (assume k hk, h k (le_trans hk $ nat.le_succ _)) end lemma find_greatest_of_ne_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b m}, nat.find_greatest P b = m → m ≠ 0 → P m | 0 m rfl h := by { have := @find_greatest_zero P _, contradiction } | (b + 1) m rfl h := decidable.by_cases (assume hb : P (b + 1), by { have := find_greatest_eq hb, rw this, exact hb }) (assume hb : ¬ P (b + 1), find_greatest_of_ne_zero (find_greatest_of_not hb).symm h) end find_greatest section div lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have hac : a ∣ c, from dvd_of_mul_right_dvd h, have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk lemma eq_of_dvd_quot_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := begin rcases w with ⟨b, rfl⟩, rw [nat.mul_comm, nat.mul_div_cancel] at h, { simp [h] }, { by_contradiction, simp * at * } end lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end end div lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ lemma with_bot.add_eq_zero_iff : ∀ {n m : with_bot ℕ}, n + m = 0 ↔ n = 0 ∧ m = 0 | none m := iff_of_false dec_trivial (λ h, absurd h.1 dec_trivial) | n none := iff_of_false (by cases n; exact dec_trivial) (λ h, absurd h.2 dec_trivial) | (some n) (some m) := show (n + m : with_bot ℕ) = (0 : ℕ) ↔ (n : with_bot ℕ) = (0 : ℕ) ∧ (m : with_bot ℕ) = (0 : ℕ), by rw [← with_bot.coe_add, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, add_eq_zero_iff' (nat.zero_le _) (nat.zero_le _)] lemma with_bot.add_eq_one_iff : ∀ {n m : with_bot ℕ}, n + m = 1 ↔ (n = 0 ∧ m = 1) ∨ (n = 1 ∧ m = 0) | none none := dec_trivial | none (some m) := dec_trivial | (some n) none := iff_of_false dec_trivial (λ h, h.elim (λ h, absurd h.2 dec_trivial) (λ h, absurd h.2 dec_trivial)) | (some n) (some 0) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp | (some n) (some (m + 1)) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp [nat.add_succ, nat.succ_inj', nat.succ_ne_zero] -- induction @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } end nat
a50ca9ae8c154e4e2a71ee0b92739b60d2bd0053
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo1981_q3.lean
10a40331f2eecc46da9570b0e7e30e89f5039079
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,987
lean
/- Copyright (c) 2020 Kevin Lacker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker -/ import data.nat.fib import tactic.linarith /-! # IMO 1981 Q3 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Determine the maximum value of `m ^ 2 + n ^ 2`, where `m` and `n` are integers in `{1, 2, ..., 1981}` and `(n ^ 2 - m * n - m ^ 2) ^ 2 = 1`. The trick to this problem is that `m` and `n` have to be consecutive Fibonacci numbers, because you can reduce any solution to a smaller one using the Fibonacci recurrence. -/ /- First, define the problem in terms of finding the maximum of a set. We first generalize the problem to `{1, 2, ..., N}` and specialize to `N = 1981` at the very end. -/ open int nat set namespace imo1981_q3 variable (N : ℕ) -- N = 1981 @[mk_iff] structure problem_predicate (m n : ℤ) : Prop := (m_range : m ∈ Ioc 0 (N : ℤ)) (n_range : n ∈ Ioc 0 (N : ℤ)) (eq_one : (n ^ 2 - m * n - m ^ 2) ^ 2 = 1) def specified_set : set ℤ := {k : ℤ | ∃ m : ℤ, ∃ n : ℤ, k = m ^ 2 + n ^ 2 ∧ problem_predicate N m n} /- We want to reduce every solution to a smaller solution. Specifically, we show that when `(m, n)` is a solution, `(n - m, m)` is also a solution, except for the base case of `(1, 1)`. -/ namespace problem_predicate variable {N} lemma m_le_n {m n : ℤ} (h1 : problem_predicate N m n) : m ≤ n := begin by_contradiction h2, have h3 : 1 = (n * (n - m) - m ^ 2) ^ 2, { calc 1 = (n ^ 2 - m * n - m ^ 2) ^ 2 : h1.eq_one.symm ... = (n * (n - m) - m ^ 2) ^ 2 : by ring }, have h4 : n * (n - m) - m ^ 2 < -1, by nlinarith [h1.n_range.left], have h5 : 1 < (n * (n - m) - m ^ 2) ^ 2, by nlinarith, exact h5.ne h3 end lemma eq_imp_1 {n : ℤ} (h1 : problem_predicate N n n) : n = 1 := begin have : n * (n * (n * n)) = 1, { calc _ = (n ^ 2 - n * n - n ^ 2) ^ 2 : by simp [sq, mul_assoc] ... = 1 : h1.eq_one }, exact eq_one_of_mul_eq_one_right h1.m_range.left.le this, end lemma reduction {m n : ℤ} (h1 : problem_predicate N m n) (h2 : 1 < n) : problem_predicate N (n - m) m := begin obtain (rfl : m = n) | (h3 : m < n) := h1.m_le_n.eq_or_lt, { have h4 : m = 1, from h1.eq_imp_1, exact absurd h4.symm h2.ne }, refine_struct { n_range := h1.m_range, .. }, -- m_range: { have h5 : 0 < n - m, from sub_pos.mpr h3, have h6 : n - m < N, { calc _ < n : sub_lt_self n h1.m_range.left ... ≤ N : h1.n_range.right }, exact ⟨h5, h6.le⟩ }, -- eq_one: { calc _ = (n ^ 2 - m * n - m ^ 2) ^ 2 : by ring ... = 1 : h1.eq_one }, end end problem_predicate /- It will be convenient to have the lemmas above in their natural number form. Most of these can be proved with the `norm_cast` family of tactics. -/ def nat_predicate (m n : ℕ) : Prop := problem_predicate N ↑m ↑n namespace nat_predicate variable {N} lemma m_le_n {m n : ℕ} (h1 : nat_predicate N m n) : m ≤ n := by exact_mod_cast h1.m_le_n lemma eq_imp_1 {n : ℕ} (h1 : nat_predicate N n n) : n = 1 := by exact_mod_cast h1.eq_imp_1 lemma reduction {m n : ℕ} (h1 : nat_predicate N m n) (h2 : 1 < n) : nat_predicate N (n - m) m := have m ≤ n, from h1.m_le_n, by exact_mod_cast h1.reduction (by exact_mod_cast h2) lemma n_pos {m n : ℕ} (h1 : nat_predicate N m n) : 0 < n := by exact_mod_cast h1.n_range.left lemma m_pos {m n : ℕ} (h1 : nat_predicate N m n) : 0 < m := by exact_mod_cast h1.m_range.left lemma n_le_N {m n : ℕ} (h1 : nat_predicate N m n) : n ≤ N := by exact_mod_cast h1.n_range.right /- Now we can use induction to show that solutions must be Fibonacci numbers. -/ lemma imp_fib {n : ℕ} : ∀ m : ℕ, nat_predicate N m n → ∃ k : ℕ, m = fib k ∧ n = fib (k + 1) := begin apply nat.strong_induction_on n _, intros n h1 m h2, have h3 : m ≤ n, from h2.m_le_n, obtain (rfl : 1 = n) | (h4 : 1 < n) := (succ_le_iff.mpr h2.n_pos).eq_or_lt, { use 1, have h5 : 1 ≤ m, from succ_le_iff.mpr h2.m_pos, simpa [fib_one, fib_two] using (h3.antisymm h5 : m = 1) }, { obtain (rfl : m = n) | (h6 : m < n) := h3.eq_or_lt, { exact absurd h2.eq_imp_1 (ne_of_gt h4) }, { have h7 : nat_predicate N (n - m) m, from h2.reduction h4, obtain ⟨k : ℕ, hnm : n - m = fib k, rfl : m = fib (k+1)⟩ := h1 m h6 (n - m) h7, use [k + 1, rfl], rw [fib_add_two, ← hnm, tsub_add_cancel_of_le h3] } } end end nat_predicate /- Next, we prove that if `N < fib K + fib (K+1)`, then the largest `m` and `n` satisfying `nat_predicate m n N` are `fib K` and `fib (K+1)`, respectively. -/ variables {K : ℕ} (HK : N < fib K + fib (K+1)) {N} include HK lemma m_n_bounds {m n : ℕ} (h1 : nat_predicate N m n) : m ≤ fib K ∧ n ≤ fib (K+1) := begin obtain ⟨k : ℕ, hm : m = fib k, hn : n = fib (k+1)⟩ := h1.imp_fib m, by_cases h2 : k < K + 1, { have h3 : k ≤ K, from lt_succ_iff.mp h2, split, { calc m = fib k : hm ... ≤ fib K : fib_mono h3, }, { have h6 : k + 1 ≤ K + 1, from succ_le_succ h3, calc n = fib (k+1) : hn ... ≤ fib (K+1) : fib_mono h6 } }, { have h7 : N < n, { have h8 : K + 2 ≤ k + 1, from succ_le_succ (not_lt.mp h2), rw ← fib_add_two at HK, calc N < fib (K+2) : HK ... ≤ fib (k+1) : fib_mono h8 ... = n : hn.symm, }, have h9 : n ≤ N, from h1.n_le_N, exact absurd h7 h9.not_lt } end /- We spell out the consequences of this result for `specified_set N` here. -/ variables {M : ℕ} (HM : M = (fib K) ^ 2 + (fib (K+1)) ^ 2) include HM lemma k_bound {m n : ℤ} (h1 : problem_predicate N m n) : m ^ 2 + n ^ 2 ≤ M := begin have h2 : 0 ≤ m, from h1.m_range.left.le, have h3 : 0 ≤ n, from h1.n_range.left.le, rw [← nat_abs_of_nonneg h2, ← nat_abs_of_nonneg h3] at h1, clear h2 h3, obtain ⟨h4 : m.nat_abs ≤ fib K, h5 : n.nat_abs ≤ fib (K+1)⟩ := m_n_bounds HK h1, have h6 : m ^ 2 ≤ (fib K) ^ 2, from nat_abs_le_iff_sq_le.mp h4, have h7 : n ^ 2 ≤ (fib (K+1)) ^ 2, from nat_abs_le_iff_sq_le.mp h5, linarith end lemma solution_bound : ∀ {k : ℤ}, k ∈ specified_set N → k ≤ M | _ ⟨_, _, rfl, h⟩ := k_bound HK HM h theorem solution_greatest (H : problem_predicate N (fib K) (fib (K + 1))) : is_greatest (specified_set N) M := ⟨⟨fib K, fib (K+1), by simp [HM], H⟩, λ k h, solution_bound HK HM h⟩ end imo1981_q3 open imo1981_q3 /- Now we just have to demonstrate that 987 and 1597 are in fact the largest Fibonacci numbers in this range, and thus provide the maximum of `specified_set`. -/ theorem imo1981_q3 : is_greatest (specified_set 1981) 3524578 := begin have := λ h, @solution_greatest 1981 16 h 3524578, simp only [show fib (16:ℕ) = 987 ∧ fib (16+1:ℕ) = 1597, by norm_num [fib_add_two]] at this, apply_mod_cast this; norm_num [problem_predicate_iff], end
8d83b36847c5efdbdb5a5265bf3d9a1cda7c52ae
4fa161becb8ce7378a709f5992a594764699e268
/src/data/real/cau_seq_completion.lean
261878e6567bcf83a3f39bec686616a8f778043c
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
9,478
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis Generalizes the Cauchy completion of (ℚ, abs) to the completion of a commutative ring with absolute value. -/ import data.real.cau_seq namespace cau_seq.completion open cau_seq section parameters {α : Type*} [discrete_linear_ordered_field α] parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv def mk : cau_seq _ abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat (x : β) : Cauchy := mk (const abv x) instance : has_zero Cauchy := ⟨of_rat 0⟩ instance : has_one Cauchy := ⟨of_rat 1⟩ instance : inhabited Cauchy := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using add_lim_zero hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk (-f)) $ λ f₁ f₂ hf, quotient.sound $ by simpa [(≈), setoid.r] using neg_lim_zero hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, mul_add, mul_comm, add_assoc, sub_eq_add_neg] using add_lim_zero (mul_lim_zero_right g₁ hf) (mul_lim_zero_right f₂ hg)⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = mk 0 := rfl private lemma one_def : 1 = mk 1 := rfl instance : comm_ring Cauchy := by refine { neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, .. }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm] } theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) end open_locale classical section parameters {α : Type*} [discrete_linear_ordered_field α] parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] local notation `Cauchy` := @Cauchy _ _ _ _ abv _ noncomputable instance : has_inv Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end noncomputable def field : field Cauchy := { inv := has_inv.inv, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], zero_ne_one := zero_ne_one, inv_zero := inv_zero, ..cau_seq.completion.comm_ring } local attribute [instance] field theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) := congr_arg mk $ by split_ifs with h; try {simp [const_lim_zero.1 h]}; refl theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) := by simp only [div_eq_inv_mul, of_rat_inv, of_rat_mul] end end cau_seq.completion variables {α : Type*} [discrete_linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] class is_complete := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete noncomputable def lim (s : cau_seq β abv) := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
24e9d6edb8a4158b53cdf92a2871983f138d1600
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/functor_category_auto.lean
4502a43ead9383be98dd792e137c9165be229f14
[]
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
13,386
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.preserves.limits import Mathlib.PostPort universes v v₂ u namespace Mathlib namespace category_theory.limits @[simp] theorem limit.lift_π_app {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (H : J ⥤ K ⥤ C) [has_limit H] (c : cone H) (j : J) (k : K) : nat_trans.app (limit.lift H c) k ≫ nat_trans.app (limit.π H j) k = nat_trans.app (nat_trans.app (cone.π c) j) k := congr_app (limit.lift_π c j) k @[simp] theorem colimit.ι_desc_app_assoc {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (H : J ⥤ K ⥤ C) [has_colimit H] (c : cocone H) (j : J) (k : K) {X' : C} (f' : functor.obj (cocone.X c) k ⟶ X') : nat_trans.app (colimit.ι H j) k ≫ nat_trans.app (colimit.desc H c) k ≫ f' = nat_trans.app (nat_trans.app (cocone.ι c) j) k ≫ f' := sorry /-- The evaluation functors jointly reflect limits: that is, to show a cone is a limit of `F` it suffices to show that each evaluation cone is a limit. In other words, to prove a cone is limiting you can show it's pointwise limiting. -/ def evaluation_jointly_reflects_limits {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] {F : J ⥤ K ⥤ C} (c : cone F) (t : (k : K) → is_limit (functor.map_cone (functor.obj (evaluation K C) k) c)) : is_limit c := is_limit.mk fun (s : cone F) => nat_trans.mk fun (k : K) => is_limit.lift (t k) (cone.mk (functor.obj (cone.X s) k) (whisker_right (cone.π s) (functor.obj (evaluation K C) k))) /-- Given a functor `F` and a collection of limit cones for each diagram `X ↦ F X k`, we can stitch them together to give a cone for the diagram `F`. `combined_is_limit` shows that the new cone is limiting, and `eval_combined` shows it is (essentially) made up of the original cones. -/ @[simp] theorem combine_cones_X_obj {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → limit_cone (functor.obj (functor.flip F) k)) (k : K) : functor.obj (cone.X (combine_cones F c)) k = cone.X (limit_cone.cone (c k)) := Eq.refl (functor.obj (cone.X (combine_cones F c)) k) /-- The stitched together cones each project down to the original given cones (up to iso). -/ def evaluate_combined_cones {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → limit_cone (functor.obj (functor.flip F) k)) (k : K) : functor.map_cone (functor.obj (evaluation K C) k) (combine_cones F c) ≅ limit_cone.cone (c k) := cones.ext (iso.refl (cone.X (functor.map_cone (functor.obj (evaluation K C) k) (combine_cones F c)))) sorry /-- Stitching together limiting cones gives a limiting cone. -/ def combined_is_limit {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → limit_cone (functor.obj (functor.flip F) k)) : is_limit (combine_cones F c) := evaluation_jointly_reflects_limits (combine_cones F c) fun (k : K) => is_limit.of_iso_limit (limit_cone.is_limit (c k)) (iso.symm (evaluate_combined_cones F c k)) /-- The evaluation functors jointly reflect colimits: that is, to show a cocone is a colimit of `F` it suffices to show that each evaluation cocone is a colimit. In other words, to prove a cocone is colimiting you can show it's pointwise colimiting. -/ def evaluation_jointly_reflects_colimits {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] {F : J ⥤ K ⥤ C} (c : cocone F) (t : (k : K) → is_colimit (functor.map_cocone (functor.obj (evaluation K C) k) c)) : is_colimit c := is_colimit.mk fun (s : cocone F) => nat_trans.mk fun (k : K) => is_colimit.desc (t k) (cocone.mk (functor.obj (cocone.X s) k) (whisker_right (cocone.ι s) (functor.obj (evaluation K C) k))) /-- Given a functor `F` and a collection of colimit cocones for each diagram `X ↦ F X k`, we can stitch them together to give a cocone for the diagram `F`. `combined_is_colimit` shows that the new cocone is colimiting, and `eval_combined` shows it is (essentially) made up of the original cocones. -/ def combine_cocones {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → colimit_cocone (functor.obj (functor.flip F) k)) : cocone F := cocone.mk (functor.mk (fun (k : K) => cocone.X (colimit_cocone.cocone (c k))) fun (k₁ k₂ : K) (f : k₁ ⟶ k₂) => is_colimit.desc (colimit_cocone.is_colimit (c k₁)) (cocone.mk (cocone.X (colimit_cocone.cocone (c k₂))) (functor.map (functor.flip F) f ≫ cocone.ι (colimit_cocone.cocone (c k₂))))) (nat_trans.mk fun (j : J) => nat_trans.mk fun (k : K) => nat_trans.app (cocone.ι (colimit_cocone.cocone (c k))) j) /-- The stitched together cocones each project down to the original given cocones (up to iso). -/ def evaluate_combined_cocones {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → colimit_cocone (functor.obj (functor.flip F) k)) (k : K) : functor.map_cocone (functor.obj (evaluation K C) k) (combine_cocones F c) ≅ colimit_cocone.cocone (c k) := cocones.ext (iso.refl (cocone.X (functor.map_cocone (functor.obj (evaluation K C) k) (combine_cocones F c)))) sorry /-- Stitching together colimiting cocones gives a colimiting cocone. -/ def combined_is_colimit {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → colimit_cocone (functor.obj (functor.flip F) k)) : is_colimit (combine_cocones F c) := evaluation_jointly_reflects_colimits (combine_cocones F c) fun (k : K) => is_colimit.of_iso_colimit (colimit_cocone.is_colimit (c k)) (iso.symm (evaluate_combined_cocones F c k)) protected instance functor_category_has_limits_of_shape {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] : has_limits_of_shape J (K ⥤ C) := has_limits_of_shape.mk fun (F : J ⥤ K ⥤ C) => has_limit.mk (limit_cone.mk (combine_cones F fun (k : K) => get_limit_cone (functor.obj (functor.flip F) k)) (combined_is_limit F fun (k : K) => get_limit_cone (functor.obj (functor.flip F) k))) protected instance functor_category_has_colimits_of_shape {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] : has_colimits_of_shape J (K ⥤ C) := has_colimits_of_shape.mk fun (F : J ⥤ K ⥤ C) => has_colimit.mk (colimit_cocone.mk (combine_cocones F fun (k : K) => get_colimit_cocone (functor.obj (functor.flip F) k)) (combined_is_colimit F fun (k : K) => get_colimit_cocone (functor.obj (functor.flip F) k))) protected instance functor_category_has_limits {C : Type u} [category C] {K : Type v} [category K] [has_limits C] : has_limits (K ⥤ C) := has_limits.mk fun (J : Type v) (𝒥 : small_category J) => limits.functor_category_has_limits_of_shape protected instance functor_category_has_colimits {C : Type u} [category C] {K : Type v} [category K] [has_colimits C] : has_colimits (K ⥤ C) := has_colimits.mk fun (J : Type v) (𝒥 : small_category J) => limits.functor_category_has_colimits_of_shape protected instance evaluation_preserves_limits_of_shape {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] (k : K) : preserves_limits_of_shape J (functor.obj (evaluation K C) k) := preserves_limits_of_shape.mk fun (F : J ⥤ K ⥤ C) => preserves_limit_of_preserves_limit_cone (combined_is_limit F fun (k : K) => get_limit_cone (F ⋙ functor.obj (evaluation K C) k)) (is_limit.of_iso_limit (limit.is_limit (F ⋙ functor.obj (evaluation K C) k)) (iso.symm (evaluate_combined_cones F (fun (k : K) => get_limit_cone (F ⋙ functor.obj (evaluation K C) k)) k))) /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a limit, then the evaluation of that limit at `k` is the limit of the evaluations of `F.obj j` at `k`. -/ def limit_obj_iso_limit_comp_evaluation {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : functor.obj (limit F) k ≅ limit (F ⋙ functor.obj (evaluation K C) k) := preserves_limit_iso (functor.obj (evaluation K C) k) F @[simp] theorem limit_obj_iso_limit_comp_evaluation_hom_π {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (j : J) (k : K) : iso.hom (limit_obj_iso_limit_comp_evaluation F k) ≫ limit.π (F ⋙ functor.obj (evaluation K C) k) j = nat_trans.app (limit.π F j) k := sorry @[simp] theorem limit_obj_iso_limit_comp_evaluation_inv_π_app_assoc {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (j : J) (k : K) {X' : C} (f' : functor.obj (functor.obj F j) k ⟶ X') : iso.inv (limit_obj_iso_limit_comp_evaluation F k) ≫ nat_trans.app (limit.π F j) k ≫ f' = limit.π (F ⋙ functor.obj (evaluation K C) k) j ≫ f' := sorry theorem limit_obj_ext {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] {H : J ⥤ K ⥤ C} [has_limits_of_shape J C] {k : K} {W : C} {f : W ⟶ functor.obj (limit H) k} {g : W ⟶ functor.obj (limit H) k} (w : ∀ (j : J), f ≫ nat_trans.app (limit.π H j) k = g ≫ nat_trans.app (limit.π H j) k) : f = g := sorry protected instance evaluation_preserves_colimits_of_shape {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] (k : K) : preserves_colimits_of_shape J (functor.obj (evaluation K C) k) := preserves_colimits_of_shape.mk fun (F : J ⥤ K ⥤ C) => preserves_colimit_of_preserves_colimit_cocone (combined_is_colimit F fun (k : K) => get_colimit_cocone (F ⋙ functor.obj (evaluation K C) k)) (is_colimit.of_iso_colimit (colimit.is_colimit (F ⋙ functor.obj (evaluation K C) k)) (iso.symm (evaluate_combined_cocones F (fun (k : K) => get_colimit_cocone (F ⋙ functor.obj (evaluation K C) k)) k))) /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a colimit, then the evaluation of that colimit at `k` is the colimit of the evaluations of `F.obj j` at `k`. -/ def colimit_obj_iso_colimit_comp_evaluation {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : functor.obj (colimit F) k ≅ colimit (F ⋙ functor.obj (evaluation K C) k) := preserves_colimit_iso (functor.obj (evaluation K C) k) F @[simp] theorem colimit_obj_iso_colimit_comp_evaluation_ι_inv {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (j : J) (k : K) : colimit.ι (F ⋙ functor.obj (evaluation K C) k) j ≫ iso.inv (colimit_obj_iso_colimit_comp_evaluation F k) = nat_trans.app (colimit.ι F j) k := sorry @[simp] theorem colimit_obj_iso_colimit_comp_evaluation_ι_app_hom {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (j : J) (k : K) : nat_trans.app (colimit.ι F j) k ≫ iso.hom (colimit_obj_iso_colimit_comp_evaluation F k) = colimit.ι (F ⋙ functor.obj (evaluation K C) k) j := sorry theorem colimit_obj_ext {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] {H : J ⥤ K ⥤ C} [has_colimits_of_shape J C] {k : K} {W : C} {f : functor.obj (colimit H) k ⟶ W} {g : functor.obj (colimit H) k ⟶ W} (w : ∀ (j : J), nat_trans.app (colimit.ι H j) k ≫ f = nat_trans.app (colimit.ι H j) k ≫ g) : f = g := sorry protected instance evaluation_preserves_limits {C : Type u} [category C] {K : Type v} [category K] [has_limits C] (k : K) : preserves_limits (functor.obj (evaluation K C) k) := preserves_limits.mk fun (J : Type v) (𝒥 : small_category J) => limits.evaluation_preserves_limits_of_shape k protected instance evaluation_preserves_colimits {C : Type u} [category C] {K : Type v} [category K] [has_colimits C] (k : K) : preserves_colimits (functor.obj (evaluation K C) k) := preserves_colimits.mk fun (J : Type v) (𝒥 : small_category J) => limits.evaluation_preserves_colimits_of_shape k end Mathlib
a768263abf8cc3734e1038441a4d29b9e4908111
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/free_comm_ring.lean
affb55652841ff9cbd4fdc0f266fee75959889bb
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
10,690
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.functor import Mathlib.data.mv_polynomial.equiv import Mathlib.data.mv_polynomial.comm_ring import Mathlib.ring_theory.free_ring import Mathlib.PostPort universes u v u_1 u_2 namespace Mathlib /-! # Free commutative rings The theory of the free commutative ring generated by a type `α`. It is isomorphic to the polynomial ring over ℤ with variables in `α` ## Main definitions * `free_comm_ring α` : the free commutative ring on a type α * `lift_hom (f : α → R)` : the ring hom `free_comm_ring α →+* R` induced by functoriality from `f`. * `map (f : α → β)` : the ring hom `free_comm_ring α →*+ free_comm_ring β` induced by functoriality from f. ## Main results `free_comm_ring` has functorial properties (it is an adjoint to the forgetful functor). In this file we have: * `of : α → free_comm_ring α` * `lift_hom (f : α → R) : free_comm_ring α →+* R` * `map (f : α → β) : free_comm_ring α →+* free_comm_ring β` * `free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ` : `free_comm_ring α` is isomorphic to a polynomial ring. ## Implementation notes `free_comm_ring α` is implemented not using `mv_polynomial` but directly as the free abelian group on `multiset α`, the type of monomials in this free commutative ring. ## Tags free commutative ring, free ring -/ /-- `free_comm_ring α` is the free commutative ring on the type `α`. -/ def free_comm_ring (α : Type u) := free_abelian_group (multiplicative (multiset α)) namespace free_comm_ring /-- The structure of a commutative ring on `free_comm_ring α`. -/ protected instance comm_ring (α : Type u) : comm_ring (free_comm_ring α) := free_abelian_group.comm_ring (multiplicative (multiset α)) protected instance inhabited (α : Type u) : Inhabited (free_comm_ring α) := { default := 0 } /-- The canonical map from `α` to the free commutative ring on `α`. -/ def of {α : Type u} (x : α) : free_comm_ring α := free_abelian_group.of ↑[x] theorem of_injective {α : Type u} : function.injective of := function.injective.comp free_abelian_group.of_injective fun (x y : α) => iff.mp (iff.trans multiset.coe_eq_coe list.singleton_perm_singleton) protected theorem induction_on {α : Type u} {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ (b : α), C (of b)) (ha : ∀ (x y : free_comm_ring α), C x → C y → C (x + y)) (hm : ∀ (x y : free_comm_ring α), C x → C y → C (x * y)) : C z := sorry /-- Lift a map `α → R` to a additive group homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift {α : Type u} {R : Type v} [comm_ring R] (f : α → R) : free_comm_ring α →+* R := ring_hom.mk (add_monoid_hom.to_fun (free_abelian_group.lift fun (s : multiplicative (multiset α)) => multiset.prod (multiset.map f (coe_fn multiplicative.to_add s)))) sorry sorry sorry sorry @[simp] theorem lift_of {α : Type u} {R : Type v} [comm_ring R] (f : α → R) (x : α) : coe_fn (lift f) (of x) = f x := sorry @[simp] theorem lift_comp_of {α : Type u} {R : Type v} [comm_ring R] (f : free_comm_ring α →+* R) : lift (⇑f ∘ of) = f := sorry /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α →+* free_comm_ring β`. -/ def map {α : Type u} {β : Type v} (f : α → β) : free_comm_ring α →+* free_comm_ring β := lift (of ∘ f) @[simp] theorem map_of {α : Type u} {β : Type v} (f : α → β) (x : α) : coe_fn (map f) (of x) = of (f x) := lift_of (of ∘ f) x /-- `is_supported x s` means that all monomials showing up in `x` have variables in `s`. -/ def is_supported {α : Type u} (x : free_comm_ring α) (s : set α) := x ∈ ring.closure (of '' s) theorem is_supported_upwards {α : Type u} {x : free_comm_ring α} {s : set α} {t : set α} (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.monotone_image hst) hs theorem is_supported_add {α : Type u} {x : free_comm_ring α} {y : free_comm_ring α} {s : set α} (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg {α : Type u} {x : free_comm_ring α} {s : set α} (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub {α : Type u} {x : free_comm_ring α} {y : free_comm_ring α} {s : set α} (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem hxs hys theorem is_supported_mul {α : Type u} {x : free_comm_ring α} {y : free_comm_ring α} {s : set α} (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero {α : Type u} {s : set α} : is_supported 0 s := is_add_submonoid.zero_mem theorem is_supported_one {α : Type u} {s : set α} : is_supported 1 s := is_submonoid.one_mem theorem is_supported_int {α : Type u} {i : ℤ} {s : set α} : is_supported (↑i) s := sorry /-- The restriction map from `free_comm_ring α` to `free_comm_ring s` where `s : set α`, defined by sending all variables not in `s` to zero. -/ def restriction {α : Type u} (s : set α) [decidable_pred s] : free_comm_ring α →+* free_comm_ring ↥s := lift fun (p : α) => dite (p ∈ s) (fun (H : p ∈ s) => of { val := p, property := H }) fun (H : ¬p ∈ s) => 0 @[simp] theorem restriction_of {α : Type u} (s : set α) [decidable_pred s] (p : α) : coe_fn (restriction s) (of p) = dite (p ∈ s) (fun (H : p ∈ s) => of { val := p, property := H }) fun (H : ¬p ∈ s) => 0 := lift_of (fun (p : α) => dite (p ∈ s) (fun (H : p ∈ s) => of { val := p, property := H }) fun (H : ¬p ∈ s) => 0) p theorem is_supported_of {α : Type u} {p : α} {s : set α} : is_supported (of p) s ↔ p ∈ s := sorry theorem map_subtype_val_restriction {α : Type u} {x : free_comm_ring α} (s : set α) [decidable_pred s] (hxs : is_supported x s) : coe_fn (map subtype.val) (coe_fn (restriction s) x) = x := sorry theorem exists_finite_support {α : Type u} (x : free_comm_ring α) : ∃ (s : set α), set.finite s ∧ is_supported x s := sorry theorem exists_finset_support {α : Type u} (x : free_comm_ring α) : ∃ (s : finset α), is_supported x ↑s := sorry end free_comm_ring namespace free_ring /-- The canonical ring homomorphism from the free ring generated by `α` to the free commutative ring generated by `α`. -/ def to_free_comm_ring {α : Type u_1} : free_ring α →+* free_comm_ring α := lift free_comm_ring.of protected instance free_comm_ring.has_coe (α : Type u) : has_coe (free_ring α) (free_comm_ring α) := has_coe.mk ⇑to_free_comm_ring protected instance coe.is_ring_hom (α : Type u) : is_ring_hom coe := ring_hom.is_ring_hom to_free_comm_ring @[simp] protected theorem coe_zero (α : Type u) : ↑0 = 0 := rfl @[simp] protected theorem coe_one (α : Type u) : ↑1 = 1 := rfl @[simp] protected theorem coe_of {α : Type u} (a : α) : ↑(of a) = free_comm_ring.of a := lift_of free_comm_ring.of a @[simp] protected theorem coe_neg {α : Type u} (x : free_ring α) : ↑(-x) = -↑x := ring_hom.map_neg (lift free_comm_ring.of) x @[simp] protected theorem coe_add {α : Type u} (x : free_ring α) (y : free_ring α) : ↑(x + y) = ↑x + ↑y := ring_hom.map_add (lift free_comm_ring.of) x y @[simp] protected theorem coe_sub {α : Type u} (x : free_ring α) (y : free_ring α) : ↑(x - y) = ↑x - ↑y := ring_hom.map_sub (lift free_comm_ring.of) x y @[simp] protected theorem coe_mul {α : Type u} (x : free_ring α) (y : free_ring α) : ↑(x * y) = ↑x * ↑y := ring_hom.map_mul (lift free_comm_ring.of) x y protected theorem coe_surjective (α : Type u) : function.surjective coe := sorry theorem coe_eq (α : Type u) : coe = Functor.map fun (l : List α) => ↑l := sorry -- FIXME This was in `deprecated.ring`, but only used here. -- It would be good to inline it into the next construction. /-- Interpret an equivalence `f : R ≃ S` as a ring equivalence `R ≃+* S`. -/ def of' {R : Type u_1} {S : Type u_2} [ring R] [ring S] (e : R ≃ S) [is_ring_hom ⇑e] : R ≃+* S := ring_equiv.mk (equiv.to_fun e) (equiv.inv_fun e) (equiv.left_inv e) (equiv.right_inv e) sorry sorry /-- If α has size at most 1 then the natural map from the free ring on `α` to the free commutative ring on `α` is an isomorphism of rings. -/ def subsingleton_equiv_free_comm_ring (α : Type u) [subsingleton α] : free_ring α ≃+* free_comm_ring α := of' (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) protected instance comm_ring (α : Type u) [subsingleton α] : comm_ring (free_ring α) := comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry sorry end free_ring /-- The free commutative ring on `α` is isomorphic to the polynomial ring over ℤ with variables in `α` -/ def free_comm_ring_equiv_mv_polynomial_int (α : Type u) : free_comm_ring α ≃+* mv_polynomial α ℤ := ring_equiv.mk (⇑(free_comm_ring.lift fun (a : α) => mv_polynomial.X a)) (mv_polynomial.eval₂ (int.cast_ring_hom (free_comm_ring α)) free_comm_ring.of) sorry sorry sorry sorry /-- The free commutative ring on the empty type is isomorphic to `ℤ`. -/ def free_comm_ring_pempty_equiv_int : free_comm_ring pempty ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int pempty) (mv_polynomial.pempty_ring_equiv ℤ) /-- The free commutative ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring PUnit ≃+* polynomial ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int PUnit) (mv_polynomial.punit_ring_equiv ℤ) /-- The free ring on the empty type is isomorphic to `ℤ`. -/ def free_ring_pempty_equiv_int : free_ring pempty ≃+* ℤ := ring_equiv.trans (free_ring.subsingleton_equiv_free_comm_ring pempty) free_comm_ring_pempty_equiv_int /-- The free ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_ring_punit_equiv_polynomial_int : free_ring PUnit ≃+* polynomial ℤ := ring_equiv.trans (free_ring.subsingleton_equiv_free_comm_ring PUnit) free_comm_ring_punit_equiv_polynomial_int
0c2ae141d18803a39477483cd82c63af07074f1e
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/field_theory/adjoin.lean
d9afc473cc588c9d8cb8b6491ad948d742d89993
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
22,373
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.intermediate_field import field_theory.splitting_field import field_theory.fixed /-! # Adjoining Elements to Fields In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`. - `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x` in `E` then `F = E` ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ open finite_dimensional open_locale classical namespace intermediate_field section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin : intermediate_field F E := { algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)), ..subfield.closure (set.range (algebra_map F E) ∪ S) } end adjoin_def section lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] @[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T := ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H, λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr (set.union_subset (intermediate_field.set_range_subset T) H)⟩ lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff /-- Galois insertion between `adjoin` and `coe`. -/ def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe := { choice := λ S _, adjoin F S, gc := intermediate_field.gc, le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (intermediate_field F E) := galois_insertion.lift_complete_lattice intermediate_field.gi instance : inhabited (intermediate_field F E) := ⟨⊤⟩ lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) := begin suffices : set.range (algebra_map F E) = (⊥ : intermediate_field F E), { rw this, refl }, { change set.range (algebra_map F E) = subfield.closure (set.range (algebra_map F E) ∪ ∅), simp [←set.image_univ, ←ring_hom.map_field_closure] } end lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) := subfield.subset_closure $ or.inr trivial @[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ := by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] } @[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ := by { ext, rw [mem_to_subalgebra, iff_true_right algebra.mem_top], exact mem_top } /-- Construct an algebra isomorphism from an equality of subalgebras -/ def subalgebra.equiv_of_eq {X Y : subalgebra F E} (h : X = Y) : X ≃ₐ[F] Y := by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy /-- The bottom intermediate_field is isomorphic to the field. -/ noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F := (subalgebra.equiv_of_eq bot_to_subalgebra).trans (algebra.bot_equiv F E) @[simp] lemma bot_equiv_def (x : F) : bot_equiv (algebra_map F (⊥ : intermediate_field F E) x) = x := alg_equiv.commutes bot_equiv x noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F := ring_hom.to_algebra intermediate_field.bot_equiv.to_alg_hom.to_ring_hom instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E := is_scalar_tower.of_algebra_map_eq begin intro x, let ϕ := algebra.of_id F (⊥ : subalgebra F E), let ψ := alg_equiv.of_bijective ϕ ((algebra.bot_equiv F E).symm.bijective), change (↑x : E) = ↑(ψ (ψ.symm ⟨x, _⟩)), rw alg_equiv.apply_symm_apply ψ ⟨x, _⟩, refl end /-- The top intermediate_field is isomorphic to the field. -/ noncomputable def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E := (subalgebra.equiv_of_eq top_to_subalgebra).trans algebra.top_equiv @[simp] lemma top_equiv_def (x : (⊤ : intermediate_field F E)) : top_equiv x = ↑x := begin suffices : algebra.to_top (top_equiv x) = algebra.to_top (x : E), { rwa subtype.ext_iff at this }, exact alg_equiv.apply_symm_apply (alg_equiv.of_bijective algebra.to_top ⟨λ _ _, subtype.mk.inj, λ x, ⟨x.val, by { ext, refl }⟩⟩ : E ≃ₐ[F] (⊤ : subalgebra F E)) (subalgebra.equiv_of_eq top_to_subalgebra x), end @[simp] lemma coe_bot_eq_self (K : intermediate_field F E) : ↑(⊥ : intermediate_field K E) = K := by { ext, rw [mem_lift2, mem_bot], exact set.ext_iff.mp subtype.range_coe x } @[simp] lemma coe_top_eq_top (K : intermediate_field F E) : ↑(⊤ : intermediate_field K E) = (⊤ : intermediate_field F E) := intermediate_field.ext'_iff.mpr (set.ext_iff.mpr (λ _, iff_of_true mem_top mem_top)) end lattice section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) lemma adjoin_eq_range_algebra_map_adjoin : (adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S := intermediate_field.algebra_map_mem (adjoin F S) x lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S := begin intros x hx, cases hx with f hf, rw ← hf, exact adjoin.algebra_map_mem F S f, end instance adjoin.field_coe : has_coe_t F (adjoin F S) := {coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩} lemma subset_adjoin : S ⊆ adjoin F S := λ x hx, subfield.subset_closure (or.inr hx) instance adjoin.set_coe : has_coe_t S (adjoin F S) := {coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩} @[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T := galois_connection.monotone_l gc h lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩ lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S := λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩ lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S := λ x hx, subset_adjoin F S (H hx) @[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (∅ : set E) = ⊥ := eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _)) /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/ lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K) (HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K := begin apply subfield.closure_le.mpr, rw set.union_subset_iff, exact ⟨HF, HS⟩, end lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E] {S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔ set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' := ⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩, λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩ /-- `F[S][T] = F[S ∪ T]` -/ lemma adjoin_adjoin_left (T : set E) : ↑(adjoin (adjoin F S) T) = adjoin F (S ∪ T) := begin rw intermediate_field.ext'_iff, change ↑(adjoin (adjoin F S) T) = _, apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split, { rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx }, { exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) }, { exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) }, { exact set.union_subset (subset_adjoin_of_subset_left _ (subset_adjoin _ _)) (subset_adjoin _ _) }, end @[simp] lemma adjoin_insert_adjoin (x : E) : adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) := le_antisymm (adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _), adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩)) (adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _))) /-- `F[S][T] = F[T][S]` -/ lemma adjoin_adjoin_comm (T : set E) : ↑(adjoin (adjoin F S) T) = (↑(adjoin (adjoin F T) S) : (intermediate_field F E)) := by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm] lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') : (adjoin F S).map f = adjoin F (f '' S) := begin ext x, show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔ x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S), rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp, f.comp_algebra_map], refl, end lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra := algebra.adjoin_le (subset_adjoin _ _) lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) : (adjoin F S).to_subalgebra = algebra.adjoin F S := le_antisymm (show adjoin F S ≤ { neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S}, from adjoin_le_iff.mpr (algebra.subset_adjoin)) (algebra_adjoin_le_adjoin _ _) lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E) (h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S := begin apply to_subalgebra_injective, rw h, refine (adjoin_eq_algebra_adjoin _ _ _).symm, intros x, convert K.inv_mem, rw ← h, refl end @[elab_as_eliminator] lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s) (Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p x⁻¹) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x)) ((algebra_map F E).map_one ▸ Hmap 1) Hadd Hneg Hinv Hmul /-- Variation on `set.insert` to enable good notation for adjoining elements to fields. Used to preferentially use `singleton` rather than `insert` when adjoining one element. -/ --this definition of notation is courtesy of Kyle Miller on zulip class insert {α : Type*} (s : set α) := (insert : α → set α) @[priority 1000] instance insert_empty {α : Type*} : insert (∅ : set α) := { insert := λ x, @singleton _ _ set.has_singleton x } @[priority 900] instance insert_nonempty {α : Type*} (s : set α) : insert s := { insert := λ x, set.insert x s } notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l section adjoin_simple variables (α : E) lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ := subset_adjoin F {α} (set.mem_singleton α) /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩ @[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl lemma adjoin_simple_adjoin_simple (β : E) : ↑F⟮α⟯⟮β⟯ = F⟮α, β⟯ := adjoin_adjoin_left _ _ _ lemma adjoin_simple_comm (β : E) : ↑F⟮α⟯⟮β⟯ = (↑F⟮β⟯⟮α⟯ : intermediate_field F E) := adjoin_adjoin_comm _ _ _ -- TODO: develop the API for `subalgebra.is_field_of_algebraic` so it can be used here lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) : (F⟮α⟯).to_subalgebra = algebra.adjoin F {α} := begin apply adjoin_eq_algebra_adjoin, intros x hx, by_cases x = 0, { rw [h, inv_zero], exact subalgebra.zero_mem (algebra.adjoin F {α}) }, let ϕ := alg_equiv.adjoin_singleton_equiv_adjoin_root_minimal_polynomial F α hα, haveI := minimal_polynomial.irreducible hα, suffices : ϕ ⟨x, hx⟩ * (ϕ ⟨x, hx⟩)⁻¹ = 1, { convert subtype.mem (ϕ.symm (ϕ ⟨x, hx⟩)⁻¹), refine (eq_inv_of_mul_right_eq_one _).symm, apply_fun ϕ.symm at this, rw [alg_equiv.map_one, alg_equiv.map_mul, alg_equiv.symm_apply_apply] at this, rw [←subsemiring.coe_one, ←this, subsemiring.coe_mul, subtype.coe_mk] }, rw mul_inv_cancel (mt (λ key, _) h), rw ← ϕ.map_zero at key, change ↑(⟨x, hx⟩ : algebra.adjoin F {α}) = _, rw [ϕ.injective key, submodule.coe_zero] end end adjoin_simple end adjoin_def section adjoin_intermediate_field_lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E} @[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) := by { rw [eq_bot_iff, adjoin_le_iff], refl, } @[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) := by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff } @[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥) @[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (one_mem ⊥) @[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) @[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) section adjoin_dim open finite_dimensional vector_space variables {K L : intermediate_field F E} @[simp] lemma dim_eq_one_iff : dim F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra, subalgebra.dim_eq_one_iff, bot_to_subalgebra] @[simp] lemma findim_eq_one_iff : findim F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← findim_eq_findim_subalgebra, subalgebra.findim_eq_one_iff, bot_to_subalgebra] lemma dim_adjoin_eq_one_iff : dim F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans dim_eq_one_iff adjoin_eq_bot_iff lemma dim_adjoin_simple_eq_one_iff : dim F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff } lemma findim_adjoin_eq_one_iff : findim F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans findim_eq_one_iff adjoin_eq_bot_iff lemma findim_adjoin_simple_eq_one_iff : findim F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw [findim_adjoin_eq_one_iff], exact set.singleton_subset_iff } /-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, dim F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact dim_adjoin_simple_eq_one_iff.mp (h x), end lemma bot_eq_top_of_findim_adjoin_eq_one (h : ∀ x : E, findim F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact findim_adjoin_simple_eq_one_iff.mp (h x), end lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, dim F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h) lemma subsingleton_of_findim_adjoin_eq_one (h : ∀ x : E, findim F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_findim_adjoin_eq_one h) /-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_findim_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, findim F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ := begin apply bot_eq_top_of_findim_adjoin_eq_one, exact λ x, by linarith [h x, show 0 < findim F F⟮x⟯, from findim_pos], end lemma subsingleton_of_findim_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, findim F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_findim_adjoin_le_one h) end adjoin_dim end adjoin_intermediate_field_lattice section adjoin_integral_element variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] {α : E} variables {K : Type*} [field K] [algebra F K] lemma aeval_gen_minimal_polynomial (h : is_integral F α) : polynomial.aeval (adjoin_simple.gen F α) (minimal_polynomial h) = 0 := begin ext, convert minimal_polynomial.aeval h, conv in (polynomial.aeval α) { rw [← adjoin_simple.algebra_map_gen F α] }, exact is_scalar_tower.algebra_map_aeval F F⟮α⟯ E _ _ end /-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/ noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) : adjoin_root (minimal_polynomial h) ≃ₐ[F] F⟮α⟯ := alg_equiv.of_bijective (alg_hom.mk (adjoin_root.lift (algebra_map F F⟮α⟯) (adjoin_simple.gen F α) (aeval_gen_minimal_polynomial F h)) (ring_hom.map_one _) (λ x y, ring_hom.map_mul _ x y) (ring_hom.map_zero _) (λ x y, ring_hom.map_add _ x y) (by { exact λ _, adjoin_root.lift_of })) (begin set f := adjoin_root.lift _ _ (aeval_gen_minimal_polynomial F h), haveI := minimal_polynomial.irreducible h, split, { exact ring_hom.injective f }, { suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f), { exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy.2⟩) }, exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy, ⟨y, ⟨subfield.mem_top y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩⟩)) (set.singleton_subset_iff.mpr ⟨adjoin_root.root (minimal_polynomial h), ⟨subfield.mem_top (adjoin_root.root (minimal_polynomial h)), by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩⟩)) } end) lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) : adjoin_root_equiv_adjoin F h (adjoin_root.root (minimal_polynomial h)) = adjoin_simple.gen F α := begin refine adjoin_root.lift_root, { exact minimal_polynomial h }, { exact aeval_gen_minimal_polynomial F h } end /-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots of `minimal_polynomial α` in `K`. -/ noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) : (F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minimal_polynomial h).map (algebra_map F K)).roots} := let ϕ := adjoin_root_equiv_adjoin F h, swap1 : (F⟮α⟯ →ₐ[F] K) ≃ (adjoin_root (minimal_polynomial h) →ₐ[F] K) := { to_fun := λ f, f.comp ϕ.to_alg_hom, inv_fun := λ f, f.comp ϕ.symm.to_alg_hom, left_inv := λ _, by { ext, simp only [alg_equiv.coe_alg_hom, alg_equiv.to_alg_hom_eq_coe, alg_hom.comp_apply, alg_equiv.apply_symm_apply]}, right_inv := λ _, by { ext, simp only [alg_equiv.symm_apply_apply, alg_equiv.coe_alg_hom, alg_equiv.to_alg_hom_eq_coe, alg_hom.comp_apply] } }, swap2 := adjoin_root.equiv F K (minimal_polynomial h) (minimal_polynomial.ne_zero h) in swap1.trans swap2 /-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/ noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) : fintype (F⟮α⟯ →ₐ[F] K) := fintype.of_equiv _ (alg_hom_adjoin_integral_equiv F h).symm lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minimal_polynomial h).separable) (h_splits : (minimal_polynomial h).splits (algebra_map F K)) : @fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) = (minimal_polynomial h).nat_degree := begin let s := ((minimal_polynomial h).map (algebra_map F K)).roots.to_finset, have H := λ x, multiset.mem_to_finset, rw [fintype.card_congr (alg_hom_adjoin_integral_equiv F h), fintype.card_of_subtype s H, polynomial.nat_degree_eq_card_roots h_splits, multiset.to_finset_card_of_nodup], exact polynomial.nodup_roots ((polynomial.separable_map (algebra_map F K)).mpr h_sep), end end adjoin_integral_element section induction variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] /-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that `intermediate_field.adjoin F t = S`. -/ def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg := ⟨t, rfl⟩ theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : intermediate_field F E).fg := ⟨∅, adjoin_empty F E⟩ lemma fg_of_fg_to_subalgebra (S : intermediate_field F E) (h : S.to_subalgebra.fg) : S.fg := begin cases h with t ht, exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩ end lemma fg_of_noetherian (S : intermediate_field F E) [is_noetherian F E] : S.fg := S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P ↑K⟮x⟯) : P (adjoin F ↑S) := begin apply finset.induction_on' S, { exact base }, { intros a s h1 _ _ h4, rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left], exact ih (adjoin F s) a h1 h4 } end lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) (hK : K.fg) : P K := begin obtain ⟨S, rfl⟩ := hK, exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK), end lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) : P K := induction_on_adjoin_fg P base ih K K.fg_of_noetherian end induction end intermediate_field
e0af5d969b6d30671ca95aa6587010290b13e2bb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/sigmaprec.lean
45f3db8fb78bf060e2dc9266f681ae9a2bd61c47
[ "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
140
lean
def f1 : Nat × Bool → Nat | _ => 0 def f2 : (α : Type) × α × α → Nat | _ => 0 def f3 : (x : Nat) × Bool → Nat | _ => 0
696fb62a874cd8d984e215a5ed552d915adf44ab
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/advanced_proposition/10.lean
f24dbf18452414917ba84bdf3ab7e97a7e28a7bd
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
148
lean
lemma contra (P Q : Prop) : (P ∧ ¬ P) → Q := begin -- fine, I'll play along intro h, cases h with hp hnp, exfalso, exact hnp hp, end
6f3c94431be4d18b094db034f6ce94793ff6747d
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/matchEqsBug.lean
e69b414c2d9d04258b83f591bbd1f5762414efeb
[ "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
689
lean
import Lean syntax (name := test) "test%" ident : command open Lean.Elab open Lean.Elab.Command @[commandElab test] def elabTest : CommandElab := fun stx => do let id ← resolveGlobalConstNoOverloadWithInfo stx[1] liftTermElabM do IO.println (repr (← Lean.Meta.Match.getEquationsFor id)) return () def f (x : List Nat) : Nat := match x with | [] => 1 | [a] => 2 | _ => 3 def g (x : Unit) (y : Bool) : Unit := match x, y with | _, true => () | x, _ => x set_option trace.Meta.Match.matchEqs true test% f.match_1 #check f.match_1.splitter def g.match_1.splitter := 4 test% g.match_1 #check g.match_1.eq_1 #check g.match_1.eq_2 #check g.match_1.splitter
9b8e43c50b524208aed8b2d1efa5f1563676ced1
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/order/absolute_value.lean
906537205350e1b63788d87769ee84a658edb270
[ "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
11,420
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Anne Baanen -/ import algebra.group_with_zero.units.lemmas import algebra.order.field.defs import algebra.order.hom.basic import algebra.order.ring.abs import algebra.ring.commute import algebra.ring.regular /-! # Absolute values > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a bundled type of absolute values `absolute_value R S`. ## Main definitions * `absolute_value R S` is the type of absolute values on `R` mapping to `S`. * `absolute_value.abs` is the "standard" absolute value on `S`, mapping negative `x` to `-x`. * `absolute_value.to_monoid_with_zero_hom`: absolute values mapping to a linear ordered field preserve `0`, `*` and `1` * `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val -/ /-- `absolute_value R S` is the type of absolute values on `R` mapping to `S`: the maps that preserve `*`, are nonnegative, positive definite and satisfy the triangle equality. -/ structure absolute_value (R S : Type*) [semiring R] [ordered_semiring S] extends R →ₙ* S := (nonneg' : ∀ x, 0 ≤ to_fun x) (eq_zero' : ∀ x, to_fun x = 0 ↔ x = 0) (add_le' : ∀ x y, to_fun (x + y) ≤ to_fun x + to_fun y) namespace absolute_value attribute [nolint doc_blame] absolute_value.to_mul_hom initialize_simps_projections absolute_value (to_mul_hom_to_fun → apply) section ordered_semiring section semiring variables {R S : Type*} [semiring R] [ordered_semiring S] (abv : absolute_value R S) instance zero_hom_class : zero_hom_class (absolute_value R S) R S := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_zero := λ f, (f.eq_zero' _).2 rfl } instance mul_hom_class : mul_hom_class (absolute_value R S) R S := { map_mul := λ f, f.map_mul' ..absolute_value.zero_hom_class } instance nonneg_hom_class : nonneg_hom_class (absolute_value R S) R S := { map_nonneg := λ f, f.nonneg', ..absolute_value.zero_hom_class } instance subadditive_hom_class : subadditive_hom_class (absolute_value R S) R S := { map_add_le_add := λ f, f.add_le', ..absolute_value.zero_hom_class } @[simp] lemma coe_mk (f : R →ₙ* S) {h₁ h₂ h₃} : ((absolute_value.mk f h₁ h₂ h₃) : R → S) = f := rfl @[ext] lemma ext ⦃f g : absolute_value R S⦄ : (∀ x, f x = g x) → f = g := fun_like.ext _ _ /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (absolute_value R S) (λ f, R → S) := fun_like.has_coe_to_fun @[simp] lemma coe_to_mul_hom : ⇑abv.to_mul_hom = abv := rfl protected theorem nonneg (x : R) : 0 ≤ abv x := abv.nonneg' x @[simp] protected theorem eq_zero {x : R} : abv x = 0 ↔ x = 0 := abv.eq_zero' x protected theorem add_le (x y : R) : abv (x + y) ≤ abv x + abv y := abv.add_le' x y @[simp] protected theorem map_mul (x y : R) : abv (x * y) = abv x * abv y := abv.map_mul' x y protected theorem ne_zero_iff {x : R} : abv x ≠ 0 ↔ x ≠ 0 := abv.eq_zero.not protected theorem pos {x : R} (hx : x ≠ 0) : 0 < abv x := lt_of_le_of_ne (abv.nonneg x) (ne.symm $ mt abv.eq_zero.mp hx) @[simp] protected theorem pos_iff {x : R} : 0 < abv x ↔ x ≠ 0 := ⟨λ h₁, mt abv.eq_zero.mpr h₁.ne', abv.pos⟩ protected theorem ne_zero {x : R} (hx : x ≠ 0) : abv x ≠ 0 := (abv.pos hx).ne' theorem map_one_of_is_regular (h : is_left_regular (abv 1)) : abv 1 = 1 := h $ by simp [←abv.map_mul] @[simp] protected theorem map_zero : abv 0 = 0 := abv.eq_zero.2 rfl end semiring section ring variables {R S : Type*} [ring R] [ordered_semiring S] (abv : absolute_value R S) protected lemma sub_le (a b c : R) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg, add_assoc] using abv.add_le (a - b) (b - c) @[simp] lemma map_sub_eq_zero_iff (a b : R) : abv (a - b) = 0 ↔ a = b := abv.eq_zero.trans sub_eq_zero end ring end ordered_semiring section ordered_ring section semiring section is_domain -- all of these are true for `no_zero_divisors S`; but it doesn't work smoothly with the -- `is_domain`/`cancel_monoid_with_zero` API variables {R S : Type*} [semiring R] [ordered_ring S] (abv : absolute_value R S) variables [is_domain S] [nontrivial R] @[simp] protected theorem map_one : abv 1 = 1 := abv.map_one_of_is_regular ((is_regular_of_ne_zero $ abv.ne_zero one_ne_zero).left) instance : monoid_with_zero_hom_class (absolute_value R S) R S := { map_zero := λ f, f.map_zero, map_one := λ f, f.map_one, ..absolute_value.mul_hom_class } /-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*`, `0` and `1`. -/ def to_monoid_with_zero_hom : R →*₀ S := abv @[simp] lemma coe_to_monoid_with_zero_hom : ⇑abv.to_monoid_with_zero_hom = abv := rfl /-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*` and `1`. -/ def to_monoid_hom : R →* S := abv @[simp] lemma coe_to_monoid_hom : ⇑abv.to_monoid_hom = abv := rfl @[simp] protected lemma map_pow (a : R) (n : ℕ) : abv (a ^ n) = abv a ^ n := abv.to_monoid_hom.map_pow a n end is_domain end semiring section ring variables {R S : Type*} [ring R] [ordered_ring S] (abv : absolute_value R S) protected lemma le_sub (a b : R) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv.add_le (a - b) b end ring end ordered_ring section ordered_comm_ring variables {R S : Type*} [ring R] [ordered_comm_ring S] (abv : absolute_value R S) variables [no_zero_divisors S] @[simp] protected theorem map_neg (a : R) : abv (-a) = abv a := begin by_cases ha : a = 0, { simp [ha] }, refine (mul_self_eq_mul_self_iff.mp (by rw [← abv.map_mul, neg_mul_neg, abv.map_mul])).resolve_right _, exact ((neg_lt_zero.mpr (abv.pos ha)).trans (abv.pos (neg_ne_zero.mpr ha))).ne' end protected theorem map_sub (a b : R) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv.map_neg] end ordered_comm_ring instance {R S : Type*} [ring R] [ordered_comm_ring S] [nontrivial R] [is_domain S] : mul_ring_norm_class (absolute_value R S) R S := { map_neg_eq_map := λ f, f.map_neg, eq_zero_of_map_eq_zero := λ f a, f.eq_zero.1, ..absolute_value.subadditive_hom_class, ..absolute_value.monoid_with_zero_hom_class } section linear_ordered_ring variables {R S : Type*} [semiring R] [linear_ordered_ring S] (abv : absolute_value R S) /-- `absolute_value.abs` is `abs` as a bundled `absolute_value`. -/ @[simps] protected def abs : absolute_value S S := { to_fun := abs, nonneg' := abs_nonneg, eq_zero' := λ _, abs_eq_zero, add_le' := abs_add, map_mul' := abs_mul } instance : inhabited (absolute_value S S) := ⟨absolute_value.abs⟩ end linear_ordered_ring section linear_ordered_comm_ring variables {R S : Type*} [ring R] [linear_ordered_comm_ring S] (abv : absolute_value R S) lemma abs_abv_sub_le_abv_sub (a b : R) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨abv.le_sub _ _, by rw abv.map_sub; apply abv.le_sub⟩ end linear_ordered_comm_ring end absolute_value /-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and multiplicative. See also the type `absolute_value` which represents a bundled version of absolute values. -/ class is_absolute_value {S} [ordered_semiring S] {R} [semiring R] (f : R → S) : 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 section ordered_semiring variables {S : Type*} [ordered_semiring S] variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv] /-- A bundled absolute value is an absolute value. -/ instance _root_.absolute_value.is_absolute_value (abv : absolute_value R S) : is_absolute_value abv := { abv_nonneg := abv.nonneg, abv_eq_zero := λ _, abv.eq_zero, abv_add := abv.add_le, abv_mul := abv.map_mul } /-- Convert an unbundled `is_absolute_value` to a bundled `absolute_value`. -/ @[simps] def to_absolute_value : absolute_value R S := { to_fun := abv, add_le' := abv_add abv, eq_zero' := λ _, abv_eq_zero abv, nonneg' := abv_nonneg abv, map_mul' := abv_mul abv } theorem abv_zero : abv 0 = 0 := (to_absolute_value abv).map_zero theorem abv_pos {a : R} : 0 < abv a ↔ a ≠ 0 := (to_absolute_value abv).pos_iff end ordered_semiring section linear_ordered_ring variables {S : Type*} [linear_ordered_ring S] instance abs_is_absolute_value : is_absolute_value (abs : S → S) := absolute_value.abs.is_absolute_value end linear_ordered_ring section ordered_ring variables {S : Type*} [ordered_ring S] section semiring variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv] variables [is_domain S] theorem abv_one [nontrivial R] : abv 1 = 1 := (to_absolute_value abv).map_one /-- `abv` as a `monoid_with_zero_hom`. -/ def abv_hom [nontrivial R] : R →*₀ S := (to_absolute_value abv).to_monoid_with_zero_hom lemma abv_pow [nontrivial R] (abv : R → S) [is_absolute_value abv] (a : R) (n : ℕ) : abv (a ^ n) = abv a ^ n := (to_absolute_value abv).map_pow a n end semiring section ring variables {R : Type*} [ring R] (abv : R → S) [is_absolute_value abv] lemma abv_sub_le (a b c : R) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : R) : abv a - abv b ≤ abv (a - b) := (to_absolute_value abv).le_sub a b end ring end ordered_ring section ordered_comm_ring variables {S : Type*} [ordered_comm_ring S] section ring variables {R : Type*} [ring R] (abv : R → S) [is_absolute_value abv] variables [no_zero_divisors S] theorem abv_neg (a : R) : abv (-a) = abv a := (to_absolute_value abv).map_neg a theorem abv_sub (a b : R) : abv (a - b) = abv (b - a) := (to_absolute_value abv).map_sub a b end ring end ordered_comm_ring section linear_ordered_comm_ring variables {S : Type*} [linear_ordered_comm_ring S] section ring variables {R : Type*} [ring R] (abv : R → S) [is_absolute_value abv] lemma abs_abv_sub_le_abv_sub (a b : R) : abs (abv a - abv b) ≤ abv (a - b) := (to_absolute_value abv).abs_abv_sub_le_abv_sub a b end ring end linear_ordered_comm_ring section linear_ordered_field variables {S : Type*} [linear_ordered_semifield S] section semiring variables {R : Type*} [semiring R] [nontrivial R] (abv : R → S) [is_absolute_value abv] lemma abv_one' : abv 1 = 1 := (to_absolute_value abv).map_one_of_is_regular $ (is_regular_of_ne_zero $ (to_absolute_value abv).ne_zero one_ne_zero).left /-- An absolute value as a monoid with zero homomorphism, assuming the target is a semifield. -/ def abv_hom' : R →*₀ S := ⟨abv, abv_zero abv, abv_one' abv, abv_mul abv⟩ end semiring section division_semiring variables {R : Type*} [division_semiring R] (abv : R → S) [is_absolute_value abv] theorem abv_inv (a : R) : abv a⁻¹ = (abv a)⁻¹ := map_inv₀ (abv_hom' abv) a theorem abv_div (a b : R) : abv (a / b) = abv a / abv b := map_div₀ (abv_hom' abv) a b end division_semiring end linear_ordered_field end is_absolute_value
d65f034aa1d41a1a5087c5382a6fdb977a05f098
4727251e0cd73359b15b664c3170e5d754078599
/src/data/qpf/multivariate/constructions/prj.lean
e27a1be1f87000d1ffb35cdab02078a4da732cce
[ "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,523
lean
/- Copyright (c) 2020 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.functor.multivariate import data.qpf.multivariate.basic /-! Projection functors are QPFs. The `n`-ary projection functors on `i` is an `n`-ary functor `F` such that `F (α₀..αᵢ₋₁, αᵢ, αᵢ₊₁..αₙ₋₁) = αᵢ` -/ universes u v namespace mvqpf open_locale mvfunctor variables {n : ℕ} (i : fin2 n) /-- The projection `i` functor -/ def prj (v : typevec.{u} n) : Type u := v i instance prj.inhabited {v : typevec.{u} n} [inhabited (v i)] : inhabited (prj i v) := ⟨ (default : v i) ⟩ /-- `map` on functor `prj i` -/ def prj.map ⦃α β : typevec n⦄ (f : α ⟹ β) : prj i α → prj i β := f _ instance prj.mvfunctor : mvfunctor (prj i) := { map := prj.map i } /-- Polynomial representation of the projection functor -/ def prj.P : mvpfunctor.{u} n := { A := punit, B := λ _ j, ulift $ plift $ i = j } /-- Abstraction function of the `qpf` instance -/ def prj.abs ⦃α : typevec n⦄ : (prj.P i).obj α → prj i α | ⟨x, f⟩ := f _ ⟨⟨rfl⟩⟩ /-- Representation function of the `qpf` instance -/ def prj.repr ⦃α : typevec n⦄ : prj i α → (prj.P i).obj α := λ x : α i, ⟨ ⟨ ⟩, λ j ⟨⟨h⟩⟩, (h.rec x : α j) ⟩ instance prj.mvqpf : mvqpf (prj i) := { P := prj.P i, abs := prj.abs i, repr := prj.repr i, abs_repr := by intros; refl, abs_map := by intros; cases p; refl } end mvqpf
cac28b96697a4f57fc8e48127ed957061c45933f
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/dynamics/periodic_pts.lean
56cb4e182b1823285fcf72bf152a1ca499bd85e1
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,585
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import dynamics.fixed_points.basic import data.set.lattice import data.pnat.basic /-! # Periodic points A point `x : α` is a periodic point of `f : α → α` of period `n` if `f^[n] x = x`. ## Main definitions * `is_periodic_pt f n x` : `x` is a periodic point of `f` of period `n`, i.e. `f^[n] x = x`. We do not require `n > 0` in the definition. * `pts_of_period f n` : the set `{x | is_periodic_pt f n x}`. Note that `n` is not required to be the minimal period of `x`. * `periodic_pts f` : the set of all periodic points of `f`. * `minimal_period f x` : the minimal period of a point `x` under an endomorphism `f` or zero if `x` is not a periodic point of `f`. ## Main statements We provide “dot syntax”-style operations on terms of the form `h : is_periodic_pt f n x` including arithmetic operations on `n` and `h.map (hg : semiconj_by g f f')`. We also prove that `f` is bijective on each set `pts_of_period f n` and on `periodic_pts f`. Finally, we prove that `x` is a periodic point of `f` of period `n` if and only if `minimal_period f x | n`. ## References * https://en.wikipedia.org/wiki/Periodic_point -/ open set namespace function variables {α : Type*} {β : Type*} {f fa : α → α} {fb : β → β} {x y : α} {m n : ℕ} /-- A point `x` is a periodic point of `f : α → α` of period `n` if `f^[n] x = x`. Note that we do not require `0 < n` in this definition. Many theorems about periodic points need this assumption. -/ def is_periodic_pt (f : α → α) (n : ℕ) (x : α) := is_fixed_pt (f^[n]) x /-- A fixed point of `f` is a periodic point of `f` of any prescribed period. -/ lemma is_fixed_pt.is_periodic_pt (hf : is_fixed_pt f x) (n : ℕ) : is_periodic_pt f n x := hf.iterate n /-- For the identity map, all points are periodic. -/ lemma is_periodic_id (n : ℕ) (x : α) : is_periodic_pt id n x := (is_fixed_pt_id x).is_periodic_pt n /-- Any point is a periodic point of period `0`. -/ lemma is_periodic_pt_zero (f : α → α) (x : α) : is_periodic_pt f 0 x := is_fixed_pt_id x namespace is_periodic_pt instance [decidable_eq α] {f : α → α} {n : ℕ} {x : α} : decidable (is_periodic_pt f n x) := is_fixed_pt.decidable protected lemma is_fixed_pt (hf : is_periodic_pt f n x) : is_fixed_pt (f^[n]) x := hf protected lemma map (hx : is_periodic_pt fa n x) {g : α → β} (hg : semiconj g fa fb) : is_periodic_pt fb n (g x) := hx.map (hg.iterate_right n) lemma apply_iterate (hx : is_periodic_pt f n x) (m : ℕ) : is_periodic_pt f n (f^[m] x) := hx.map $ commute.iterate_self f m protected lemma apply (hx : is_periodic_pt f n x) : is_periodic_pt f n (f x) := hx.apply_iterate 1 protected lemma add (hn : is_periodic_pt f n x) (hm : is_periodic_pt f m x) : is_periodic_pt f (n + m) x := by { rw [is_periodic_pt, iterate_add], exact hn.comp hm } lemma left_of_add (hn : is_periodic_pt f (n + m) x) (hm : is_periodic_pt f m x) : is_periodic_pt f n x := by { rw [is_periodic_pt, iterate_add] at hn, exact hn.left_of_comp hm } lemma right_of_add (hn : is_periodic_pt f (n + m) x) (hm : is_periodic_pt f n x) : is_periodic_pt f m x := by { rw add_comm at hn, exact hn.left_of_add hm } protected lemma sub (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (m - n) x := begin cases le_total n m with h h, { refine left_of_add _ hn, rwa [nat.sub_add_cancel h] }, { rw [nat.sub_eq_zero_of_le h], apply is_periodic_pt_zero } end protected lemma mul_const (hm : is_periodic_pt f m x) (n : ℕ) : is_periodic_pt f (m * n) x := by simp only [is_periodic_pt, iterate_mul, hm.is_fixed_pt.iterate n] protected lemma const_mul (hm : is_periodic_pt f m x) (n : ℕ) : is_periodic_pt f (n * m) x := by simp only [mul_comm n, hm.mul_const n] lemma trans_dvd (hm : is_periodic_pt f m x) {n : ℕ} (hn : m ∣ n) : is_periodic_pt f n x := let ⟨k, hk⟩ := hn in hk.symm ▸ hm.mul_const k protected lemma iterate (hf : is_periodic_pt f n x) (m : ℕ) : is_periodic_pt (f^[m]) n x := begin rw [is_periodic_pt, ← iterate_mul, mul_comm, iterate_mul], exact hf.is_fixed_pt.iterate m end protected lemma mod (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (m % n) x := begin rw [← nat.mod_add_div m n] at hm, exact hm.left_of_add (hn.mul_const _) end protected lemma gcd (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (m.gcd n) x := begin revert hm hn, refine nat.gcd.induction m n (λ n h0 hn, _) (λ m n hm ih hm hn, _), { rwa [nat.gcd_zero_left], }, { rw [nat.gcd_rec], exact ih (hn.mod hm) hm } end /-- If `f` sends two periodic points `x` and `y` of the same positive period to the same point, then `x = y`. For a similar statement about points of different periods see `eq_of_apply_eq`. -/ lemma eq_of_apply_eq_same (hx : is_periodic_pt f n x) (hy : is_periodic_pt f n y) (hn : 0 < n) (h : f x = f y) : x = y := by rw [← hx.eq, ← hy.eq, ← iterate_pred_comp_of_pos f hn, comp_app, h] /-- If `f` sends two periodic points `x` and `y` of positive periods to the same point, then `x = y`. -/ lemma eq_of_apply_eq (hx : is_periodic_pt f m x) (hy : is_periodic_pt f n y) (hm : 0 < m) (hn : 0 < n) (h : f x = f y) : x = y := (hx.mul_const n).eq_of_apply_eq_same (hy.const_mul m) (mul_pos hm hn) h end is_periodic_pt /-- The set of periodic points of a given (possibly non-minimal) period. -/ def pts_of_period (f : α → α) (n : ℕ) : set α := {x : α | is_periodic_pt f n x} @[simp] lemma mem_pts_of_period : x ∈ pts_of_period f n ↔ is_periodic_pt f n x := iff.rfl lemma semiconj.maps_to_pts_of_period {g : α → β} (h : semiconj g fa fb) (n : ℕ) : maps_to g (pts_of_period fa n) (pts_of_period fb n) := (h.iterate_right n).maps_to_fixed_pts lemma bij_on_pts_of_period (f : α → α) {n : ℕ} (hn : 0 < n) : bij_on f (pts_of_period f n) (pts_of_period f n) := ⟨(commute.refl f).maps_to_pts_of_period n, λ x hx y hy hxy, hx.eq_of_apply_eq_same hy hn hxy, λ x hx, ⟨f^[n.pred] x, hx.apply_iterate _, by rw [← comp_app f, comp_iterate_pred_of_pos f hn, hx.eq]⟩⟩ lemma directed_pts_of_period_pnat (f : α → α) : directed (⊆) (λ n : ℕ+, pts_of_period f n) := λ m n, ⟨m * n, λ x hx, hx.mul_const n, λ x hx, hx.const_mul m⟩ /-- The set of periodic points of a map `f : α → α`. -/ def periodic_pts (f : α → α) : set α := {x : α | ∃ n > 0, is_periodic_pt f n x} lemma mk_mem_periodic_pts (hn : 0 < n) (hx : is_periodic_pt f n x) : x ∈ periodic_pts f := ⟨n, hn, hx⟩ lemma mem_periodic_pts : x ∈ periodic_pts f ↔ ∃ n > 0, is_periodic_pt f n x := iff.rfl variable (f) lemma bUnion_pts_of_period : (⋃ n > 0, pts_of_period f n) = periodic_pts f := set.ext $ λ x, by simp [mem_periodic_pts] lemma Union_pnat_pts_of_period : (⋃ n : ℕ+, pts_of_period f n) = periodic_pts f := supr_subtype.trans $ bUnion_pts_of_period f lemma bij_on_periodic_pts : bij_on f (periodic_pts f) (periodic_pts f) := Union_pnat_pts_of_period f ▸ bij_on_Union_of_directed (directed_pts_of_period_pnat f) (λ i, bij_on_pts_of_period f i.pos) variable {f} lemma semiconj.maps_to_periodic_pts {g : α → β} (h : semiconj g fa fb) : maps_to g (periodic_pts fa) (periodic_pts fb) := λ x ⟨n, hn, hx⟩, ⟨n, hn, hx.map h⟩ open_locale classical noncomputable theory /-- Minimal period of a point `x` under an endomorphism `f`. If `x` is not a periodic point of `f`, then `minimal_period f x = 0`. -/ def minimal_period (f : α → α) (x : α) := if h : x ∈ periodic_pts f then nat.find h else 0 lemma is_periodic_pt_minimal_period (f : α → α) (x : α) : is_periodic_pt f (minimal_period f x) x := begin delta minimal_period, split_ifs with hx, { exact (nat.find_spec hx).snd }, { exact is_periodic_pt_zero f x } end lemma minimal_period_pos_of_mem_periodic_pts (hx : x ∈ periodic_pts f) : 0 < minimal_period f x := by simp only [minimal_period, dif_pos hx, gt_iff_lt.1 (nat.find_spec hx).fst] lemma is_periodic_pt.minimal_period_pos (hn : 0 < n) (hx : is_periodic_pt f n x) : 0 < minimal_period f x := minimal_period_pos_of_mem_periodic_pts $ mk_mem_periodic_pts hn hx lemma minimal_period_pos_iff_mem_periodic_pts : 0 < minimal_period f x ↔ x ∈ periodic_pts f := ⟨not_imp_not.1 $ λ h, by simp only [minimal_period, dif_neg h, lt_irrefl 0, not_false_iff], minimal_period_pos_of_mem_periodic_pts⟩ lemma is_periodic_pt.minimal_period_le (hn : 0 < n) (hx : is_periodic_pt f n x) : minimal_period f x ≤ n := begin rw [minimal_period, dif_pos (mk_mem_periodic_pts hn hx)], exact nat.find_min' (mk_mem_periodic_pts hn hx) ⟨hn, hx⟩ end lemma is_periodic_pt.eq_zero_of_lt_minimal_period (hx : is_periodic_pt f n x) (hn : n < minimal_period f x) : n = 0 := eq.symm $ (eq_or_lt_of_le $ n.zero_le).resolve_right $ λ hn0, not_lt.2 (hx.minimal_period_le hn0) hn lemma is_periodic_pt.minimal_period_dvd (hx : is_periodic_pt f n x) : minimal_period f x ∣ n := (eq_or_lt_of_le $ n.zero_le).elim (λ hn0, hn0 ▸ dvd_zero _) $ λ hn0, (nat.dvd_iff_mod_eq_zero _ _).2 $ (hx.mod $ is_periodic_pt_minimal_period f x).eq_zero_of_lt_minimal_period $ nat.mod_lt _ $ hx.minimal_period_pos hn0 lemma is_periodic_pt_iff_minimal_period_dvd : is_periodic_pt f n x ↔ minimal_period f x ∣ n := ⟨is_periodic_pt.minimal_period_dvd, λ h, (is_periodic_pt_minimal_period f x).trans_dvd h⟩ end function
a8475839ff99472ee36e24c915749343a97d305f
4727251e0cd73359b15b664c3170e5d754078599
/src/data/real/golden_ratio.lean
e3e6e5209b3ecfa001dd0b5f3f6485be4136f5cc
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,579
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Alexey Soloyev, Junyan Xu -/ import data.real.irrational import data.nat.fib import data.fin.vec_notation import tactic.ring_exp import algebra.linear_recurrence /-! # The golden ratio and its conjugate This file defines the golden ratio `φ := (1 + √5)/2` and its conjugate `ψ := (1 - √5)/2`, which are the two real roots of `X² - X - 1`. Along with various computational facts about them, we prove their irrationality, and we link them to the Fibonacci sequence by proving Binet's formula. -/ noncomputable theory /-- The golden ratio `φ := (1 + √5)/2`. -/ @[reducible] def golden_ratio := (1 + real.sqrt 5)/2 /-- The conjugate of the golden ratio `ψ := (1 - √5)/2`. -/ @[reducible] def golden_conj := (1 - real.sqrt 5)/2 localized "notation `φ` := golden_ratio" in real localized "notation `ψ` := golden_conj" in real /-- The inverse of the golden ratio is the opposite of its conjugate. -/ lemma inv_gold : φ⁻¹ = -ψ := begin have : 1 + real.sqrt 5 ≠ 0, from ne_of_gt (add_pos (by norm_num) $ real.sqrt_pos.mpr (by norm_num)), field_simp [sub_mul, mul_add], norm_num end /-- The opposite of the golden ratio is the inverse of its conjugate. -/ lemma inv_gold_conj : ψ⁻¹ = -φ := begin rw [inv_eq_iff_inv_eq, ← neg_inv, neg_eq_iff_neg_eq], exact inv_gold.symm, end @[simp] lemma gold_mul_gold_conj : φ * ψ = -1 := by {field_simp, rw ← sq_sub_sq, norm_num} @[simp] lemma gold_conj_mul_gold : ψ * φ = -1 := by {rw mul_comm, exact gold_mul_gold_conj} @[simp] lemma gold_add_gold_conj : φ + ψ = 1 := by {rw [golden_ratio, golden_conj], ring} lemma one_sub_gold_conj : 1 - φ = ψ := by linarith [gold_add_gold_conj] lemma one_sub_gold : 1 - ψ = φ := by linarith [gold_add_gold_conj] @[simp] lemma gold_sub_gold_conj : φ - ψ = real.sqrt 5 := by {rw [golden_ratio, golden_conj], ring} @[simp] lemma gold_sq : φ^2 = φ + 1 := begin rw [golden_ratio, ←sub_eq_zero], ring_exp, rw real.sq_sqrt; norm_num, end @[simp] lemma gold_conj_sq : ψ^2 = ψ + 1 := begin rw [golden_conj, ←sub_eq_zero], ring_exp, rw real.sq_sqrt; norm_num, end lemma gold_pos : 0 < φ := mul_pos (by apply add_pos; norm_num) $ inv_pos.2 zero_lt_two lemma gold_ne_zero : φ ≠ 0 := ne_of_gt gold_pos lemma one_lt_gold : 1 < φ := begin refine lt_of_mul_lt_mul_left _ (le_of_lt gold_pos), simp [← sq, gold_pos, zero_lt_one] end lemma gold_conj_neg : ψ < 0 := by linarith [one_sub_gold_conj, one_lt_gold] lemma gold_conj_ne_zero : ψ ≠ 0 := ne_of_lt gold_conj_neg lemma neg_one_lt_gold_conj : -1 < ψ := begin rw [neg_lt, ← inv_gold], exact inv_lt_one one_lt_gold, end /-! ## Irrationality -/ /-- The golden ratio is irrational. -/ theorem gold_irrational : irrational φ := begin have := nat.prime.irrational_sqrt (show nat.prime 5, by norm_num), have := this.rat_add 1, have := this.rat_mul (show (0.5 : ℚ) ≠ 0, by norm_num), convert this, field_simp end /-- The conjugate of the golden ratio is irrational. -/ theorem gold_conj_irrational : irrational ψ := begin have := nat.prime.irrational_sqrt (show nat.prime 5, by norm_num), have := this.rat_sub 1, have := this.rat_mul (show (0.5 : ℚ) ≠ 0, by norm_num), convert this, field_simp end /-! ## Links with Fibonacci sequence -/ section fibrec variables {α : Type*} [comm_semiring α] /-- The recurrence relation satisfied by the Fibonacci sequence. -/ def fib_rec : linear_recurrence α := { order := 2, coeffs := ![1, 1]} section poly open polynomial /-- The characteristic polynomial of `fib_rec` is `X² - (X + 1)`. -/ lemma fib_rec_char_poly_eq {β : Type*} [comm_ring β] : fib_rec.char_poly = X^2 - (X + (1 : polynomial β)) := begin rw [fib_rec, linear_recurrence.char_poly], simp [finset.sum_fin_eq_sum_range, finset.sum_range_succ', monomial_eq_smul_X] end end poly /-- As expected, the Fibonacci sequence is a solution of `fib_rec`. -/ lemma fib_is_sol_fib_rec : fib_rec.is_solution (λ x, x.fib : ℕ → α) := begin rw fib_rec, intros n, simp only, rw [nat.fib_add_two, add_comm], simp [finset.sum_fin_eq_sum_range, finset.sum_range_succ'], end /-- The geometric sequence `λ n, φ^n` is a solution of `fib_rec`. -/ lemma geom_gold_is_sol_fib_rec : fib_rec.is_solution (pow φ) := begin rw [fib_rec.geom_sol_iff_root_char_poly, fib_rec_char_poly_eq], simp [sub_eq_zero] end /-- The geometric sequence `λ n, ψ^n` is a solution of `fib_rec`. -/ lemma geom_gold_conj_is_sol_fib_rec : fib_rec.is_solution (pow ψ) := begin rw [fib_rec.geom_sol_iff_root_char_poly, fib_rec_char_poly_eq], simp [sub_eq_zero] end end fibrec /-- Binet's formula as a function equality. -/ theorem real.coe_fib_eq' : (λ n, nat.fib n : ℕ → ℝ) = λ n, (φ^n - ψ^n) / real.sqrt 5 := begin rw fib_rec.sol_eq_of_eq_init, { intros i hi, fin_cases hi, { simp }, { simp only [golden_ratio, golden_conj], ring_exp, rw mul_inv_cancel; norm_num } }, { exact fib_is_sol_fib_rec }, { ring_nf, exact (@fib_rec ℝ _).sol_space.sub_mem (submodule.smul_mem fib_rec.sol_space (real.sqrt 5)⁻¹ geom_gold_is_sol_fib_rec) (submodule.smul_mem fib_rec.sol_space (real.sqrt 5)⁻¹ geom_gold_conj_is_sol_fib_rec) } end /-- Binet's formula as a dependent equality. -/ theorem real.coe_fib_eq : ∀ n, (nat.fib n : ℝ) = (φ^n - ψ^n) / real.sqrt 5 := by rw [← function.funext_iff, real.coe_fib_eq']
92eefe1354ac98c370026553711b2f11ed0b9867
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/multiplicity.lean
078abe2f1443bf0164acf9789da68cae445f6be0
[ "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
11,876
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.big_operators.intervals import data.nat.bitwise import data.nat.log import data.nat.parity import ring_theory.int.basic /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power dividing a number) when applied to naturals, in particular calculating it for factorials and binomial coefficients. ## Multiplicity calculations * `nat.multiplicity_factorial`: Legendre's Theorem. The multiplicity of `p` in `n!` is `n/p + ... + n/p^b` for any `b` such that `n/p^(b + 1) = 0`. * `nat.multiplicity_factorial_mul`: The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. * `nat.multiplicity_choose`: The multiplicity of `p` in `n.choose k` is the number of carries when `k` and`n - k` are added in base `p`. ## Other declarations * `nat.multiplicity_eq_card_pow_dvd`: The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. * `nat.multiplicity_two_factorial_lt`: The multiplicity of `2` in `n!` is strictly less than `n`. * `nat.prime.multiplicity_something`: Specialization of `multiplicity.something` to a prime in the naturals. Avoids having to provide `p ≠ 1` and other trivialities, along with translating between `prime` and `nat.prime`. ## Tags Legendre, p-adic -/ open finset nat multiplicity open_locale big_operators nat namespace nat /-- The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. This set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log m n`. -/ lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm : m ≠ 1) (hn : 0 < n) (hb : log m n < b): multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card := calc multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm, hn⟩) + 1)).card : by simp ... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card : congr_arg coe $ congr_arg card $ finset.ext $ λ i, begin rw [mem_filter, mem_Ico, mem_Ico, lt_succ_iff, ←@enat.coe_le_coe i, enat.coe_get, ←pow_dvd_iff_le_multiplicity, and.right_comm], refine (and_iff_left_of_imp (λ h, _)).symm, cases m, { rw [zero_pow, zero_dvd_iff] at h, exact (hn.ne' h.2).elim, { exact h.1 } }, exact ((pow_le_iff_le_log (succ_lt_succ $ nat.pos_of_ne_zero $ succ_ne_succ.1 hm) hn).1 $ le_of_dvd hn h.2).trans_lt hb, end namespace prime lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 := multiplicity.one_right (prime_iff.mp hp).not_unit lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := multiplicity.mul $ prime_iff.mp hp lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) : multiplicity p (m ^ n) = n • (multiplicity p m) := multiplicity.pow $ prime_iff.mp hp lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 := multiplicity_self (prime_iff.mp hp).not_unit hp.ne_zero lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.ne_zero (prime_iff.mp hp).not_unit n /-- **Legendre's Theorem** The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed over the finset `Ico 1 b` where `b` is any bound greater than `log p n`. -/ lemma multiplicity_factorial {p : ℕ} (hp : p.prime) : ∀ {n b : ℕ}, log p n < b → multiplicity p n! = (∑ i in Ico 1 b, n / p ^ i : ℕ) | 0 b hb := by simp [Ico, hp.multiplicity_one] | (n+1) b hb := calc multiplicity p (n+1)! = multiplicity p n! + multiplicity p (n+1) : by rw [factorial_succ, hp.multiplicity_mul, add_comm] ... = (∑ i in Ico 1 b, n / p ^ i : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card : by rw [multiplicity_factorial ((log_le_log_of_le $ le_succ _).trans_lt hb), ← multiplicity_eq_card_pow_dvd hp.ne_one (succ_pos _) hb] ... = (∑ i in Ico 1 b, (n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) : by { rw [sum_add_distrib, sum_boole], simp } ... = (∑ i in Ico 1 b, (n + 1) / p ^ i : ℕ) : congr_arg coe $ finset.sum_congr rfl $ λ _ _, (succ_div _ _).symm /-- The multiplicity of `p` in `(p * (n + 1))!` is one more than the sum of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/ lemma multiplicity_factorial_mul_succ {n p : ℕ} (hp : p.prime) : multiplicity p (p * (n + 1))! = multiplicity p (p * n)! + multiplicity p (n + 1) + 1 := begin have hp' := prime_iff.mp hp, have h0 : 2 ≤ p := hp.two_le, have h1 : 1 ≤ p * n + 1 := nat.le_add_left _ _, have h2 : p * n + 1 ≤ p * (n + 1), linarith, have h3 : p * n + 1 ≤ p * (n + 1) + 1, linarith, have hm : multiplicity p (p * n)! ≠ ⊤, { rw [ne.def, eq_top_iff_not_finite, not_not, finite_nat_iff], exact ⟨hp.ne_one, factorial_pos _⟩ }, revert hm, have h4 : ∀ m ∈ Ico (p * n + 1) (p * (n + 1)), multiplicity p m = 0, { intros m hm, apply multiplicity_eq_zero_of_not_dvd, rw [← exists_lt_and_lt_iff_not_dvd _ (pos_iff_ne_zero.mpr hp.ne_zero)], rw [mem_Ico] at hm, exact ⟨n, lt_of_succ_le hm.1, hm.2⟩ }, simp_rw [← prod_Ico_id_eq_factorial, multiplicity.finset.prod hp', ← sum_Ico_consecutive _ h1 h3, add_assoc], intro h, rw [enat.add_left_cancel_iff h, sum_Ico_succ_top h2, multiplicity.mul hp', hp.multiplicity_self, sum_congr rfl h4, sum_const_zero, zero_add, add_comm (1 : enat)] end /-- The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. -/ lemma multiplicity_factorial_mul {n p : ℕ} (hp : p.prime) : multiplicity p (p * n)! = multiplicity p n! + n := begin induction n with n ih, { simp }, { simp only [succ_eq_add_one, multiplicity.mul, hp, prime_iff.mp hp, ih, multiplicity_factorial_mul_succ, ←add_assoc, nat.cast_one, nat.cast_add, factorial_succ], congr' 1, rw [add_comm, add_assoc] } end /-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/ lemma pow_dvd_factorial_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : log p n < b) : p ^ r ∣ n! ↔ r ≤ ∑ i in Ico 1 b, n / p ^ i := by rw [← enat.coe_le_coe, ← hp.multiplicity_factorial hbn, ← pow_dvd_iff_le_multiplicity] lemma multiplicity_factorial_le_div_pred {p : ℕ} (hp : p.prime) (n : ℕ) : multiplicity p n! ≤ (n/(p - 1) : ℕ) := begin rw [hp.multiplicity_factorial (lt_succ_self _), enat.coe_le_coe], exact nat.geom_sum_Ico_le hp.two_le _ _, end lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) : ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, k / p ^ i + ∑ i in finset.Ico 1 b, (n - k) / p ^ i + ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := calc ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, (k + (n - k)) / p ^ i : by simp only [add_tsub_cancel_of_le hkn] ... = ∑ i in finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i + if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) : by simp only [nat.add_div (pow_pos hp.pos _)] ... = _ : by simp [sum_add_distrib, sum_boole] /-- The multiplicity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p n`. -/ lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : log p n < b) : multiplicity p (choose n k) = ((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := have h₁ : multiplicity p (choose n k) + multiplicity p (k! * (n - k)!) = ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + multiplicity p (k! * (n - k)!), begin rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_factorial_mul_factorial hkn, hp.multiplicity_factorial hnb, hp.multiplicity_mul, hp.multiplicity_factorial ((log_le_log_of_le hkn).trans_lt hnb), hp.multiplicity_factorial (lt_of_le_of_lt (log_le_log_of_le tsub_le_self) hnb), multiplicity_choose_aux hp hkn], simp [add_comm], end, (enat.add_right_cancel_iff (enat.ne_top_iff_dom.2 $ by exact finite_nat_iff.2 ⟨ne_of_gt hp.one_lt, mul_pos (factorial_pos k) (factorial_pos (n - k))⟩)).1 h₁ /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) (n k : ℕ) : multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k := if hkn : n < k then by simp [choose_eq_zero_of_lt hkn] else if hk0 : k = 0 then by simp [hk0] else if hn0 : n = 0 then by cases k; simp [hn0, *] at * else begin rw [multiplicity_choose hp (le_of_not_gt hkn) (lt_succ_self _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hk0) (lt_succ_of_le (log_le_log_of_le (le_of_not_gt hkn))), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hn0) (lt_succ_self _), ← nat.cast_add, enat.coe_le_coe], calc ((Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ n)).card ≤ ((Ico 1 (log p n).succ).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i) ∪ (Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ k) ).card : card_le_of_subset $ λ i, begin have := @le_mod_add_mod_of_dvd_add_of_not_dvd k (n - k) (p ^ i), simp [add_tsub_cancel_of_le (le_of_not_gt hkn)] at * {contextual := tt}, tauto end ... ≤ ((Ico 1 (log p n).succ).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + ((Ico 1 (log p n).succ).filter (λ i, p ^ i ∣ k)).card : card_union_le _ _ end lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime) (hkn : k ≤ p ^ n) (hk0 : 0 < k) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (have hdisj : disjoint ((Ico 1 n.succ).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i)) ((Ico 1 n.succ).filter (λ i, p ^ i ∣ k)), by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (pow_pos hp.pos _)] {contextual := tt}, begin rw [multiplicity_choose hp hkn (lt_succ_self _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0 (lt_succ_of_le (log_le_log_of_le hkn)), ← nat.cast_add, enat.coe_le_coe, log_pow hp.one_lt, ← card_disjoint_union hdisj, filter_union_right], have filter_le_Ico := (Ico 1 n.succ).card_filter_le _, rwa card_Ico 1 n.succ at filter_le_Ico, end) (by rw [← hp.multiplicity_pow_self]; exact multiplicity_le_multiplicity_choose_add hp _ _) end prime lemma multiplicity_two_factorial_lt : ∀ {n : ℕ} (h : n ≠ 0), multiplicity 2 n! < n := begin have h2 := prime_iff.mp prime_two, refine binary_rec _ _, { contradiction }, { intros b n ih h, by_cases hn : n = 0, { subst hn, simp at h, simp [h, one_right h2.not_unit, enat.zero_lt_one] }, have : multiplicity 2 (2 * n)! < (2 * n : ℕ), { rw [prime_two.multiplicity_factorial_mul], refine (enat.add_lt_add_right (ih hn) (enat.coe_ne_top _)).trans_le _, rw [two_mul], norm_cast }, cases b, { simpa [bit0_eq_two_mul n] }, { suffices : multiplicity 2 (2 * n + 1) + multiplicity 2 (2 * n)! < ↑(2 * n) + 1, { simpa [succ_eq_add_one, multiplicity.mul, h2, prime_two, nat.bit1_eq_succ_bit0, bit0_eq_two_mul n] }, rw [multiplicity_eq_zero_of_not_dvd (two_not_dvd_two_mul_add_one n), zero_add], refine this.trans _, exact_mod_cast lt_succ_self _ }} end end nat
2d60a5a2c2d01a46f73ae6bedbec0aae926d6a66
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/free_module/basic.lean
f90e7bc658b6a6aee1fd9eca658a6eb652da39ef
[ "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
6,084
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.direct_sum.finsupp import logic.small import linear_algebra.std_basis /-! # Free modules We introduce a class `module.free R M`, for `R` a `semiring` and `M` an `R`-module and we provide several basic instances for this class. Use `finsupp.total_id_surjective` to prove that any module is the quotient of a free module. ## Main definition * `module.free R M` : the class of free `R`-modules. -/ universes u v w z variables (R : Type u) (M : Type v) (N : Type z) open_locale tensor_product direct_sum big_operators section basic variables [semiring R] [add_comm_monoid M] [module R M] /-- `module.free R M` is the statement that the `R`-module `M` is free.-/ class module.free : Prop := (exists_basis [] : nonempty (Σ (I : Type v), basis I R M)) /- If `M` fits in universe `w`, then freeness is equivalent to existence of a basis in that universe. Note that if `M` does not fit in `w`, the reverse direction of this implication is still true as `module.free.of_basis`. -/ lemma module.free_def [small.{w} M] : module.free R M ↔ ∃ (I : Type w), nonempty (basis I R M) := ⟨ λ h, ⟨shrink (set.range h.exists_basis.some.2), ⟨(basis.reindex_range h.exists_basis.some.2).reindex (equiv_shrink _)⟩⟩, λ h, ⟨(nonempty_sigma.2 h).map $ λ ⟨i, b⟩, ⟨set.range b, b.reindex_range⟩⟩⟩ lemma module.free_iff_set : module.free R M ↔ ∃ (S : set M), nonempty (basis S R M) := ⟨λ h, ⟨set.range h.exists_basis.some.2, ⟨basis.reindex_range h.exists_basis.some.2⟩⟩, λ ⟨S, hS⟩, ⟨nonempty_sigma.2 ⟨S, hS⟩⟩⟩ variables {R M} lemma module.free.of_basis {ι : Type w} (b : basis ι R M) : module.free R M := (module.free_def R M).2 ⟨set.range b, ⟨b.reindex_range⟩⟩ end basic namespace module.free section semiring variables (R M) [semiring R] [add_comm_monoid M] [module R M] [module.free R M] variables [add_comm_monoid N] [module R N] /-- If `module.free R M` then `choose_basis_index R M` is the `ι` which indexes the basis `ι → M`. -/ @[nolint has_inhabited_instance] def choose_basis_index := (exists_basis R M).some.1 /-- If `module.free R M` then `choose_basis : ι → M` is the basis. Here `ι = choose_basis_index R M`. -/ noncomputable def choose_basis : basis (choose_basis_index R M) R M := (exists_basis R M).some.2 /-- The isomorphism `M ≃ₗ[R] (choose_basis_index R M →₀ R)`. -/ noncomputable def repr : M ≃ₗ[R] (choose_basis_index R M →₀ R) := (choose_basis R M).repr /-- The universal property of free modules: giving a functon `(choose_basis_index R M) → N`, for `N` an `R`-module, is the same as giving an `R`-linear map `M →ₗ[R] N`. This definition is parameterized over an extra `semiring S`, such that `smul_comm_class R S M'` holds. If `R` is commutative, you can set `S := R`; if `R` is not commutative, you can recover an `add_equiv` by setting `S := ℕ`. See library note [bundled maps over different rings]. -/ noncomputable def constr {S : Type z} [semiring S] [module S N] [smul_comm_class R S N] : ((choose_basis_index R M) → N) ≃ₗ[S] M →ₗ[R] N := basis.constr (choose_basis R M) S @[priority 100] instance no_zero_smul_divisors [no_zero_divisors R] : no_zero_smul_divisors R M := let ⟨⟨_, b⟩⟩ := exists_basis R M in b.no_zero_smul_divisors /-- The product of finitely many free modules is free. -/ instance pi {ι : Type*} [fintype ι] {M : ι → Type*} [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π i, M i) := of_basis $ pi.basis $ λ i, choose_basis R (M i) /-- The module of finite matrices is free. -/ instance matrix {m n : Type*} [fintype m] [fintype n] : module.free R (matrix m n R) := of_basis $ matrix.std_basis R m n variables {R M N} lemma of_equiv (e : M ≃ₗ[R] N) : module.free R N := of_basis $ (choose_basis R M).map e /-- A variation of `of_equiv`: the assumption `module.free R P` here is explicit rather than an instance. -/ lemma of_equiv' {P : Type v} [add_comm_monoid P] [module R P] (h : module.free R P) (e : P ≃ₗ[R] N) : module.free R N := of_equiv e variables (R M N) instance {ι : Type v} : module.free R (ι →₀ R) := of_basis (basis.of_repr (linear_equiv.refl _ _)) instance {ι : Type v} [fintype ι] : module.free R (ι → R) := of_equiv (basis.of_repr $ linear_equiv.refl _ _).equiv_fun instance prod [module.free R N] : module.free R (M × N) := of_basis $ (choose_basis R M).prod (choose_basis R N) instance self : module.free R R := of_basis $ basis.singleton unit R @[priority 100] instance of_subsingleton [subsingleton N] : module.free R N := of_basis (basis.empty N : basis pempty R N) @[priority 100] instance of_subsingleton' [subsingleton R] : module.free R N := by letI := module.subsingleton R N; exact module.free.of_subsingleton R N instance dfinsupp {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π₀ i, M i) := of_basis $ dfinsupp.basis $ λ i, choose_basis R (M i) instance direct_sum {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (⨁ i, M i) := module.free.dfinsupp R M end semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] [module.free R M] variables [add_comm_group N] [module R N] [module.free R N] instance tensor : module.free R (M ⊗[R] N) := of_equiv' (of_equiv' (finsupp.free R) (finsupp_tensor_finsupp' R _ _).symm) (tensor_product.congr (choose_basis R M).repr (choose_basis R N).repr).symm end comm_ring section division_ring variables [division_ring R] [add_comm_group M] [module R M] @[priority 100] instance of_division_ring : module.free R M := of_basis (basis.of_vector_space R M) end division_ring end module.free
9def7bf4fc9d8a88bd6261c4d3370583cbf02403
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Std/Data/HashMap.lean
5b4a85224751dc8eb31ee22e207f4a90a0d5dd44
[ "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
7,653
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 -/ import Std.Data.AssocList namespace Std universes u v w def HashMapBucket (α : Type u) (β : Type v) := { b : Array (AssocList α β) // b.size > 0 } def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β := ⟨ data.val.uset i d h, by erw [Array.size_set]; exact data.property ⟩ structure HashMapImp (α : Type u) (β : Type v) where size : Nat buckets : HashMapBucket α β def mkHashMapImp {α : Type u} {β : Type v} (nbuckets := 8) : HashMapImp α β := let n := if nbuckets = 0 then 8 else nbuckets; { size := 0, buckets := ⟨ mkArray n AssocList.nil, by simp; cases nbuckets; decide; apply Nat.zeroLtSucc; done ⟩ } namespace HashMapImp variable {α : Type u} {β : Type v} def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } := ⟨u % n, USize.modn_lt _ h⟩ @[inline] def reinsertAux (hashFn : α → USize) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β := let ⟨i, h⟩ := mkIdx data.property (hashFn a) data.update i (AssocList.cons a b (data.val.uget i h)) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ := data.val.foldlM (init := d) fun d b => b.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ := foldBuckets m.buckets d f @[inline] def forBucketsM {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (f : α → β → m PUnit) : m PUnit := data.val.forM fun b => b.forM f @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMapImp α β) : m PUnit := forBucketsM h.buckets f def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).findEntry? a def find? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).find? a def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).contains a -- TODO: remove `partial` by using well-founded recursion partial def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : AssocList α β := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx AssocList.nil let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β := let nbuckets := buckets.val.size * 2 have : nbuckets > 0 := Nat.mulPos buckets.property (by decide) let new_buckets : HashMapBucket α β := ⟨mkArray nbuckets AssocList.nil, by simp; assumption⟩ { size := size, buckets := moveEntries 0 buckets.val new_buckets } def insert [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size, buckets.update i (bkt.replace a b) h⟩ else let size' := size + 1 let buckets' := buckets.update i (AssocList.cons a b bkt) h if size' ≤ buckets.val.size then { size := size', buckets := buckets' } else expand size' buckets' def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop where | mkWff : ∀ n, WellFormed (mkHashMapImp n) | insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashMapImp def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := { m : HashMapImp α β // m.WellFormed } open Std.HashMapImp def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (nbuckets := 8) : HashMap α β := ⟨ mkHashMapImp nbuckets, WellFormed.mkWff nbuckets ⟩ namespace HashMap variable {α : Type u} {β : Type v} [BEq α] [Hashable α] instance : Inhabited (HashMap α β) where default := mkHashMap instance : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩ @[inline] def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.insert a b, WellFormed.insertWff m a b hw ⟩ @[inline] def erase (m : HashMap α β) (a : α) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) := match m with | ⟨ m, _ ⟩ => m.findEntry? a @[inline] def find? (m : HashMap α β) (a : α) : Option β := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" @[inline] def getOp (self : HashMap α β) (idx : α) : Option β := self.find? idx @[inline] def contains (m : HashMap α β) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMap α β) : m PUnit := match h with | ⟨ h, _ ⟩ => h.forM f @[inline] def size (m : HashMap α β) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashMap α β) : Bool := m.size = 0 @[inline] def empty : HashMap α β := mkHashMap def toList (m : HashMap α β) : List (α × β) := m.fold (init := []) fun r k v => (k, v)::r def toArray (m : HashMap α β) : Array (α × β) := m.fold (init := #[]) fun r k v => r.push (k, v) def numBuckets (m : HashMap α β) : Nat := m.val.buckets.val.size end HashMap end Std
9b2632f4bed65be318e8b6f40b8d66b27e721bcf
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/Tactic/Simp/CongrLemmas.lean
f31adb76308a04805a6fdb8495f98dbcec966efd
[ "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
5,244
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.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.Basic namespace Lean.Meta structure CongrLemma where theoremName : Name funName : Name hypothesesPos : Array Nat priority : Nat deriving Inhabited, Repr structure CongrLemmas where lemmas : SMap Name (List CongrLemma) := {} deriving Inhabited, Repr def CongrLemmas.get (d : CongrLemmas) (declName : Name) : List CongrLemma := match d.lemmas.find? declName with | none => [] | some cs => cs def addCongrLemmaEntry (d : CongrLemmas) (e : CongrLemma) : CongrLemmas := { d with lemmas := match d.lemmas.find? e.funName with | none => d.lemmas.insert e.funName [e] | some es => d.lemmas.insert e.funName <| insert es } where insert : List CongrLemma → List CongrLemma | [] => [e] | e'::es => if e.priority ≥ e'.priority then e::e'::es else e' :: insert es builtin_initialize congrExtension : SimpleScopedEnvExtension CongrLemma CongrLemmas ← registerSimpleScopedEnvExtension { name := `congrExt initial := {} addEntry := addCongrLemmaEntry finalizeImport := fun s => { s with lemmas := s.lemmas.switch } } def mkCongrLemma (declName : Name) (prio : Nat) : MetaM CongrLemma := withReducible do let info ← getConstInfo declName let c := mkConst declName (info.levelParams.map mkLevelParam) let (xs, bis, type) ← forallMetaTelescopeReducing (← inferType c) match type.eq? with | none => throwError! "invalid 'congr' lemma, equality expected{indentExpr type}" | some (_, lhs, rhs) => lhs.withApp fun lhsFn lhsArgs => rhs.withApp fun rhsFn rhsArgs => do unless lhsFn.isConst && rhsFn.isConst && lhsFn.constName! == rhsFn.constName! && lhsArgs.size == rhsArgs.size do throwError! "invalid 'congr' lemma, equality left/right-hand sides must be applications of the same function{indentExpr type}" let mut foundMVars : NameSet := {} for lhsArg in lhsArgs do unless lhsArg.isSort do unless lhsArg.isMVar do throwError! "invalid 'congr' lemma, arguments in the left-hand-side must be variables or sorts{indentExpr lhs}" foundMVars := foundMVars.insert lhsArg.mvarId! let mut i := 0 let mut hypothesesPos := #[] for x in xs, bi in bis do if bi.isExplicit && !foundMVars.contains x.mvarId! then let rhsFn? ← forallTelescopeReducing (← inferType x) fun ys xType => do match xType.eq? with | none => pure none -- skip | some (_, xLhs, xRhs) => let mut j := 0 for y in ys do let yType ← inferType y unless onlyMVarsAt yType foundMVars do throwError! "invalid 'congr' lemma, argument #{j+1} of parameter #{i+1} contains unresolved parameter{indentExpr yType}" j := j + 1 unless onlyMVarsAt xLhs foundMVars do throwError! "invalid 'congr' lemma, parameter #{i+1} is not a valid hypothesis, the left-hand-side contains unresolved parameters{indentExpr xLhs}" let xRhsFn := xRhs.getAppFn unless xRhsFn.isMVar do throwError! "invalid 'congr' lemma, parameter #{i+1} is not a valid hypothesis, the right-hand-side head is not a metavariable{indentExpr xRhs}" unless !foundMVars.contains xRhsFn.mvarId! do throwError! "invalid 'congr' lemma, parameter #{i+1} is not a valid hypothesis, the right-hand-side head was already resolved{indentExpr xRhs}" for arg in xRhs.getAppArgs do unless arg.isFVar do throwError! "invalid 'congr' lemma, parameter #{i+1} is not a valid hypothesis, the right-hand-side argument is not local variable{indentExpr xRhs}" pure (some xRhsFn) match rhsFn? with | none => pure () | some rhsFn => foundMVars := foundMVars.insert x.mvarId! |>.insert rhsFn.mvarId! hypothesesPos := hypothesesPos.push i i := i + 1 trace[Meta.debug]! "c: {c} : {type}" return { theoremName := declName funName := lhsFn.constName! hypothesesPos := hypothesesPos priority := prio } where /-- Return `true` if `t` contains a metavariable that is not in `mvarSet` -/ onlyMVarsAt (t : Expr) (mvarSet : NameSet) : Bool := Option.isNone <| t.find? fun e => e.isMVar && !mvarSet.contains e.mvarId! def addCongrLemma (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let lemma ← mkCongrLemma declName prio congrExtension.add lemma attrKind builtin_initialize registerBuiltinAttribute { name := `congr descr := "congruence lemma" add := fun declName stx attrKind => do let prio ← getAttrParamOptPrio stx[1] discard <| addCongrLemma declName attrKind prio |>.run {} {} } def getCongrLemmas : MetaM CongrLemmas := return congrExtension.getState (← getEnv) end Lean.Meta
506a47f37b5761b97680b1ddce9423ddfe119a94
ac60dab17014edd769c9618cc1569ce8c960a6a5
/src/matrix.lean
9b7d2f934685fc1cb9594ae9c0cc10b32d0f6b89
[ "MIT" ]
permissive
frankSil/CAExtensions
20e1f856b3ad775d5e8dc8877614dbcd58c77901
f5c74fd9a806696c73497d9abd45b7315f45379f
refs/heads/master
1,608,706,941,607
1,586,193,337,000
1,586,193,337,000
237,077,434
0
0
null
null
null
null
UTF-8
Lean
false
false
5,505
lean
import grid utils data.vector2 tactic.elide open utils namespace matrix structure matrix (m n : ℕ) (α : Type) := (g : vec_grid₀ α) (hr : g.r = m) (hc : g.c = n) section ext variables {m n : ℕ} {α : Type} {m₁ m₂ : matrix m n α} theorem ext_iff : m₁.g = m₂.g ↔ m₁ = m₂ := by cases m₁; rcases m₂; simp @[ext] theorem ext : m₁.g = m₂.g → m₁ = m₂ := ext_iff.1 end ext section operations variables {m n o p : ℕ} {α β γ δ : Type} open relative_grid grid lemma matrix_nonempty {m₁ : matrix m n α} : m * n > 0 := by rcases m₁ with ⟨⟨⟨_, _, _, _⟩, _⟩, _, _⟩; finish def matrix_string [has_to_string α] (m : matrix m n α) := grid_str m.g instance matrix_repr [has_to_string α] : has_repr (matrix m n α) := ⟨matrix_string⟩ instance matrix_to_string [has_to_string α] : has_to_string (matrix m n α) := ⟨matrix_string⟩ instance matrix_functor : functor (matrix m n) := { map := λα β f m, ⟨f <$> m.g, by rw [vec_grid₀_fmap_r, m.hr], by rw [vec_grid₀_fmap_c, m.hc]⟩ } instance matrix_functor_law : is_lawful_functor (matrix m n) := { id_map := λα ⟨⟨⟨r, c, h, d⟩, o⟩, hr, hc⟩, by simp [(<$>), vector.map_id], comp_map := λα β γ f h ⟨⟨⟨r, c, h, d⟩, o⟩, hr, hc⟩, by simp [(<$>)] } def m₁ : matrix 5 2 ℕ := matrix.mk (vec_grid₀.mk ⟨5, 2, dec_trivial, ⟨[1, 3, 4, 5, 7, 8, 9, 10, 11, 12], dec_trivial⟩⟩ ⟨5, 1⟩) rfl rfl def m₂ : matrix 2 3 ℕ := matrix.mk (vec_grid₀.mk ⟨2, 3, dec_trivial, ⟨[2, 2, 2, 2, 2, 2], dec_trivial⟩⟩ ⟨0, 0⟩) rfl rfl instance [has_add α] : has_add (matrix m n α) := { add := λm₁ m₂, ⟨⟨⟨m, n, @matrix_nonempty _ _ _ m₁, begin rcases m₁ with ⟨⟨⟨g₁r, g₁c, g₁h, g₁d⟩, g₁o⟩, hr₁, hc₁⟩, rcases m₂ with ⟨⟨⟨g₂r, g₂c, g₂h, g₂d⟩, g₂o⟩, hr₂, hc₂⟩, simp at hr₁ hc₁ hr₂ hc₂, substs hc₁ hr₁ hc₂ hr₂, exact vector.zip_with (+) g₁d g₂d end⟩, ⟨0, 0⟩⟩, rfl, rfl⟩ } def transpose (m₁ : matrix m n α) : matrix n m α := ⟨(vec_grid₀_of_fgrid₀ ⟨ n, m, mul_comm m n ▸ @matrix_nonempty _ _ _ m₁, ⟨m₁.g.o.y, m₁.g.o.x⟩, λx y, abs_data m₁.g ⟨ ⟨y.1, begin cases y with y h, simp at h, simp [expand_gtr, grid.bl], have : ↑(rows (m₁.g)) = ↑m, by rcases m₁ with ⟨⟨⟨_, _, _, _⟩, _⟩, h₁, h₂⟩; substs h₁ h₂; simp [rows], rw this, exact h end⟩, ⟨x.1, begin cases x with x h, simp at h, simp [expand_gtr, grid.bl], have : ↑(cols (m₁.g)) = ↑n, by rcases m₁ with ⟨⟨⟨_, _, _, _⟩, _⟩, h₁, h₂⟩; substs h₁ h₂; simp [cols], rw this, exact h end⟩⟩⟩), by simp, by simp⟩ theorem transpose_transpose_id (m₁ : matrix m n α) : transpose (transpose m₁) = m₁ := begin rcases m₁ with ⟨⟨g, ⟨_, _⟩⟩, h₁, h₂⟩, subst h₁, subst h₂, unfold transpose, congr' 1, ext _; try { simp }, rw gen_aof_eq_gen, apply list.ext_le _ _, { repeat { rw length_generate_eq_size }, simp [size, rows, cols] }, { intros n h₁ h₂, rw nth_le_generate_f₀, simp [abs_data_eq_nth_v₀', tl, bl, vector.nth_eq_nth_le, vector.to_list], rw [← option.some_inj, ← list.nth_le_nth, nth_vecgrid_of_fgrid], have : |↑n % ↑g.c| + g.c * |↑n / ↑g.c| < list.length g.data.val, by rw [mul_comm, mod_add_div_coe]; rw generate_eq_data at h₂; exact h₂, simp [length_generate_eq_size, size] at h₂, have rpos : g.r > 0, from (gt_and_gt_of_mul_gt g.h).1, have cpos : g.c > 0, from (gt_and_gt_of_mul_gt g.h).2, have nltcr : n < g.r * g.c, by simp [rows, cols, *] at h₂; assumption, have h₃ : ↑(n / g.c) < ↑g.r, by rwa [int.coe_nat_lt_coe_nat_iff, nat.div_lt_iff_lt_mul _ _ cpos], rw nth_generate_f₀, simp [abs_data_eq_nth_v₀', vector.nth_eq_nth_le, list.nth_le_nth this, vector.to_list], rw [← with_bot.some_eq_coe], simp [generate_eq_data], congr, { have rnezero : g.r ≠ 0, by intros contra; rw contra at rpos; linarith, rw ← int.coe_nat_eq_coe_nat_iff, simp, repeat { rw int.nat_abs_of_nonneg; try { apply int.coe_zero_le } }, rw @int.add_mul_div_right _ _ g.r (by simpa), norm_cast, rw nat.div_div_eq_div_mul, rw mul_comm g.c g.r, simp[@nat.div_eq_of_lt n (g.r * g.c) nltcr], norm_cast, have h₄ : (0 : ℤ) ≤ ↑(n / g.c), by simp, rw @int.mod_eq_of_lt ↑(n / g.c) ↑g.r h₄ h₃, rw mul_comm, apply int.mod_add_div }, { rw length_generate_eq_size, simp [size, cols, rows], rw [add_comm], have h₄ : |↑n / ↑g.c| < g.r, by norm_cast at *; exact h₃, have h₅ : |↑n % ↑g.c| < g.c, begin rw [← int.coe_nat_lt_coe_nat_iff, int.nat_abs_of_nonneg], apply @int.mod_lt_of_pos ↑n ↑g.c (by norm_cast; exact cpos), have cnezero : g.c ≠ 0, by intros contra; rw contra at cpos; linarith, exact int.mod_nonneg _ (by simp [cnezero]) end, exact linearize_array h₄ h₅ } } end end operations end matrix
47b86e6470721adb0c55ccd8d5af17feec624d51
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/init/ua.hlean
e3f3a4ae1ca126d891d58582f5b05e1a0ab654aa
[ "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
2,960
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jakob von Raumer Ported from Coq HoTT -/ prelude import .equiv open eq equiv is_equiv equiv.ops --Ensure that the types compared are in the same universe section universe variable l variables {A B : Type.{l}} definition is_equiv_cast_of_eq [constructor] (H : A = B) : is_equiv (cast H) := is_equiv_tr (λX, X) H definition equiv_of_eq [constructor] (H : A = B) : A ≃ B := equiv.mk _ (is_equiv_cast_of_eq H) definition equiv_of_eq_refl [reducible] [unfold-full] (A : Type) : equiv_of_eq (refl A) = equiv.refl := idp end axiom univalence (A B : Type) : is_equiv (@equiv_of_eq A B) attribute univalence [instance] -- This is the version of univalence axiom we will probably use most often definition ua [reducible] {A B : Type} : A ≃ B → A = B := equiv_of_eq⁻¹ definition eq_equiv_equiv (A B : Type) : (A = B) ≃ (A ≃ B) := equiv.mk equiv_of_eq _ definition equiv_of_eq_ua [reducible] {A B : Type} (f : A ≃ B) : equiv_of_eq (ua f) = f := right_inv equiv_of_eq f definition cast_ua_fn {A B : Type} (f : A ≃ B) : cast (ua f) = f := ap to_fun (equiv_of_eq_ua f) definition cast_ua {A B : Type} (f : A ≃ B) (a : A) : cast (ua f) a = f a := ap10 (cast_ua_fn f) a definition ua_equiv_of_eq [reducible] {A B : Type} (p : A = B) : ua (equiv_of_eq p) = p := left_inv equiv_of_eq p definition eq_of_equiv_lift {A B : Type} (f : A ≃ B) : A = lift B := ua (f ⬝e !equiv_lift) namespace equiv definition ua_refl (A : Type) : ua erfl = idpath A := eq_of_fn_eq_fn !eq_equiv_equiv (right_inv !eq_equiv_equiv erfl) -- One consequence of UA is that we can transport along equivalencies of types -- We can use this for calculation evironments protected definition transport_of_equiv [subst] (P : Type → Type) {A B : Type} (H : A ≃ B) : P A → P B := eq.transport P (ua H) -- we can "recurse" on equivalences, by replacing them by (equiv_of_eq _) definition rec_on_ua [recursor] {A B : Type} {P : A ≃ B → Type} (f : A ≃ B) (H : Π(q : A = B), P (equiv_of_eq q)) : P f := right_inv equiv_of_eq f ▸ H (ua f) -- a variant where we immediately recurse on the equality in the new goal definition rec_on_ua_idp [recursor] {A : Type} {P : Π{B}, A ≃ B → Type} {B : Type} (f : A ≃ B) (H : P equiv.refl) : P f := rec_on_ua f (λq, eq.rec_on q H) -- a variant where (equiv_of_eq (ua f)) will be replaced by f in the new goal definition rec_on_ua' {A B : Type} {P : A ≃ B → A = B → Type} (f : A ≃ B) (H : Π(q : A = B), P (equiv_of_eq q) q) : P f (ua f) := right_inv equiv_of_eq f ▸ H (ua f) -- a variant where we do both definition rec_on_ua_idp' {A : Type} {P : Π{B}, A ≃ B → A = B → Type} {B : Type} (f : A ≃ B) (H : P equiv.refl idp) : P f (ua f) := rec_on_ua' f (λq, eq.rec_on q H) end equiv
b4d3483a11189a4b8dfdba647c1f4de8821dffeb
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/test/showTerm.lean
83239c68416fba1bd58e8936d3633648db100b27
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
353
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison -/ import Mathlib.Tactic.ShowTerm example (n : Nat) : Nat × Nat := by showTerm constructor exact n exact 37 example (n : Nat) : Nat × Nat := by showTerm constructor repeat exact 42
aa77bfa5a0618aa8a3e0ab72b9097705b1e7b925
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/algebra/unitization.lean
b21beee7f5a812008f2313a032020021eb759628
[ "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
21,793
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.algebra.basic import linear_algebra.prod import algebra.hom.non_unital_alg /-! # Unitization of a non-unital algebra Given a non-unital `R`-algebra `A` (given via the type classes `[non_unital_ring A] [module R A] [smul_comm_class R A A] [is_scalar_tower R A A]`) we construct the minimal unital `R`-algebra containing `A` as an ideal. This object `algebra.unitization R A` is a type synonym for `R × A` on which we place a different multiplicative structure, namely, `(r₁, a₁) * (r₂, a₂) = (r₁ * r₂, r₁ • a₂ + r₂ • a₁ + a₁ * a₂)` where the multiplicative identity is `(1, 0)`. Note, when `A` is a *unital* `R`-algebra, then `unitization R A` constructs a new multiplicative identity different from the old one, and so in general `unitization R A` and `A` will not be isomorphic even in the unital case. This approach actually has nice functorial properties. There is a natural coercion from `A` to `unitization R A` given by `λ a, (0, a)`, the image of which is a proper ideal (TODO), and when `R` is a field this ideal is maximal. Moreover, this ideal is always an essential ideal (it has nontrivial intersection with every other nontrivial ideal). Every non-unital algebra homomorphism from `A` into a *unital* `R`-algebra `B` has a unique extension to a (unital) algebra homomorphism from `unitization R A` to `B`. ## Main definitions * `unitization R A`: the unitization of a non-unital `R`-algebra `A`. * `unitization.algebra`: the unitization of `A` as a (unital) `R`-algebra. * `unitization.coe_non_unital_alg_hom`: coercion as a non-unital algebra homomorphism. * `non_unital_alg_hom.to_alg_hom φ`: the extension of a non-unital algebra homomorphism `φ : A → B` into a unital `R`-algebra `B` to an algebra homomorphism `unitization R A →ₐ[R] B`. ## Main results * `non_unital_alg_hom.to_alg_hom_unique`: the extension is unique ## TODO * prove the unitization operation is a functor between the appropriate categories * prove the image of the coercion is an essential ideal, maximal if scalars are a field. -/ /-- The minimal unitization of a non-unital `R`-algebra `A`. This is just a type synonym for `R × A`.-/ def unitization (R A : Type*) := R × A namespace unitization section basic variables {R A : Type*} /-- The canonical inclusion `R → unitization R A`. -/ def inl [has_zero A] (r : R) : unitization R A := (r, 0) /-- The canonical inclusion `A → unitization R A`. -/ instance [has_zero R] : has_coe_t A (unitization R A) := { coe := λ a, (0, a) } /-- The canonical projection `unitization R A → R`. -/ def fst (x : unitization R A) : R := x.1 /-- The canonical projection `unitization R A → A`. -/ def snd (x : unitization R A) : A := x.2 @[ext] lemma ext {x y : unitization R A} (h1 : x.fst = y.fst) (h2 : x.snd = y.snd) : x = y := prod.ext h1 h2 section variables (A) @[simp] lemma fst_inl [has_zero A] (r : R) : (inl r : unitization R A).fst = r := rfl @[simp] lemma snd_inl [has_zero A] (r : R) : (inl r : unitization R A).snd = 0 := rfl end section variables (R) @[simp] lemma fst_coe [has_zero R] (a : A) : (a : unitization R A).fst = 0 := rfl @[simp] lemma snd_coe [has_zero R] (a : A) : (a : unitization R A).snd = a := rfl end lemma inl_injective [has_zero A] : function.injective (inl : R → unitization R A) := function.left_inverse.injective $ fst_inl _ lemma coe_injective [has_zero R] : function.injective (coe : A → unitization R A) := function.left_inverse.injective $ snd_coe _ end basic /-! ### Structures inherited from `prod` Additive operators and scalar multiplication operate elementwise. -/ section additive variables {T : Type*} {S : Type*} {R : Type*} {A : Type*} instance [inhabited R] [inhabited A] : inhabited (unitization R A) := prod.inhabited instance [has_zero R] [has_zero A] : has_zero (unitization R A) := prod.has_zero instance [has_add R] [has_add A] : has_add (unitization R A) := prod.has_add instance [has_neg R] [has_neg A] : has_neg (unitization R A) := prod.has_neg instance [add_semigroup R] [add_semigroup A] : add_semigroup (unitization R A) := prod.add_semigroup instance [add_zero_class R] [add_zero_class A] : add_zero_class (unitization R A) := prod.add_zero_class instance [add_monoid R] [add_monoid A] : add_monoid (unitization R A) := prod.add_monoid instance [add_group R] [add_group A] : add_group (unitization R A) := prod.add_group instance [add_comm_semigroup R] [add_comm_semigroup A] : add_comm_semigroup (unitization R A) := prod.add_comm_semigroup instance [add_comm_monoid R] [add_comm_monoid A] : add_comm_monoid (unitization R A) := prod.add_comm_monoid instance [add_comm_group R] [add_comm_group A] : add_comm_group (unitization R A) := prod.add_comm_group instance [has_scalar S R] [has_scalar S A] : has_scalar S (unitization R A) := prod.has_scalar instance [has_scalar T R] [has_scalar T A] [has_scalar S R] [has_scalar S A] [has_scalar T S] [is_scalar_tower T S R] [is_scalar_tower T S A] : is_scalar_tower T S (unitization R A) := prod.is_scalar_tower instance [has_scalar T R] [has_scalar T A] [has_scalar S R] [has_scalar S A] [smul_comm_class T S R] [smul_comm_class T S A] : smul_comm_class T S (unitization R A) := prod.smul_comm_class instance [has_scalar S R] [has_scalar S A] [has_scalar Sᵐᵒᵖ R] [has_scalar Sᵐᵒᵖ A] [is_central_scalar S R] [is_central_scalar S A] : is_central_scalar S (unitization R A) := prod.is_central_scalar instance [monoid S] [mul_action S R] [mul_action S A] : mul_action S (unitization R A) := prod.mul_action instance [monoid S] [add_monoid R] [add_monoid A] [distrib_mul_action S R] [distrib_mul_action S A] : distrib_mul_action S (unitization R A) := prod.distrib_mul_action instance [semiring S] [add_comm_monoid R] [add_comm_monoid A] [module S R] [module S A] : module S (unitization R A) := prod.module @[simp] lemma fst_zero [has_zero R] [has_zero A] : (0 : unitization R A).fst = 0 := rfl @[simp] lemma snd_zero [has_zero R] [has_zero A] : (0 : unitization R A).snd = 0 := rfl @[simp] lemma fst_add [has_add R] [has_add A] (x₁ x₂ : unitization R A) : (x₁ + x₂).fst = x₁.fst + x₂.fst := rfl @[simp] lemma snd_add [has_add R] [has_add A] (x₁ x₂ : unitization R A) : (x₁ + x₂).snd = x₁.snd + x₂.snd := rfl @[simp] lemma fst_neg [has_neg R] [has_neg A] (x : unitization R A) : (-x).fst = -x.fst := rfl @[simp] lemma snd_neg [has_neg R] [has_neg A] (x : unitization R A) : (-x).snd = -x.snd := rfl @[simp] lemma fst_smul [has_scalar S R] [has_scalar S A] (s : S) (x : unitization R A) : (s • x).fst = s • x.fst := rfl @[simp] lemma snd_smul [has_scalar S R] [has_scalar S A] (s : S) (x : unitization R A) : (s • x).snd = s • x.snd := rfl section variables (A) @[simp] lemma inl_zero [has_zero R] [has_zero A] : (inl 0 : unitization R A) = 0 := rfl @[simp] lemma inl_add [has_add R] [add_zero_class A] (r₁ r₂ : R) : (inl (r₁ + r₂) : unitization R A) = inl r₁ + inl r₂ := ext rfl (add_zero 0).symm @[simp] lemma inl_neg [has_neg R] [add_group A] (r : R) : (inl (-r) : unitization R A) = -inl r := ext rfl neg_zero.symm @[simp] lemma inl_smul [monoid S] [add_monoid A] [has_scalar S R] [distrib_mul_action S A] (s : S) (r : R) : (inl (s • r) : unitization R A) = s • inl r := ext rfl (smul_zero s).symm end section variables (R) @[simp] lemma coe_zero [has_zero R] [has_zero A] : ↑(0 : A) = (0 : unitization R A) := rfl @[simp] lemma coe_add [add_zero_class R] [has_add A] (m₁ m₂ : A) : (↑(m₁ + m₂) : unitization R A) = m₁ + m₂ := ext (add_zero 0).symm rfl @[simp] lemma coe_neg [add_group R] [has_neg A] (m : A) : (↑(-m) : unitization R A) = -m := ext neg_zero.symm rfl @[simp] lemma coe_smul [has_zero R] [has_zero S] [smul_with_zero S R] [has_scalar S A] (r : S) (m : A) : (↑(r • m) : unitization R A) = r • m := ext (smul_zero' _ _).symm rfl end lemma inl_fst_add_coe_snd_eq [add_zero_class R] [add_zero_class A] (x : unitization R A) : inl x.fst + ↑x.snd = x := ext (add_zero x.1) (zero_add x.2) /-- To show a property hold on all `unitization R A` it suffices to show it holds on terms of the form `inl r + a`. This can be used as `induction x using unitization.ind`. -/ lemma ind {R A} [add_zero_class R] [add_zero_class A] {P : unitization R A → Prop} (h : ∀ (r : R) (a : A), P (inl r + a)) (x) : P x := inl_fst_add_coe_snd_eq x ▸ h x.1 x.2 /-- This cannot be marked `@[ext]` as it ends up being used instead of `linear_map.prod_ext` when working with `R × A`. -/ lemma linear_map_ext {N} [semiring S] [add_comm_monoid R] [add_comm_monoid A] [add_comm_monoid N] [module S R] [module S A] [module S N] ⦃f g : unitization R A →ₗ[S] N⦄ (hl : ∀ r, f (inl r) = g (inl r)) (hr : ∀ a : A, f a = g a) : f = g := linear_map.prod_ext (linear_map.ext hl) (linear_map.ext hr) variables (R A) /-- The canonical `R`-linear inclusion `A → unitization R A`. -/ @[simps apply] def coe_hom [semiring R] [add_comm_monoid A] [module R A] : A →ₗ[R] unitization R A := { to_fun := coe, ..linear_map.inr R R A } /-- The canonical `R`-linear projection `unitization R A → A`. -/ @[simps apply] def snd_hom [semiring R] [add_comm_monoid A] [module R A] : unitization R A →ₗ[R] A := { to_fun := snd, ..linear_map.snd _ _ _ } end additive /-! ### Multiplicative structure -/ section mul variables {R A : Type*} instance [has_one R] [has_zero A] : has_one (unitization R A) := ⟨(1, 0)⟩ instance [has_mul R] [has_add A] [has_mul A] [has_scalar R A] : has_mul (unitization R A) := ⟨λ x y, (x.1 * y.1, x.1 • y.2 + y.1 • x.2 + x.2 * y.2)⟩ @[simp] lemma fst_one [has_one R] [has_zero A] : (1 : unitization R A).fst = 1 := rfl @[simp] lemma snd_one [has_one R] [has_zero A] : (1 : unitization R A).snd = 0 := rfl @[simp] lemma fst_mul [has_mul R] [has_add A] [has_mul A] [has_scalar R A] (x₁ x₂ : unitization R A) : (x₁ * x₂).fst = x₁.fst * x₂.fst := rfl @[simp] lemma snd_mul [has_mul R] [has_add A] [has_mul A] [has_scalar R A] (x₁ x₂ : unitization R A) : (x₁ * x₂).snd = x₁.fst • x₂.snd + x₂.fst • x₁.snd + x₁.snd * x₂.snd := rfl section variables (A) @[simp] lemma inl_one [has_one R] [has_zero A] : (inl 1 : unitization R A) = 1 := rfl @[simp] lemma inl_mul [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] (r₁ r₂ : R) : (inl (r₁ * r₂) : unitization R A) = inl r₁ * inl r₂ := ext rfl $ show (0 : A) = r₁ • (0 : A) + r₂ • 0 + 0 * 0, by simp only [smul_zero, add_zero, mul_zero] lemma inl_mul_inl [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] (r₁ r₂ : R) : (inl r₁ * inl r₂ : unitization R A) = inl (r₁ * r₂) := (inl_mul A r₁ r₂).symm end section variables (R) @[simp] lemma coe_mul [semiring R] [add_comm_monoid A] [has_mul A] [smul_with_zero R A] (a₁ a₂ : A) : (↑(a₁ * a₂) : unitization R A) = a₁ * a₂ := ext (mul_zero _).symm $ show a₁ * a₂ = (0 : R) • a₂ + (0 : R) • a₁ + a₁ * a₂, by simp only [zero_smul, zero_add] end lemma inl_mul_coe [semiring R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] (r : R) (a : A) : (inl r * a : unitization R A) = ↑(r • a) := ext (mul_zero r) $ show r • a + (0 : R) • 0 + 0 * a = r • a, by rw [smul_zero, add_zero, zero_mul, add_zero] lemma coe_mul_inl [semiring R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] (r : R) (a : A) : (a * inl r : unitization R A) = ↑(r • a) := ext (zero_mul r) $ show (0 : R) • 0 + r • a + a * 0 = r • a, by rw [smul_zero, zero_add, mul_zero, add_zero] instance mul_one_class [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] : mul_one_class (unitization R A) := { one_mul := λ x, ext (one_mul x.1) $ show (1 : R) • x.2 + x.1 • 0 + 0 * x.2 = x.2, by rw [one_smul, smul_zero, add_zero, zero_mul, add_zero], mul_one := λ x, ext (mul_one x.1) $ show (x.1 • 0 : A) + (1 : R) • x.2 + x.2 * 0 = x.2, by rw [smul_zero, zero_add, one_smul, mul_zero, add_zero], .. unitization.has_one, .. unitization.has_mul } instance [semiring R] [non_unital_non_assoc_semiring A] [module R A] : non_assoc_semiring (unitization R A) := { zero_mul := λ x, ext (zero_mul x.1) $ show (0 : R) • x.2 + x.1 • 0 + 0 * x.2 = 0, by rw [zero_smul, zero_add, smul_zero, zero_mul, add_zero], mul_zero := λ x, ext (mul_zero x.1) $ show (x.1 • 0 : A) + (0 : R) • x.2 + x.2 * 0 = 0, by rw [smul_zero, zero_add, zero_smul, mul_zero, add_zero], left_distrib := λ x₁ x₂ x₃, ext (mul_add x₁.1 x₂.1 x₃.1) $ show x₁.1 • (x₂.2 + x₃.2) + (x₂.1 + x₃.1) • x₁.2 + x₁.2 * (x₂.2 + x₃.2) = x₁.1 • x₂.2 + x₂.1 • x₁.2 + x₁.2 * x₂.2 + (x₁.1 • x₃.2 + x₃.1 • x₁.2 + x₁.2 * x₃.2), by { simp only [smul_add, add_smul, mul_add], abel }, right_distrib := λ x₁ x₂ x₃, ext (add_mul x₁.1 x₂.1 x₃.1) $ show (x₁.1 + x₂.1) • x₃.2 + x₃.1 • (x₁.2 + x₂.2) + (x₁.2 + x₂.2) * x₃.2 = x₁.1 • x₃.2 + x₃.1 • x₁.2 + x₁.2 * x₃.2 + (x₂.1 • x₃.2 + x₃.1 • x₂.2 + x₂.2 * x₃.2), by { simp only [add_smul, smul_add, add_mul], abel }, .. unitization.mul_one_class, .. unitization.add_comm_monoid } instance [comm_monoid R] [non_unital_semiring A] [distrib_mul_action R A] [is_scalar_tower R A A] [smul_comm_class R A A] : monoid (unitization R A) := { mul_assoc := λ x y z, ext (mul_assoc x.1 y.1 z.1) $ show (x.1 * y.1) • z.2 + z.1 • (x.1 • y.2 + y.1 • x.2 + x.2 * y.2) + (x.1 • y.2 + y.1 • x.2 + x.2 * y.2) * z.2 = x.1 • (y.1 • z.2 + z.1 • y.2 + y.2 * z.2) + (y.1 * z.1) • x.2 + x.2 * (y.1 • z.2 + z.1 • y.2 + y.2 * z.2), { simp only [smul_add, mul_add, add_mul, smul_smul, smul_mul_assoc, mul_smul_comm, mul_assoc], nth_rewrite 1 mul_comm, nth_rewrite 2 mul_comm, abel }, ..unitization.mul_one_class } -- This should work for `non_unital_comm_semiring`s, but we don't seem to have those instance [comm_monoid R] [comm_semiring A] [distrib_mul_action R A] [is_scalar_tower R A A] [smul_comm_class R A A] : comm_monoid (unitization R A) := { mul_comm := λ x₁ x₂, ext (mul_comm x₁.1 x₂.1) $ show x₁.1 • x₂.2 + x₂.1 • x₁.2 + x₁.2 * x₂.2 = x₂.1 • x₁.2 + x₁.1 • x₂.2 + x₂.2 * x₁.2, by rw [add_comm (x₁.1 • x₂.2), mul_comm], ..unitization.monoid } instance [comm_semiring R] [non_unital_semiring A] [module R A] [is_scalar_tower R A A] [smul_comm_class R A A] : semiring (unitization R A) := { ..unitization.monoid, ..unitization.non_assoc_semiring } -- This should work for `non_unital_comm_semiring`s, but we don't seem to have those instance [comm_semiring R] [comm_semiring A] [module R A] [is_scalar_tower R A A] [smul_comm_class R A A] : comm_semiring (unitization R A) := { ..unitization.comm_monoid, ..unitization.non_assoc_semiring } variables (R A) /-- The canonical inclusion of rings `R →+* unitization R A`. -/ @[simps apply] def inl_ring_hom [semiring R] [non_unital_semiring A] [module R A] : R →+* unitization R A := { to_fun := inl, map_one' := inl_one A, map_mul' := inl_mul A, map_zero' := inl_zero A, map_add' := inl_add A } end mul /-! ### Star structure -/ section star variables {R A : Type*} instance [has_star R] [has_star A] : has_star (unitization R A) := ⟨λ ra, (star ra.fst, star ra.snd)⟩ @[simp] lemma fst_star [has_star R] [has_star A] (x : unitization R A) : (star x).fst = star x.fst := rfl @[simp] lemma snd_star [has_star R] [has_star A] (x : unitization R A) : (star x).snd = star x.snd := rfl @[simp] lemma inl_star [has_star R] [add_monoid A] [star_add_monoid A] (r : R) : inl (star r) = star (inl r : unitization R A) := ext rfl (by simp only [snd_star, star_zero, snd_inl]) @[simp] lemma coe_star [add_monoid R] [star_add_monoid R] [has_star A] (a : A) : ↑(star a) = star (a : unitization R A) := ext (by simp only [fst_star, star_zero, fst_coe]) rfl instance [add_monoid R] [add_monoid A] [star_add_monoid R] [star_add_monoid A] : star_add_monoid (unitization R A) := { star_involutive := λ x, ext (star_star x.fst) (star_star x.snd), star_add := λ x y, ext (star_add x.fst y.fst) (star_add x.snd y.snd) } instance [comm_semiring R] [star_ring R] [add_comm_monoid A] [star_add_monoid A] [module R A] [star_module R A] : star_module R (unitization R A) := { star_smul := λ r x, ext (by simp) (by simp) } instance [comm_semiring R] [star_ring R] [non_unital_semiring A] [star_ring A] [module R A] [is_scalar_tower R A A] [smul_comm_class R A A] [star_module R A] : star_ring (unitization R A) := { star_mul := λ x y, ext (by simp [star_mul]) (by simp [star_mul, add_comm (star x.fst • star y.snd)]), ..unitization.star_add_monoid } end star /-! ### Algebra structure -/ section algebra variables (S R A : Type*) [comm_semiring S] [comm_semiring R] [non_unital_semiring A] [module R A] [is_scalar_tower R A A] [smul_comm_class R A A] [algebra S R] [distrib_mul_action S A] [is_scalar_tower S R A] instance algebra : algebra S (unitization R A) := { commutes' := λ r x, begin induction x using unitization.ind, simp only [mul_add, add_mul, ring_hom.to_fun_eq_coe, ring_hom.coe_comp, function.comp_app, inl_ring_hom_apply, inl_mul_inl], rw [inl_mul_coe, coe_mul_inl, mul_comm] end, smul_def' := λ s x, begin induction x using unitization.ind, simp only [mul_add, smul_add, ring_hom.to_fun_eq_coe, ring_hom.coe_comp, function.comp_app, inl_ring_hom_apply, algebra.algebra_map_eq_smul_one], rw [inl_mul_inl, inl_mul_coe, smul_one_mul, inl_smul, coe_smul, smul_one_smul] end, ..(unitization.inl_ring_hom R A).comp (algebra_map S R) } lemma algebra_map_eq_inl_comp : ⇑(algebra_map S (unitization R A)) = inl ∘ algebra_map S R := rfl lemma algebra_map_eq_inl_ring_hom_comp : algebra_map S (unitization R A) = (inl_ring_hom R A).comp (algebra_map S R) := rfl lemma algebra_map_eq_inl : ⇑(algebra_map R (unitization R A)) = inl := rfl lemma algebra_map_eq_inl_hom : algebra_map R (unitization R A) = inl_ring_hom R A := rfl /-- The canonical `R`-algebra projection `unitization R A → R`. -/ @[simps] def fst_hom : unitization R A →ₐ[R] R := { to_fun := fst, map_one' := fst_one, map_mul' := fst_mul, map_zero' := fst_zero, map_add' := fst_add, commutes' := fst_inl A } end algebra section coe /-- The coercion from a non-unital `R`-algebra `A` to its unitization `unitization R A` realized as a non-unital algebra homomorphism. -/ @[simps] def coe_non_unital_alg_hom (R A : Type*) [comm_semiring R] [non_unital_semiring A] [module R A] : A →ₙₐ[R] unitization R A := { to_fun := coe, map_smul' := coe_smul R, map_zero' := coe_zero R, map_add' := coe_add R, map_mul' := coe_mul R } end coe section alg_hom variables {S R A : Type*} [comm_semiring S] [comm_semiring R] [non_unital_semiring A] [module R A] [smul_comm_class R A A] [is_scalar_tower R A A] {B : Type*} [semiring B] [algebra S B] [algebra S R] [distrib_mul_action S A] [is_scalar_tower S R A] {C : Type*} [ring C] [algebra R C] lemma alg_hom_ext {φ ψ : unitization R A →ₐ[S] B} (h : ∀ a : A, φ a = ψ a) (h' : ∀ r, φ (algebra_map R (unitization R A) r) = ψ (algebra_map R (unitization R A) r)) : φ = ψ := begin ext, induction x using unitization.ind, simp only [map_add, ←algebra_map_eq_inl, h, h'], end /-- See note [partially-applied ext lemmas] -/ @[ext] lemma alg_hom_ext' {φ ψ : unitization R A →ₐ[R] C} (h : φ.to_non_unital_alg_hom.comp (coe_non_unital_alg_hom R A) = ψ.to_non_unital_alg_hom.comp (coe_non_unital_alg_hom R A)) : φ = ψ := alg_hom_ext (non_unital_alg_hom.congr_fun h) (by simp [alg_hom.commutes]) /-- Non-unital algebra homomorphisms from `A` into a unital `R`-algebra `C` lift uniquely to `unitization R A →ₐ[R] C`. This is the universal property of the unitization. -/ @[simps apply_apply] def lift : (A →ₙₐ[R] C) ≃ (unitization R A →ₐ[R] C) := { to_fun := λ φ, { to_fun := λ x, algebra_map R C x.fst + φ x.snd, map_one' := by simp only [fst_one, map_one, snd_one, φ.map_zero, add_zero], map_mul' := λ x y, begin induction x using unitization.ind, induction y using unitization.ind, simp only [mul_add, add_mul, coe_mul, fst_add, fst_mul, fst_inl, fst_coe, mul_zero, add_zero, zero_mul, map_mul, snd_add, snd_mul, snd_inl, smul_zero, snd_coe, zero_add, φ.map_add, φ.map_smul, φ.map_mul, zero_smul, zero_add], rw ←algebra.commutes _ (φ x_a), simp only [algebra.algebra_map_eq_smul_one, smul_one_mul, add_assoc], end, map_zero' := by simp only [fst_zero, map_zero, snd_zero, φ.map_zero, add_zero], map_add' := λ x y, begin induction x using unitization.ind, induction y using unitization.ind, simp only [fst_add, fst_inl, fst_coe, add_zero, map_add, snd_add, snd_inl, snd_coe, zero_add, φ.map_add], rw add_add_add_comm, end, commutes' := λ r, by simp only [algebra_map_eq_inl, fst_inl, snd_inl, φ.map_zero, add_zero] }, inv_fun := λ φ, φ.to_non_unital_alg_hom.comp (coe_non_unital_alg_hom R A), left_inv := λ φ, by { ext, simp, }, right_inv := λ φ, unitization.alg_hom_ext' (by { ext, simp }), } lemma lift_symm_apply (φ : unitization R A →ₐ[R] C) (a : A) : unitization.lift.symm φ a = φ a := rfl end alg_hom end unitization
f0c92a2d3bd2270c907c766c0dcb78d2ac27423f
7b66d83f3b69dae0a3dfb684d7ebe5e9e3f3c913
/src/solutions/thursday/morning/groups_rings_fields.lean
5eadb4d779af8119b75393a6e56d91592b395c39
[]
permissive
dpochekutov/lftcm2020
58a09e10f0e638075b97884d3c2612eb90296adb
cdfbf1ac089f21058e523db73f2476c9c98ed16a
refs/heads/master
1,669,226,265,076
1,594,629,725,000
1,594,629,725,000
279,213,346
1
0
MIT
1,594,622,757,000
1,594,615,843,000
null
UTF-8
Lean
false
false
3,275
lean
import linear_algebra.finite_dimensional import ring_theory.algebraic import data.zmod.basic import tactic section exercise1 /- We will warm up with a well-known result: “Subgroups of abelian groups are normal.” Hints for proving this result: * Notice that `normal` is a structure, which you can see by going to the definition. The `constructor` tactic will help you to get started. -/ namespace add_subgroup variables {A : Type*} [add_comm_group A] lemma normal_of_add_comm_group (H : add_subgroup A) : normal H := begin -- sorry constructor, intros x hx y, simpa, -- sorry end end add_subgroup end exercise1 section exercise2 /- The following exercise will not be completely straight-forward. We will prove a result that is not yet in mathlib: “Finite field extensions are algebraic.” Hints for proving this result: * Look up the definition of `finite_dimensional`. * Search the library for useful lemmas about `is_algebraic` and `is_integral`. -/ namespace algebra variables {K L : Type*} [field K] [field L] [algebra K L] [finite_dimensional K L] lemma is_algebraic_of_finite_dimensional : is_algebraic K L := begin -- sorry intro x, rw is_algebraic_iff_is_integral, apply is_integral_of_noetherian', assumption, -- sorry end end algebra end exercise2 section exercise3 /- The next exercise asks to show that a monic polynomial `f ∈ ℤ[X]` is irreducible if it is irreducible modulo a prime `p`. This fact is also not in mathlib. Hint: prove the helper lemma that is stated first. Follow-up question: Can you generalise `irreducible_of_irreducible_mod_prime`? -/ namespace polynomial variables {R S : Type*} [semiring R] [integral_domain S] (φ : R →+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map (f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) : is_unit f := begin -- sorry have key := degree_eq_zero_of_is_unit H, have hφ_lcf : φ (leading_coeff f) ≠ 0, { apply is_unit.ne_zero, apply is_unit.map', assumption }, rw degree_map_eq_of_leading_coeff_ne_zero _ hφ_lcf at key, rw eq_C_of_degree_eq_zero key, apply is_unit.map', rw [eq_C_of_degree_eq_zero key, leading_coeff_C] at hf, exact hf, -- sorry end lemma irreducible_of_irreducible_mod_prime (f : polynomial ℤ) (p : ℕ) [fact p.prime] (h_mon : monic f) (h_irr : irreducible (map (int.cast_ring_hom (zmod p)) f)) : irreducible f := begin -- sorry split, { intro hf, apply h_irr.1, apply is_unit.map', exact hf }, { intros g h Hf, have aux : is_unit (leading_coeff g * leading_coeff h), { rw [← leading_coeff_mul, ← Hf, h_mon.leading_coeff], exact is_unit_one }, have lc_g_unit : is_unit (leading_coeff g), { apply is_unit_of_mul_is_unit_left aux }, have lc_h_unit : is_unit (leading_coeff h), { apply is_unit_of_mul_is_unit_right aux }, rw Hf at h_irr, simp at h_irr, have key_fact := h_irr.2 _ _ rfl, cases key_fact with Hg Hh, { left, apply is_unit_of_is_unit_leading_coeff_of_is_unit_map _ g lc_g_unit Hg }, { right, apply is_unit_of_is_unit_leading_coeff_of_is_unit_map _ h lc_h_unit Hh } } -- sorry end end polynomial end exercise3 example : true := begin exact x end
5920008d425ed901b5e9e04cd5673ecd350b3d68
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/initial_seg.lean
25d3a21cfd946d95108bd0fd9364fdcedfd1e247
[ "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
18,106
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import order.rel_iso import order.well_founded /-! # Initial and principal segments This file defines initial and principal segments. ## Main definitions * `initial_seg r s`: type of order embeddings of `r` into `s` for which the range is an initial segment (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). It is denoted by `r ≼i s`. * `principal_seg r s`: Type of order embeddings of `r` into `s` for which the range is a principal segment, i.e., an interval of the form `(-∞, top)` for some element `top`. It is denoted by `r ≺i s`. ## Notations These notations belong to the `initial_seg` locale. * `r ≼i s`: the type of initial segment embeddings of `r` into `s`. * `r ≺i s`: the type of principal segment embeddings of `r` into `s`. -/ /-! ### Initial segments Order embeddings whose range is an initial segment of `s` (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). The type of these embeddings from `r` to `s` is called `initial_seg r s`, and denoted by `r ≼i s`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} open function /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≼i s` is an order embedding whose range is an initial segment. That is, whenever `b < f a` in `β` then `b` is in the range of `f`. -/ structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (init : ∀ a b, s b (to_rel_embedding a) → ∃ a', to_rel_embedding a' = b) localized "infix (name := initial_seg) ` ≼i `:25 := initial_seg" in initial_seg namespace initial_seg instance : has_coe (r ≼i s) (r ↪r s) := ⟨initial_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≼i s) (λ _, α → β) := ⟨λ f x, (f : r ↪r s) x⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (o) : (@initial_seg.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≼i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ↪r s) : α → β) = f := rfl theorem init' (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b := f.init _ _ theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r ↪r s).map_rel_iff.1 (e.symm ▸ h)⟩, λ ⟨a', e, h⟩, e ▸ (f : r ↪r s).map_rel_iff.2 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃r s) : r ≼i s := ⟨f, λ a b h, ⟨f.symm b, rel_iso.apply_symm_apply f _⟩⟩ /-- The identity function shows that `≼i` is reflexive -/ @[refl] protected def refl (r : α → α → Prop) : r ≼i r := ⟨rel_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩ instance (r : α → α → Prop) : inhabited (r ≼i r) := ⟨initial_seg.refl r⟩ /-- Composition of functions shows that `≼i` is transitive -/ @[trans] protected def trans (f : r ≼i s) (g : s ≼i t) : r ≼i t := ⟨f.1.trans g.1, λ a c h, begin simp at h ⊢, rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.1.map_rel_iff.1 h, rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼i s) (g : s ≼i t) (a : α) : (f.trans g) a = g (f a) := rfl theorem unique_of_trichotomous_of_irrefl [is_trichotomous β s] [is_irrefl β s] : well_founded r → subsingleton (r ≼i s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : α → β) = g, { cases f, cases g, congr, exact rel_embedding.coe_fn_injective this }, funext a, have := h a, induction this with a H IH, refine extensional_of_trichotomous_of_irrefl s (λ x, ⟨λ h, _, λ h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r ↪r s).map_rel_iff.2 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r ↪r s).map_rel_iff.2 h' } end⟩ instance [is_well_order β s] : subsingleton (r ≼i s) := ⟨λ a, @subsingleton.elim _ (unique_of_trichotomous_of_irrefl (@rel_embedding.well_founded _ _ r s a is_well_founded.wf)) a⟩ protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f := initial_seg.eq (f.trans g) (initial_seg.refl _) /-- If we have order embeddings between `α` and `β` whose images are initial segments, and `β` is a well-order then `α` and `β` are order-isomorphic. -/ def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃r s := by haveI := f.to_rel_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, λ _ _, f.map_rel_iff'⟩ @[simp] theorem antisymm_to_fun [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl @[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f := rel_iso.coe_fn_injective rfl theorem eq_or_principal [is_well_order β s] (f : r ≼i s) : surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x := or_iff_not_imp_right.2 $ λ h b, acc.rec_on (is_well_founded.wf.apply b : acc s b) $ λ x H IH, not_forall_not.1 $ λ hn, h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (λ hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p := ⟨rel_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- Initial segment from an empty type. -/ def of_is_empty (r : α → α → Prop) (s : β → β → Prop) [is_empty α] : r ≼i s := ⟨rel_embedding.of_is_empty r s, is_empty_elim⟩ /-- Initial segment embedding of an order `r` into the disjoint union of `r` and `s`. -/ def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s := ⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, sum.lex_inl_inl⟩, λ a b, by cases b; [exact λ _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩ @[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg /-! ### Principal segments Order embeddings whose range is a principal segment of `s` (i.e., an interval of the form `(-∞, top)` for some element `top` of `β`). The type of these embeddings from `r` to `s` is called `principal_seg r s`, and denoted by `r ≺i s`. Principal segments are in particular initial segments. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≺i s` is an order embedding whose range is an open interval `(-∞, top)` for some element `top` of `β`. Such order embeddings are called principal segments -/ @[nolint has_nonempty_instance] structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (top : β) (down' : ∀ b, s b top ↔ ∃ a, to_rel_embedding a = b) localized "infix (name := principal_seg) ` ≺i `:25 := principal_seg" in initial_seg namespace principal_seg instance : has_coe (r ≺i s) (r ↪r s) := ⟨principal_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≺i s) (λ _, α → β) := ⟨λ f, f⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (t o) : (@principal_seg.mk _ _ r s f t o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≺i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≺i s) : ((f : r ↪r s) : α → β) = f := rfl theorem down (f : r ≺i s) : ∀ {b : β}, s b f.top ↔ ∃ a, f a = b := f.down' theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.down.2 ⟨_, rfl⟩ theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b := f.down.1 $ trans h $ f.lt_top _ /-- A principal segment is in particular an initial segment. -/ instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) := ⟨λ f, ⟨f.to_rel_embedding, λ a b, f.init⟩⟩ theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := @initial_seg.init_iff α β r s f a b theorem irrefl {r : α → α → Prop} [is_well_order α r] (f : r ≺i r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end instance (r : α → α → Prop) [is_well_order α r] : is_empty (r ≺i r) := ⟨λ f, f.irrefl⟩ /-- Composition of a principal segment with an initial segment, as a principal segment -/ def lt_le (f : r ≺i s) (g : s ≼i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, λ a, by simp only [g.init_iff, f.down', exists_and_distrib_left.symm, exists_swap, rel_embedding.trans_apply, exists_eq_right']; refl⟩ @[simp] theorem lt_le_apply (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl /-- Composition of two principal segments as a principal segment -/ @[trans] protected def trans [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t := lt_le f g @[simp] theorem trans_apply [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl /-- Composition of an order isomorphism with a principal segment, as a principal segment -/ def equiv_lt (f : r ≃r s) (g : s ≺i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g.top, λ c, suffices (∃ (a : β), g a = c) ↔ ∃ (a : α), g (f a) = c, by simpa [g.down], ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, rel_iso.apply_symm_apply, rel_iso.coe_coe_fn]⟩, λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩ /-- Composition of a principal segment with an order isomorphism, as a principal segment -/ def lt_equiv {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : principal_seg r s) (g : s ≃r t) : principal_seg r t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, begin intro x, rw [← g.apply_symm_apply x, g.map_rel_iff, f.down', exists_congr], intro y, exact ⟨congr_arg g, λ h, g.to_equiv.bijective.1 h⟩ end⟩ @[simp] theorem equiv_lt_apply (f : r ≃r s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem equiv_lt_top (f : r ≃r s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl /-- Given a well order `s`, there is a most one principal segment embedding of `r` into `s`. -/ instance [is_well_order β s] : subsingleton (r ≺i s) := ⟨λ f g, begin have ef : (f : α → β) = g, { show ((f : r ≼i s) : α → β) = g, rw @subsingleton.elim _ _ (f : r ≼i s) g, refl }, have et : f.top = g.top, { refine extensional_of_trichotomous_of_irrefl s (λ x, _), simp only [f.down, g.down, ef, coe_fn_to_rel_embedding] }, cases f, cases g, have := rel_embedding.coe_fn_injective ef; congr' end⟩ theorem top_eq [is_well_order γ t] (e : r ≃r s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl lemma top_lt_top {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} [is_well_order γ t] (f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top := by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top } /-- Any element of a well order yields a principal segment -/ def of_element {α : Type*} (r : α → α → Prop) (a : α) : subrel r {b | r b a} ≺i r := ⟨subrel.rel_embedding _ _, a, λ b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) (a : α) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) (a : α) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set β) (f : r ≺i s) (H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p := ⟨rel_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩, f.down.trans $ exists_congr $ λ a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl /-- Principal segment from an empty type into a type with a minimal element. -/ def of_is_empty (r : α → α → Prop) [is_empty α] {b : β} (H : ∀ b', ¬ s b' b) : r ≺i s := { top := b, down' := by simp [H], ..rel_embedding.of_is_empty r s } @[simp] theorem of_is_empty_top (r : α → α → Prop) [is_empty α] {b : β} (H : ∀ b', ¬ s b' b) : (of_is_empty r H).top = b := rfl /-- Principal segment from the empty relation on `pempty` to the empty relation on `punit`. -/ @[reducible] def pempty_to_punit : @empty_relation pempty ≺i @empty_relation punit := @of_is_empty _ _ empty_relation _ _ punit.star $ λ x, not_false end principal_seg /-! ### Properties of initial and principal segments -/ /-- To an initial segment taking values in a well order, one can associate either a principal segment (if the range is not everything, hence one can take as top the minimum of the complement of the range) or an order isomorphism (if the range is everything). -/ noncomputable def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) : (r ≺i s) ⊕ (r ≃r s) := begin by_cases h : surjective f, { exact sum.inr (rel_iso.of_surjective f h) }, { have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, exact sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ } end theorem initial_seg.lt_or_eq_apply_left [is_well_order β s] (f : r ≼i s) (g : r ≺i s) (a : α) : g a = f a := @initial_seg.eq α β r s _ g f a theorem initial_seg.lt_or_eq_apply_right [is_well_order β s] (f : r ≼i s) (g : r ≃r s) (a : α) : g a = f a := initial_seg.eq (initial_seg.of_iso g) f a /-- Composition of an initial segment taking values in a well order and a principal segment. -/ noncomputable def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left] }, { simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right] } end namespace rel_embedding /-- Given an order embedding into a well order, collapse the order embedding by filling the gaps, to obtain an initial segment. Here, we construct the collapsed order embedding pointwise, but the proof of the fact that it is an initial segment will be given in `collapse`. -/ noncomputable def collapse_F [is_well_order β s] (f : r ↪r s) : Π a, {b // ¬ s (f a) b} := (rel_embedding.well_founded f $ is_well_founded.wf).fix $ λ a IH, begin let S := {b | ∀ a h, s (IH a h).1 b}, have : f a ∈ S, from λ a' h, ((trichotomous _ _) .resolve_left $ λ h', (IH a' h).2 $ trans (f.map_rel_iff.2 h) h') .resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.map_rel_iff.2 h, exact ⟨is_well_founded.wf.min S ⟨_, this⟩, is_well_founded.wf.not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order β s] (f : r ↪r s) {a : α} : ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order β s] (f : r ↪r s) (a : α) {b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding into a well order, by collapsing it to fill the gaps. -/ noncomputable def collapse [is_well_order β s] (f : r ↪r s) : r ≼i s := by haveI := rel_embedding.is_well_order f; exact ⟨rel_embedding.of_monotone (λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f), λ a b, acc.rec_on (is_well_founded.wf.apply b : acc s b) (λ b H IH a h, begin let S := {a | ¬ s (collapse_F f a).1 b}, have : S.nonempty := ⟨_, asymm h⟩, existsi (is_well_founded.wf : well_founded r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_founded.wf : well_founded r).min_mem S this }, { refine collapse_F.not_lt f _ (λ a' h', _), by_contradiction hn, exact is_well_founded.wf.not_lt_min S this hn h' } end) a⟩ theorem collapse_apply [is_well_order β s] (f : r ↪r s) (a) : collapse f a = (collapse_F f a).1 := rfl end rel_embedding
17ca8bf9e9ca0b219b47cd258a3e3b611b2646c8
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/order/atoms.lean
7f756bf66727b31a0e9a72b7a797edfffbeb6c76
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,226
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 order.complete_boolean_algebra import order.modular_lattice import data.fintype.basic /-! # Atoms, Coatoms, and Simple Lattices This module defines atoms, which are minimal non-`⊥` elements in bounded lattices, simple lattices, which are lattices with only two elements, and related ideas. ## Main definitions ### Atoms and Coatoms * `is_atom a` indicates that the only element below `a` is `⊥`. * `is_coatom a` indicates that the only element above `a` is `⊤`. ### Atomic and Atomistic Lattices * `is_atomic` indicates that every element other than `⊥` is above an atom. * `is_coatomic` indicates that every element other than `⊤` is below a coatom. * `is_atomistic` indicates that every element is the `Sup` of a set of atoms. * `is_coatomistic` indicates that every element is the `Inf` of a set of coatoms. ### Simple Lattices * `is_simple_lattice` indicates that a bounded lattice has only two elements, `⊥` and `⊤`. * `is_simple_lattice.bounded_distrib_lattice` * Given an instance of `is_simple_lattice`, we provide the following definitions. These are not made global instances as they contain data : * `is_simple_lattice.boolean_algebra` * `is_simple_lattice.complete_lattice` * `is_simple_lattice.complete_boolean_algebra` ## Main results * `is_atom_dual_iff_is_coatom` and `is_coatom_dual_iff_is_atom` express the (definitional) duality of `is_atom` and `is_coatom`. * `is_simple_lattice_iff_is_atom_top` and `is_simple_lattice_iff_is_coatom_bot` express the connection between atoms, coatoms, and simple lattices * `is_compl.is_atom_iff_is_coatom` and `is_compl.is_coatom_if_is_atom`: In a modular bounded lattice, a complement of an atom is a coatom and vice versa. * ``is_atomic_iff_is_coatomic`: A modular complemented lattice is atomic iff it is coatomic. -/ variable {α : Type*} section atoms section is_atom variable [order_bot α] /-- An atom of an `order_bot` is an element with no other element between it and `⊥`, which is not `⊥`. -/ def is_atom (a : α) : Prop := a ≠ ⊥ ∧ (∀ b, b < a → b = ⊥) lemma eq_bot_or_eq_of_le_atom {a b : α} (ha : is_atom a) (hab : b ≤ a) : b = ⊥ ∨ b = a := hab.lt_or_eq.imp_left (ha.2 b) lemma is_atom.Iic {x a : α} (ha : is_atom a) (hax : a ≤ x) : is_atom (⟨a, hax⟩ : set.Iic x) := ⟨λ con, ha.1 (subtype.mk_eq_mk.1 con), λ ⟨b, hb⟩ hba, subtype.mk_eq_mk.2 (ha.2 b hba)⟩ lemma is_atom.of_is_atom_coe_Iic {x : α} {a : set.Iic x} (ha : is_atom a) : is_atom (a : α) := ⟨λ con, ha.1 (subtype.ext con), λ b hba, subtype.mk_eq_mk.1 (ha.2 ⟨b, hba.le.trans a.prop⟩ hba)⟩ end is_atom section is_coatom variable [order_top α] /-- A coatom of an `order_top` is an element with no other element between it and `⊤`, which is not `⊤`. -/ def is_coatom (a : α) : Prop := a ≠ ⊤ ∧ (∀ b, a < b → b = ⊤) lemma eq_top_or_eq_of_coatom_le {a b : α} (ha : is_coatom a) (hab : a ≤ b) : b = ⊤ ∨ b = a := hab.lt_or_eq.imp (ha.2 b) eq_comm.2 lemma is_coatom.Ici {x a : α} (ha : is_coatom a) (hax : x ≤ a) : is_coatom (⟨a, hax⟩ : set.Ici x) := ⟨λ con, ha.1 (subtype.mk_eq_mk.1 con), λ ⟨b, hb⟩ hba, subtype.mk_eq_mk.2 (ha.2 b hba)⟩ lemma is_coatom.of_is_coatom_coe_Ici {x : α} {a : set.Ici x} (ha : is_coatom a) : is_coatom (a : α) := ⟨λ con, ha.1 (subtype.ext con), λ b hba, subtype.mk_eq_mk.1 (ha.2 ⟨b, le_trans a.prop hba.le⟩ hba)⟩ end is_coatom section pairwise lemma is_atom.inf_eq_bot_of_ne [semilattice_inf_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : a ⊓ b = ⊥ := or.elim (eq_bot_or_eq_of_le_atom ha inf_le_left) id (λ h1, or.elim (eq_bot_or_eq_of_le_atom hb inf_le_right) id (λ h2, false.rec _ (hab (le_antisymm (inf_eq_left.mp h1) (inf_eq_right.mp h2))))) lemma is_atom.disjoint_of_ne [semilattice_inf_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : disjoint a b := disjoint_iff.mpr (is_atom.inf_eq_bot_of_ne ha hb hab) lemma is_coatom.sup_eq_top_of_ne [semilattice_sup_top α] {a b : α} (ha : is_coatom a) (hb : is_coatom b) (hab : a ≠ b) : a ⊔ b = ⊤ := or.elim (eq_top_or_eq_of_coatom_le ha le_sup_left) id (λ h1, or.elim (eq_top_or_eq_of_coatom_le hb le_sup_right) id (λ h2, false.rec _ (hab (le_antisymm (sup_eq_right.mp h2) (sup_eq_left.mp h1))))) end pairwise variable {a : α} @[simp] lemma is_coatom_dual_iff_is_atom [order_bot α] : is_coatom (order_dual.to_dual a) ↔ is_atom a := iff.rfl @[simp] lemma is_atom_dual_iff_is_coatom [order_top α] : is_atom (order_dual.to_dual a) ↔ is_coatom a := iff.rfl end atoms section atomic variable (α) /-- A lattice is atomic iff every element other than `⊥` has an atom below it. -/ class is_atomic [order_bot α] : Prop := (eq_bot_or_exists_atom_le : ∀ (b : α), b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b) /-- A lattice is coatomic iff every element other than `⊤` has a coatom above it. -/ class is_coatomic [order_top α] : Prop := (eq_top_or_exists_le_coatom : ∀ (b : α), b = ⊤ ∨ ∃ (a : α), is_coatom a ∧ b ≤ a) export is_atomic (eq_bot_or_exists_atom_le) is_coatomic (eq_top_or_exists_le_coatom) variable {α} @[simp] theorem is_coatomic_dual_iff_is_atomic [order_bot α] : is_coatomic (order_dual α) ↔ is_atomic α := ⟨λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩, λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩⟩ @[simp] theorem is_atomic_dual_iff_is_coatomic [order_top α] : is_atomic (order_dual α) ↔ is_coatomic α := ⟨λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩, λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩⟩ namespace is_atomic variables [order_bot α] [is_atomic α] instance is_coatomic_dual : is_coatomic (order_dual α) := is_coatomic_dual_iff_is_atomic.2 ‹is_atomic α› instance {x : α} : is_atomic (set.Iic x) := ⟨λ ⟨y, hy⟩, (eq_bot_or_exists_atom_le y).imp subtype.mk_eq_mk.2 (λ ⟨a, ha, hay⟩, ⟨⟨a, hay.trans hy⟩, ha.Iic (hay.trans hy), hay⟩)⟩ end is_atomic namespace is_coatomic variables [order_top α] [is_coatomic α] instance is_coatomic : is_atomic (order_dual α) := is_atomic_dual_iff_is_coatomic.2 ‹is_coatomic α› instance {x : α} : is_coatomic (set.Ici x) := ⟨λ ⟨y, hy⟩, (eq_top_or_exists_le_coatom y).imp subtype.mk_eq_mk.2 (λ ⟨a, ha, hay⟩, ⟨⟨a, le_trans hy hay⟩, ha.Ici (le_trans hy hay), hay⟩)⟩ end is_coatomic theorem is_atomic_iff_forall_is_atomic_Iic [order_bot α] : is_atomic α ↔ ∀ (x : α), is_atomic (set.Iic x) := ⟨@is_atomic.set.Iic.is_atomic _ _, λ h, ⟨λ x, ((@eq_bot_or_exists_atom_le _ _ (h x)) (⊤ : set.Iic x)).imp subtype.mk_eq_mk.1 (exists_imp_exists' coe (λ ⟨a, ha⟩, and.imp_left (is_atom.of_is_atom_coe_Iic)))⟩⟩ theorem is_coatomic_iff_forall_is_coatomic_Ici [order_top α] : is_coatomic α ↔ ∀ (x : α), is_coatomic (set.Ici x) := is_atomic_dual_iff_is_coatomic.symm.trans $ is_atomic_iff_forall_is_atomic_Iic.trans $ forall_congr (λ x, is_coatomic_dual_iff_is_atomic.symm.trans iff.rfl) end atomic section atomistic variables (α) [complete_lattice α] /-- A lattice is atomistic iff every element is a `Sup` of a set of atoms. -/ class is_atomistic : Prop := (eq_Sup_atoms : ∀ (b : α), ∃ (s : set α), b = Sup s ∧ ∀ a, a ∈ s → is_atom a) /-- A lattice is coatomistic iff every element is an `Inf` of a set of coatoms. -/ class is_coatomistic : Prop := (eq_Inf_coatoms : ∀ (b : α), ∃ (s : set α), b = Inf s ∧ ∀ a, a ∈ s → is_coatom a) export is_atomistic (eq_Sup_atoms) is_coatomistic (eq_Inf_coatoms) variable {α} @[simp] theorem is_coatomistic_dual_iff_is_atomistic : is_coatomistic (order_dual α) ↔ is_atomistic α := ⟨λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩, λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩⟩ @[simp] theorem is_atomistic_dual_iff_is_coatomistic : is_atomistic (order_dual α) ↔ is_coatomistic α := ⟨λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩, λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩⟩ namespace is_atomistic instance is_coatomistic_dual [h : is_atomistic α] : is_coatomistic (order_dual α) := is_coatomistic_dual_iff_is_atomistic.2 h variable [is_atomistic α] @[priority 100] instance : is_atomic α := ⟨λ b, by { rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩, cases s.eq_empty_or_nonempty with h h, { simp [h] }, { exact or.intro_right _ ⟨h.some, hs _ h.some_spec, le_Sup h.some_spec⟩ } } ⟩ end is_atomistic section is_atomistic variables [is_atomistic α] @[simp] theorem Sup_atoms_le_eq (b : α) : Sup {a : α | is_atom a ∧ a ≤ b} = b := begin rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩, exact le_antisymm (Sup_le (λ _, and.right)) (Sup_le_Sup (λ a ha, ⟨hs a ha, le_Sup ha⟩)), end @[simp] theorem Sup_atoms_eq_top : Sup {a : α | is_atom a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_atoms_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_atom_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, is_atom c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_atoms_le_eq a, ← Sup_atoms_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ end is_atomistic namespace is_coatomistic instance is_atomistic_dual [h : is_coatomistic α] : is_atomistic (order_dual α) := is_atomistic_dual_iff_is_coatomistic.2 h variable [is_coatomistic α] @[priority 100] instance : is_coatomic α := ⟨λ b, by { rcases eq_Inf_coatoms b with ⟨s, rfl, hs⟩, cases s.eq_empty_or_nonempty with h h, { simp [h] }, { exact or.intro_right _ ⟨h.some, hs _ h.some_spec, Inf_le h.some_spec⟩ } } ⟩ end is_coatomistic end atomistic /-- A lattice is simple iff it has only two elements, `⊥` and `⊤`. -/ class is_simple_lattice (α : Type*) [bounded_lattice α] extends nontrivial α : Prop := (eq_bot_or_eq_top : ∀ (a : α), a = ⊥ ∨ a = ⊤) export is_simple_lattice (eq_bot_or_eq_top) theorem is_simple_lattice_iff_is_simple_lattice_order_dual [bounded_lattice α] : is_simple_lattice α ↔ is_simple_lattice (order_dual α) := begin split; intro i; haveI := i, { exact { exists_pair_ne := @exists_pair_ne α _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top ((order_dual.of_dual a)) : _ ∨ _) } }, { exact { exists_pair_ne := @exists_pair_ne (order_dual α) _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top (order_dual.to_dual a)) } } end section is_simple_lattice variables [bounded_lattice α] [is_simple_lattice α] instance : is_simple_lattice (order_dual α) := is_simple_lattice_iff_is_simple_lattice_order_dual.1 (by apply_instance) @[simp] lemma is_atom_top : is_atom (⊤ : α) := ⟨top_ne_bot, λ a ha, or.resolve_right (eq_bot_or_eq_top a) (ne_of_lt ha)⟩ @[simp] lemma is_coatom_bot : is_coatom (⊥ : α) := is_atom_dual_iff_is_coatom.1 is_atom_top end is_simple_lattice namespace is_simple_lattice section bounded_lattice variables [bounded_lattice α] [is_simple_lattice α] /-- A simple `bounded_lattice` is also distributive. -/ @[priority 100] instance : bounded_distrib_lattice α := { le_sup_inf := λ x y z, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp }, .. (infer_instance : bounded_lattice α) } @[priority 100] instance : is_atomic α := ⟨λ b, (eq_bot_or_eq_top b).imp_right (λ h, ⟨⊤, ⟨is_atom_top, ge_of_eq h⟩⟩)⟩ @[priority 100] instance : is_coatomic α := is_atomic_dual_iff_is_coatomic.1 is_simple_lattice.is_atomic end bounded_lattice /- It is important that in this section `is_simple_lattice` is the last type-class argument. -/ section decidable_eq variables [decidable_eq α] [bounded_lattice α] [is_simple_lattice α] /-- Every simple lattice is order-isomorphic to `bool`. -/ def order_iso_bool : α ≃o bool := { to_fun := λ x, x = ⊤, inv_fun := λ x, cond x ⊤ ⊥, left_inv := λ x, by { rcases (eq_bot_or_eq_top x) with rfl | rfl; simp [bot_ne_top] }, right_inv := λ x, by { cases x; simp [bot_ne_top] }, map_rel_iff' := λ a b, begin rcases (eq_bot_or_eq_top a) with rfl | rfl, { simp [bot_ne_top] }, { rcases (eq_bot_or_eq_top b) with rfl | rfl, { simp [bot_ne_top.symm, bot_ne_top, bool.ff_lt_tt] }, { simp [bot_ne_top] } } end } /- It is important that `is_simple_lattice` is the last type-class argument of this instance, so that type-class inference fails quickly if it doesn't apply. -/ @[priority 200] instance : fintype α := fintype.of_equiv bool (order_iso_bool.to_equiv).symm /-- A simple `bounded_lattice` is also a `boolean_algebra`. -/ protected def boolean_algebra : boolean_algebra α := { compl := λ x, if x = ⊥ then ⊤ else ⊥, sdiff := λ x y, if x = ⊤ ∧ y = ⊥ then ⊤ else ⊥, sdiff_eq := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; simp [bot_ne_top, has_sdiff.sdiff, compl], inf_compl_le_bot := λ x, by rcases eq_bot_or_eq_top x with rfl | rfl; simp, top_le_sup_compl := λ x, by rcases eq_bot_or_eq_top x with rfl | rfl; simp, sup_inf_sdiff := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; rcases eq_bot_or_eq_top y with rfl | rfl; simp [bot_ne_top], inf_inf_sdiff := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; rcases eq_bot_or_eq_top y with rfl | rfl; simp, .. is_simple_lattice.bounded_distrib_lattice } end decidable_eq variables [bounded_lattice α] [is_simple_lattice α] open_locale classical /-- A simple `bounded_lattice` is also complete. -/ protected noncomputable def complete_lattice : complete_lattice α := { Sup := λ s, if ⊤ ∈ s then ⊤ else ⊥, Inf := λ s, if ⊥ ∈ s then ⊥ else ⊤, le_Sup := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_pos h } }, Sup_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_neg, intro con, exact bot_ne_top (eq_top_iff.2 (h ⊤ con)) }, { exact le_top } }, Inf_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_pos h }, { exact le_top } }, le_Inf := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_neg, intro con, exact top_ne_bot (eq_bot_iff.2 (h ⊥ con)) } }, .. (infer_instance : bounded_lattice α) } /-- A simple `bounded_lattice` is also a `complete_boolean_algebra`. -/ protected noncomputable def complete_boolean_algebra : complete_boolean_algebra α := { infi_sup_le_sup_Inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_sup_eq, ← Inf_eq_infi], apply le_refl }, { simp only [top_sup_eq, le_top] }, }, inf_Sup_le_supr_inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_inf_eq, bot_le] }, { simp only [top_inf_eq, ← Sup_eq_supr], apply le_refl } }, .. is_simple_lattice.complete_lattice, .. is_simple_lattice.boolean_algebra } end is_simple_lattice namespace is_simple_lattice variables [complete_lattice α] [is_simple_lattice α] set_option default_priority 100 instance : is_atomistic α := ⟨λ b, (eq_bot_or_eq_top b).elim (λ h, ⟨∅, ⟨h.trans Sup_empty.symm, λ a ha, false.elim (set.not_mem_empty _ ha)⟩⟩) (λ h, ⟨{⊤}, h.trans Sup_singleton.symm, λ a ha, (set.mem_singleton_iff.1 ha).symm ▸ is_atom_top⟩)⟩ instance : is_coatomistic α := is_atomistic_dual_iff_is_coatomistic.1 is_simple_lattice.is_atomistic end is_simple_lattice namespace fintype namespace is_simple_lattice variables [bounded_lattice α] [is_simple_lattice α] [decidable_eq α] lemma univ : (finset.univ : finset α) = {⊤, ⊥} := begin change finset.map _ (finset.univ : finset bool) = _, rw fintype.univ_bool, simp only [finset.map_insert, function.embedding.coe_fn_mk, finset.map_singleton], refl, end lemma card : fintype.card α = 2 := (fintype.of_equiv_card _).trans fintype.card_bool end is_simple_lattice end fintype namespace bool instance : is_simple_lattice bool := ⟨λ a, begin rw [← finset.mem_singleton, or.comm, ← finset.mem_insert, top_eq_tt, bot_eq_ff, ← fintype.univ_bool], apply finset.mem_univ, end⟩ end bool theorem is_simple_lattice_iff_is_atom_top [bounded_lattice α] : is_simple_lattice α ↔ is_atom (⊤ : α) := ⟨λ h, @is_atom_top _ _ h, λ h, { exists_pair_ne := ⟨⊤, ⊥, h.1⟩, eq_bot_or_eq_top := λ a, ((eq_or_lt_of_le (@le_top _ _ a)).imp_right (h.2 a)).symm }⟩ theorem is_simple_lattice_iff_is_coatom_bot [bounded_lattice α] : is_simple_lattice α ↔ is_coatom (⊥ : α) := is_simple_lattice_iff_is_simple_lattice_order_dual.trans is_simple_lattice_iff_is_atom_top namespace set theorem is_simple_lattice_Iic_iff_is_atom [bounded_lattice α] {a : α} : is_simple_lattice (Iic a) ↔ is_atom a := is_simple_lattice_iff_is_atom_top.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ theorem is_simple_lattice_Ici_iff_is_coatom [bounded_lattice α] {a : α} : is_simple_lattice (Ici a) ↔ is_coatom a := is_simple_lattice_iff_is_coatom_bot.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ end set namespace order_iso @[simp] lemma is_atom_iff [order_bot α] {β : Type*} [order_bot β] (f : α ≃o β) (a : α) : is_atom (f a) ↔ is_atom a := and_congr (not_congr ⟨λ h, f.injective (f.map_bot.symm ▸ h), λ h, f.map_bot ▸ (congr rfl h)⟩) ⟨λ h b hb, f.injective ((h (f b) ((f : α ↪o β).lt_iff_lt.2 hb)).trans f.map_bot.symm), λ h b hb, f.symm.injective begin rw f.symm.map_bot, apply h, rw [← f.symm_apply_apply a], exact (f.symm : β ↪o α).lt_iff_lt.2 hb, end⟩ @[simp] lemma is_coatom_iff [order_top α] {β : Type*} [order_top β] (f : α ≃o β) (a : α) : is_coatom (f a) ↔ is_coatom a := f.dual.is_atom_iff a lemma is_simple_lattice_iff [bounded_lattice α] {β : Type*} [bounded_lattice β] (f : α ≃o β) : is_simple_lattice α ↔ is_simple_lattice β := by rw [is_simple_lattice_iff_is_atom_top, is_simple_lattice_iff_is_atom_top, ← f.is_atom_iff ⊤, f.map_top] lemma is_simple_lattice [bounded_lattice α] {β : Type*} [bounded_lattice β] [h : is_simple_lattice β] (f : α ≃o β) : is_simple_lattice α := f.is_simple_lattice_iff.mpr h lemma is_atomic_iff [order_bot α] {β : Type*} [order_bot β] (f : α ≃o β) : is_atomic α ↔ is_atomic β := begin suffices : (∀ b : α, b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b) ↔ (∀ b : β, b = ⊥ ∨ ∃ (a : β), is_atom a ∧ a ≤ b), from ⟨λ ⟨p⟩, ⟨this.mp p⟩, λ ⟨p⟩, ⟨this.mpr p⟩⟩, apply f.to_equiv.forall_congr, simp_rw [rel_iso.coe_fn_to_equiv], intro b, apply or_congr, { rw [f.apply_eq_iff_eq_symm_apply, map_bot], }, { split, { exact λ ⟨a, ha⟩, ⟨f a, ⟨(f.is_atom_iff a).mpr ha.1, f.le_iff_le.mpr ha.2⟩⟩, }, { rintros ⟨b, ⟨hb1, hb2⟩⟩, refine ⟨f.symm b, ⟨(f.symm.is_atom_iff b).mpr hb1, _⟩⟩, rwa [←f.le_iff_le, f.apply_symm_apply], }, }, end lemma is_coatomic_iff [order_top α] {β : Type*} [order_top β] (f : α ≃o β) : is_coatomic α ↔ is_coatomic β := by { rw [←is_atomic_dual_iff_is_coatomic, ←is_atomic_dual_iff_is_coatomic], exact f.dual.is_atomic_iff } end order_iso section is_modular_lattice variables [bounded_lattice α] [is_modular_lattice α] namespace is_compl variables {a b : α} (hc : is_compl a b) include hc lemma is_atom_iff_is_coatom : is_atom a ↔ is_coatom b := set.is_simple_lattice_Iic_iff_is_atom.symm.trans $ hc.Iic_order_iso_Ici.is_simple_lattice_iff.trans set.is_simple_lattice_Ici_iff_is_coatom lemma is_coatom_iff_is_atom : is_coatom a ↔ is_atom b := hc.symm.is_atom_iff_is_coatom.symm end is_compl variables [is_complemented α] lemma is_coatomic_of_is_atomic_of_is_complemented_of_is_modular [is_atomic α] : is_coatomic α := ⟨λ x, begin rcases exists_is_compl x with ⟨y, xy⟩, apply (eq_bot_or_exists_atom_le y).imp _ _, { rintro rfl, exact eq_top_of_is_compl_bot xy }, { rintro ⟨a, ha, ay⟩, rcases exists_is_compl (xy.symm.Iic_order_iso_Ici ⟨a, ay⟩) with ⟨⟨b, xb⟩, hb⟩, refine ⟨↑(⟨b, xb⟩ : set.Ici x), is_coatom.of_is_coatom_coe_Ici _, xb⟩, rw [← hb.is_atom_iff_is_coatom, order_iso.is_atom_iff], apply ha.Iic } end⟩ lemma is_atomic_of_is_coatomic_of_is_complemented_of_is_modular [is_coatomic α] : is_atomic α := is_coatomic_dual_iff_is_atomic.1 is_coatomic_of_is_atomic_of_is_complemented_of_is_modular theorem is_atomic_iff_is_coatomic : is_atomic α ↔ is_coatomic α := ⟨λ h, @is_coatomic_of_is_atomic_of_is_complemented_of_is_modular _ _ _ _ h, λ h, @is_atomic_of_is_coatomic_of_is_complemented_of_is_modular _ _ _ _ h⟩ end is_modular_lattice
2859e5596c7eed189c69c1ffdeba745b97baa554
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Compiler/IR/ElimDeadBranches.lean
8cc829e4b43c61910afde46711e2e510ea445e1d
[ "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
11,689
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.Format import Lean.Compiler.IR.Basic import Lean.Compiler.IR.CompilerM namespace Lean.IR.UnreachableBranches /-- Value used in the abstract interpreter -/ inductive Value where | bot -- undefined | top -- any value | ctor (i : CtorInfo) (vs : Array Value) | choice (vs : List Value) deriving Inhabited, Repr protected partial def Value.toFormat : Value → Format | Value.bot => "⊥" | Value.top => "⊤" | Value.ctor info vs => if vs.isEmpty then format info.name else Format.paren <| format info.name ++ Std.Format.join (vs.toList.map fun v => " " ++ Value.toFormat v) | Value.choice vs => Format.paren <| Std.Format.joinSep (vs.map Value.toFormat) " | " instance : ToFormat Value where format := Value.toFormat instance : ToString Value where toString v := toString (format v) namespace Value protected partial def beq : Value → Value → Bool | bot, bot => true | top, top => true | ctor i₁ vs₁, ctor i₂ vs₂ => i₁ == i₂ && Array.isEqv vs₁ vs₂ Value.beq | choice vs₁, choice vs₂ => vs₁.all (fun v₁ => vs₂.any fun v₂ => Value.beq v₁ v₂) && vs₂.all (fun v₂ => vs₁.any fun v₁ => Value.beq v₁ v₂) | _, _ => false instance : BEq Value := ⟨Value.beq⟩ partial def addChoice (merge : Value → Value → Value) : List Value → Value → List Value | [], v => [v] | v₁@(ctor i₁ vs₁) :: cs, v₂@(ctor i₂ vs₂) => if i₁ == i₂ then merge v₁ v₂ :: cs else v₁ :: addChoice merge cs v₂ | _, _ => panic! "invalid addChoice" partial def merge (v₁ v₂ : Value) : Value := match v₁, v₂ with | bot, v => v | v, bot => v | top, _ => top | _, top => top | v₁@(ctor i₁ vs₁), v₂@(ctor i₂ vs₂) => if i₁ == i₂ then ctor i₁ $ vs₁.size.fold (init := #[]) fun i r => r.push (merge vs₁[i] vs₂[i]) else choice [v₁, v₂] | choice vs₁, choice vs₂ => choice $ vs₁.foldl (addChoice merge) vs₂ | choice vs, v => choice $ addChoice merge vs v | v, choice vs => choice $ addChoice merge vs v protected partial def format : Value → Format | top => "top" | bot => "bot" | choice vs => format "@" ++ @List.format _ ⟨Value.format⟩ vs | ctor i vs => format "#" ++ if vs.isEmpty then format i.name else Format.paren (format i.name ++ @formatArray _ ⟨Value.format⟩ vs) instance : ToFormat Value := ⟨Value.format⟩ instance : ToString Value := ⟨Format.pretty ∘ Value.format⟩ /-- In `truncate`, we approximate a value as `top` if depth > `truncateMaxDepth`. TODO: add option to control this parameter. -/ def truncateMaxDepth := 8 /-- Make sure constructors of recursive inductive datatypes can only occur once in each path. Values at depth > truncateMaxDepth are also approximated at `top`. We use this function this function to implement a simple widening operation for our abstract interpreter. Recall the widening functions is used to ensure termination in abstract interpreters. -/ partial def truncate (env : Environment) (v : Value) (s : NameSet) : Value := go v s truncateMaxDepth where go (v : Value) (s : NameSet) (depth : Nat) : Value := match depth with | 0 => top | depth+1 => match v, s with | ctor i vs, found => let I := i.name.getPrefix if found.contains I then top else let cont (found' : NameSet) : Value := ctor i (vs.map fun v => go v found' depth) match env.find? I with | some (ConstantInfo.inductInfo d) => if d.isRec then cont (found.insert I) else cont found | _ => cont found | choice vs, found => let newVs := vs.map fun v => go v found depth if newVs.elem top then top else choice newVs | v, _ => v /-- Widening operator that guarantees termination in our abstract interpreter. -/ def widening (env : Environment) (v₁ v₂ : Value) : Value := truncate env (merge v₁ v₂) {} end Value abbrev FunctionSummaries := SMap FunId Value builtin_initialize functionSummariesExt : SimplePersistentEnvExtension (FunId × Value) FunctionSummaries ← registerSimplePersistentEnvExtension { name := `unreachBranchesFunSummary, addImportedFn := fun as => let cache : FunctionSummaries := mkStateFromImportedEntries (fun s (p : FunId × Value) => s.insert p.1 p.2) {} as cache.switch, addEntryFn := fun s ⟨e, n⟩ => s.insert e n } def addFunctionSummary (env : Environment) (fid : FunId) (v : Value) : Environment := functionSummariesExt.addEntry env (fid, v) def getFunctionSummary? (env : Environment) (fid : FunId) : Option Value := (functionSummariesExt.getState env).find? fid abbrev Assignment := Std.HashMap VarId Value structure InterpContext where currFnIdx : Nat := 0 decls : Array Decl env : Environment lctx : LocalContext := {} structure InterpState where assignments : Array Assignment funVals : Std.PArray Value -- we take snapshots during fixpoint computations abbrev M := ReaderT InterpContext (StateM InterpState) open Value def findVarValue (x : VarId) : M Value := do let ctx ← read let s ← get let assignment := s.assignments[ctx.currFnIdx] pure $ assignment.findD x bot def findArgValue (arg : Arg) : M Value := match arg with | Arg.var x => findVarValue x | _ => pure top def updateVarAssignment (x : VarId) (v : Value) : M Unit := do let v' ← findVarValue x let ctx ← read modify fun s => { s with assignments := s.assignments.modify ctx.currFnIdx fun a => a.insert x (merge v v') } def resetVarAssignment (x : VarId) : M Unit := do let ctx ← read modify fun s => { s with assignments := s.assignments.modify ctx.currFnIdx fun a => a.insert x Value.bot } def resetParamAssignment (y : Param) : M Unit := resetVarAssignment y.x partial def projValue : Value → Nat → Value | ctor _ vs, i => vs.getD i bot | choice vs, i => vs.foldl (fun r v => merge r (projValue v i)) bot | v, _ => v def interpExpr : Expr → M Value | Expr.ctor i ys => return ctor i (← ys.mapM fun y => findArgValue y) | Expr.proj i x => return projValue (← findVarValue x) i | Expr.fap fid ys => do let ctx ← read match getFunctionSummary? ctx.env fid with | some v => pure v | none => do let s ← get match ctx.decls.findIdx? (fun decl => decl.name == fid) with | some idx => pure s.funVals[idx] | none => pure top | _ => pure top partial def containsCtor : Value → CtorInfo → Bool | top, _ => true | ctor i _, j => i == j | choice vs, j => vs.any $ fun v => containsCtor v j | _, _ => false def updateCurrFnSummary (v : Value) : M Unit := do let ctx ← read let currFnIdx := ctx.currFnIdx modify fun s => { s with funVals := s.funVals.modify currFnIdx (fun v' => widening ctx.env v v') } /-- Return true if the assignment of at least one parameter has been updated. -/ def updateJPParamsAssignment (ys : Array Param) (xs : Array Arg) : M Bool := do let ctx ← read let currFnIdx := ctx.currFnIdx ys.size.foldM (init := false) fun i r => do let y := ys[i] let x := xs[i] let yVal ← findVarValue y.x let xVal ← findArgValue x let newVal := merge yVal xVal if newVal == yVal then pure r else modify fun s => { s with assignments := s.assignments.modify currFnIdx fun a => a.insert y.x newVal } pure true private partial def resetNestedJPParams : FnBody → M Unit | FnBody.jdecl _ ys b k => do let ctx ← read let currFnIdx := ctx.currFnIdx ys.forM resetParamAssignment /- Remark we don't need to reset the parameters of joint-points nested in `b` since they will be reset if this JP is used. -/ resetNestedJPParams k | FnBody.case _ _ _ alts => alts.forM fun alt => match alt with | Alt.ctor _ b => resetNestedJPParams b | Alt.default b => resetNestedJPParams b | e => do unless e.isTerminal do resetNestedJPParams e.body partial def interpFnBody : FnBody → M Unit | FnBody.vdecl x _ e b => do let v ← interpExpr e updateVarAssignment x v interpFnBody b | FnBody.jdecl j ys v b => withReader (fun ctx => { ctx with lctx := ctx.lctx.addJP j ys v }) do interpFnBody b | FnBody.case _ x _ alts => do let v ← findVarValue x alts.forM fun alt => do match alt with | Alt.ctor i b => if containsCtor v i then interpFnBody b | Alt.default b => interpFnBody b | FnBody.ret x => do let v ← findArgValue x -- dbgTrace ("ret " ++ toString v) $ fun _ => updateCurrFnSummary v | FnBody.jmp j xs => do let ctx ← read let ys := (ctx.lctx.getJPParams j).get! let b := (ctx.lctx.getJPBody j).get! let updated ← updateJPParamsAssignment ys xs if updated then -- We must reset the value of nested join-point parameters since they depend on `ys` values resetNestedJPParams b interpFnBody b | e => do unless e.isTerminal do interpFnBody e.body def inferStep : M Bool := do let ctx ← read modify fun s => { s with assignments := ctx.decls.map fun _ => {} } ctx.decls.size.foldM (init := false) fun idx modified => do match ctx.decls[idx] with | Decl.fdecl (xs := ys) (body := b) .. => do let s ← get let currVals := s.funVals[idx] withReader (fun ctx => { ctx with currFnIdx := idx }) do ys.forM fun y => updateVarAssignment y.x top interpFnBody b let s ← get let newVals := s.funVals[idx] pure (modified || currVals != newVals) | Decl.extern _ _ _ _ => pure modified partial def inferMain : M Unit := do let modified ← inferStep if modified then inferMain else pure () partial def elimDeadAux (assignment : Assignment) : FnBody → FnBody | FnBody.vdecl x t e b => FnBody.vdecl x t e (elimDeadAux assignment b) | FnBody.jdecl j ys v b => FnBody.jdecl j ys (elimDeadAux assignment v) (elimDeadAux assignment b) | FnBody.case tid x xType alts => let v := assignment.findD x bot let alts := alts.map fun alt => match alt with | Alt.ctor i b => Alt.ctor i $ if containsCtor v i then elimDeadAux assignment b else FnBody.unreachable | Alt.default b => Alt.default (elimDeadAux assignment b) FnBody.case tid x xType alts | e => if e.isTerminal then e else let (instr, b) := e.split let b := elimDeadAux assignment b instr.setBody b partial def elimDead (assignment : Assignment) (d : Decl) : Decl := match d with | Decl.fdecl (body := b) .. => d.updateBody! <| elimDeadAux assignment b | other => other end UnreachableBranches open UnreachableBranches def elimDeadBranches (decls : Array Decl) : CompilerM (Array Decl) := do let s ← get let env := s.env let assignments : Array Assignment := decls.map fun _ => {} let funVals := Std.mkPArray decls.size Value.bot let ctx : InterpContext := { decls := decls, env := env } let s : InterpState := { assignments := assignments, funVals := funVals } let (_, s) := (inferMain ctx).run s let funVals := s.funVals let assignments := s.assignments modify fun s => let env := decls.size.fold (init := s.env) fun i env => addFunctionSummary env decls[i].name funVals[i] { s with env := env } pure $ decls.mapIdx fun i decl => elimDead assignments[i] decl end Lean.IR
f7833b422dafbd53c8517bce82553ac5da69ea18
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/occurs_check_bug1.lean
5479cea8eb4343b9e6daae97f98f3389c4fdd8fd
[ "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
507
lean
open nat prod open decidable constant modulo1 (x : ℕ) (y : ℕ) : ℕ infixl `mod`:70 := modulo1 constant gcd_aux : ℕ × ℕ → ℕ noncomputable definition gcd (x y : ℕ) : ℕ := gcd_aux (x, y) theorem gcd_def (x y : ℕ) : gcd x y = @ite (y = 0) (nat.decidable_eq (snd (x, y)) 0) nat x (gcd y (x mod y)) := sorry constant succ_ne_zero (a : nat) : succ a ≠ 0 theorem gcd_succ (m n : ℕ) : gcd m (succ n) = gcd (succ n) (m mod succ n) := eq.trans (gcd_def _ _) (if_neg (nat.succ_ne_zero _))
db4efbf8fdbb8ed696f9ba233cc4efdc5702fa1f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/continuous_function/weierstrass.lean
d60d6f9f63f881cd7937989a5923ed8b64a47b95
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,348
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import analysis.special_functions.bernstein import topology.algebra.algebra /-! # The Weierstrass approximation theorem for continuous functions on `[a,b]` We've already proved the Weierstrass approximation theorem in the sense that we've shown that the Bernstein approximations to a continuous function on `[0,1]` converge uniformly. Here we rephrase this more abstractly as `polynomial_functions_closure_eq_top' : (polynomial_functions I).topological_closure = ⊤` and then, by precomposing with suitable affine functions, `polynomial_functions_closure_eq_top : (polynomial_functions (set.Icc a b)).topological_closure = ⊤` -/ open continuous_map filter open_locale unit_interval /-- The special case of the Weierstrass approximation theorem for the interval `[0,1]`. This is just a matter of unravelling definitions and using the Bernstein approximations. -/ theorem polynomial_functions_closure_eq_top' : (polynomial_functions I).topological_closure = ⊤ := begin apply eq_top_iff.mpr, rintros f -, refine filter.frequently.mem_closure _, refine filter.tendsto.frequently (bernstein_approximation_uniform f) _, apply frequently_of_forall, intro n, simp only [set_like.mem_coe], apply subalgebra.sum_mem, rintro n -, apply subalgebra.smul_mem, dsimp [bernstein, polynomial_functions], simp, end /-- The **Weierstrass Approximation Theorem**: polynomials functions on `[a, b] ⊆ ℝ` are dense in `C([a,b],ℝ)` (While we could deduce this as an application of the Stone-Weierstrass theorem, our proof of that relies on the fact that `abs` is in the closure of polynomials on `[-M, M]`, so we may as well get this done first.) -/ theorem polynomial_functions_closure_eq_top (a b : ℝ) : (polynomial_functions (set.Icc a b)).topological_closure = ⊤ := begin by_cases h : a < b, -- (Otherwise it's easy; we'll deal with that later.) { -- We can pullback continuous functions on `[a,b]` to continuous functions on `[0,1]`, -- by precomposing with an affine map. let W : C(set.Icc a b, ℝ) →ₐ[ℝ] C(I, ℝ) := comp_right_alg_hom ℝ ℝ (Icc_homeo_I a b h).symm.to_continuous_map, -- This operation is itself a homeomorphism -- (with respect to the norm topologies on continuous functions). let W' : C(set.Icc a b, ℝ) ≃ₜ C(I, ℝ) := comp_right_homeomorph ℝ (Icc_homeo_I a b h).symm, have w : (W : C(set.Icc a b, ℝ) → C(I, ℝ)) = W' := rfl, -- Thus we take the statement of the Weierstrass approximation theorem for `[0,1]`, have p := polynomial_functions_closure_eq_top', -- and pullback both sides, obtaining an equation between subalgebras of `C([a,b], ℝ)`. apply_fun (λ s, s.comap W) at p, simp only [algebra.comap_top] at p, -- Since the pullback operation is continuous, it commutes with taking `topological_closure`, rw subalgebra.topological_closure_comap_homeomorph _ W W' w at p, -- and precomposing with an affine map takes polynomial functions to polynomial functions. rw polynomial_functions.comap_comp_right_alg_hom_Icc_homeo_I at p, -- 🎉 exact p }, { -- Otherwise, `b ≤ a`, and the interval is a subsingleton, -- so all subalgebras are the same anyway. haveI : subsingleton (set.Icc a b) := ⟨λ x y, le_antisymm ((x.2.2.trans (not_lt.mp h)).trans y.2.1) ((y.2.2.trans (not_lt.mp h)).trans x.2.1)⟩, apply subsingleton.elim, } end /-- An alternative statement of Weierstrass' theorem. Every real-valued continuous function on `[a,b]` is a uniform limit of polynomials. -/ theorem continuous_map_mem_polynomial_functions_closure (a b : ℝ) (f : C(set.Icc a b, ℝ)) : f ∈ (polynomial_functions (set.Icc a b)).topological_closure := begin rw polynomial_functions_closure_eq_top _ _, simp, end open_locale polynomial /-- An alternative statement of Weierstrass' theorem, for those who like their epsilons. Every real-valued continuous function on `[a,b]` is within any `ε > 0` of some polynomial. -/ theorem exists_polynomial_near_continuous_map (a b : ℝ) (f : C(set.Icc a b, ℝ)) (ε : ℝ) (pos : 0 < ε) : ∃ (p : ℝ[X]), ‖p.to_continuous_map_on _ - f‖ < ε := begin have w := mem_closure_iff_frequently.mp (continuous_map_mem_polynomial_functions_closure _ _ f), rw metric.nhds_basis_ball.frequently_iff at w, obtain ⟨-, H, ⟨m, ⟨-, rfl⟩⟩⟩ := w ε pos, rw [metric.mem_ball, dist_eq_norm] at H, exact ⟨m, H⟩, end /-- Another alternative statement of Weierstrass's theorem, for those who like epsilons, but not bundled continuous functions. Every real-valued function `ℝ → ℝ` which is continuous on `[a,b]` can be approximated to within any `ε > 0` on `[a,b]` by some polynomial. -/ theorem exists_polynomial_near_of_continuous_on (a b : ℝ) (f : ℝ → ℝ) (c : continuous_on f (set.Icc a b)) (ε : ℝ) (pos : 0 < ε) : ∃ (p : ℝ[X]), ∀ x ∈ set.Icc a b, |p.eval x - f x| < ε := begin let f' : C(set.Icc a b, ℝ) := ⟨λ x, f x, continuous_on_iff_continuous_restrict.mp c⟩, obtain ⟨p, b⟩ := exists_polynomial_near_continuous_map a b f' ε pos, use p, rw norm_lt_iff _ pos at b, intros x m, exact b ⟨x, m⟩, end
89150681a090aadf8f6f38b1c0ce3f5e9b980056
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean.lean
88d8fc47eb65524f6094d7e75fc45ab323e11a89
[ "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
702
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Compiler import Init.Lean.Environment import Init.Lean.Modifiers import Init.Lean.ProjFns import Init.Lean.Runtime import Init.Lean.Attributes import Init.Lean.Parser import Init.Lean.ReducibilityAttrs import Init.Lean.Elab import Init.Lean.EqnCompiler import Init.Lean.Class import Init.Lean.LocalContext import Init.Lean.MetavarContext import Init.Lean.AuxRecursor import Init.Lean.Linter import Init.Lean.Meta import Init.Lean.Util import Init.Lean.Eval import Init.Lean.Structure import Init.Lean.Delaborator
334473fdb44f9e378c0128f0df5cff79e8e0552e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/finite.lean
f86cca6bfa443505d134e1f0ce09a5e777b96e26
[ "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
57,753
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, Kyle Miller -/ import data.finset.basic import data.set.functor import data.finite.basic /-! # Finite sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines predicates for finite and infinite sets and provides `fintype` instances for many set constructions. It also proves basic facts about finite sets and gives ways to manipulate `set.finite` expressions. ## Main definitions * `set.finite : set α → Prop` * `set.infinite : set α → Prop` * `set.to_finite` to prove `set.finite` for a `set` from a `finite` instance. * `set.finite.to_finset` to noncomputably produce a `finset` from a `set.finite` proof. (See `set.to_finset` for a computable version.) ## Implementation A finite set is defined to be a set whose coercion to a type has a `fintype` instance. Since `set.finite` is `Prop`-valued, this is the mere fact that the `fintype` instance exists. There are two components to finiteness constructions. The first is `fintype` instances for each construction. This gives a way to actually compute a `finset` that represents the set, and these may be accessed using `set.to_finset`. This gets the `finset` in the correct form, since otherwise `finset.univ : finset s` is a `finset` for the subtype for `s`. The second component is "constructors" for `set.finite` that give proofs that `fintype` instances exist classically given other `set.finite` proofs. Unlike the `fintype` instances, these *do not* use any decidability instances since they do not compute anything. ## Tags finite sets -/ open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if there is a `finset` with the same elements. This is represented as there being a `fintype` instance for the set coerced to a type. Note: this is a custom inductive type rather than `nonempty (fintype s)` so that it won't be frozen as a local instance. -/ @[protected] inductive finite (s : set α) : Prop | intro : fintype s → finite -- The `protected` attribute does not take effect within the same namespace block. end set namespace set lemma finite_def {s : set α} : s.finite ↔ nonempty (fintype s) := ⟨λ ⟨h⟩, ⟨h⟩, λ ⟨h⟩, ⟨h⟩⟩ alias finite_def ↔ finite.nonempty_fintype _ lemma finite_coe_iff {s : set α} : finite s ↔ s.finite := by rw [finite_iff_nonempty_fintype, finite_def] /-- Constructor for `set.finite` using a `finite` instance. -/ theorem to_finite (s : set α) [finite s] : s.finite := finite_coe_iff.mp ‹_› /-- Construct a `finite` instance for a `set` from a `finset` with the same elements. -/ protected lemma finite.of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : p.finite := ⟨fintype.of_finset s H⟩ /-- Projection of `set.finite` to its `finite` instance. This is intended to be used with dot notation. See also `set.finite.fintype` and `set.finite.nonempty_fintype`. -/ protected lemma finite.to_subtype {s : set α} (h : s.finite) : finite s := finite_coe_iff.mpr h /-- A finite set coerced to a type is a `fintype`. This is the `fintype` projection for a `set.finite`. Note that because `finite` isn't a typeclass, this definition will not fire if it is made into an instance -/ protected noncomputable def finite.fintype {s : set α} (h : s.finite) : fintype s := h.nonempty_fintype.some /-- Using choice, get the `finset` that represents this `set.` -/ protected noncomputable def finite.to_finset {s : set α} (h : s.finite) : finset α := @set.to_finset _ _ h.fintype theorem finite.to_finset_eq_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset = s.to_finset := by { rw [finite.to_finset], congr } @[simp] theorem to_finite_to_finset (s : set α) [fintype s] : s.to_finite.to_finset = s.to_finset := s.to_finite.to_finset_eq_to_finset theorem finite.exists_finset {s : set α} (h : s.finite) : ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s := by { casesI h, exact ⟨s.to_finset, λ _, mem_to_finset⟩ } theorem finite.exists_finset_coe {s : set α} (h : s.finite) : ∃ s' : finset α, ↑s' = s := by { casesI h, exact ⟨s.to_finset, s.coe_to_finset⟩ } /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) coe set.finite := { prf := λ s hs, hs.exists_finset_coe } /-- A set is infinite if it is not finite. This is protected so that it does not conflict with global `infinite`. -/ protected def infinite (s : set α) : Prop := ¬ s.finite @[simp] lemma not_infinite {s : set α} : ¬ s.infinite ↔ s.finite := not_not alias not_infinite ↔ _ finite.not_infinite attribute [simp] finite.not_infinite /-- See also `finite_or_infinite`, `fintype_or_infinite`. -/ protected lemma finite_or_infinite (s : set α) : s.finite ∨ s.infinite := em _ protected lemma infinite_or_finite (s : set α) : s.infinite ∨ s.finite := em' _ /-! ### Basic properties of `set.finite.to_finset` -/ namespace finite variables {s t : set α} {a : α} {hs : s.finite} {ht : t.finite} @[simp] protected lemma mem_to_finset (h : s.finite) : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] protected lemma coe_to_finset (h : s.finite) : (h.to_finset : set α) = s := @coe_to_finset _ _ h.fintype @[simp] protected lemma to_finset_nonempty (h : s.finite) : h.to_finset.nonempty ↔ s.nonempty := by rw [← finset.coe_nonempty, finite.coe_to_finset] /-- Note that this is an equality of types not holding definitionally. Use wisely. -/ lemma coe_sort_to_finset (h : s.finite) : ↥h.to_finset = ↥s := by rw [← finset.coe_sort_coe _, h.coe_to_finset] @[simp] protected lemma to_finset_inj : hs.to_finset = ht.to_finset ↔ s = t := @to_finset_inj _ _ _ hs.fintype ht.fintype @[simp] lemma to_finset_subset {t : finset α} : hs.to_finset ⊆ t ↔ s ⊆ t := by rw [←finset.coe_subset, finite.coe_to_finset] @[simp] lemma to_finset_ssubset {t : finset α} : hs.to_finset ⊂ t ↔ s ⊂ t := by rw [←finset.coe_ssubset, finite.coe_to_finset] @[simp] lemma subset_to_finset {s : finset α} : s ⊆ ht.to_finset ↔ ↑s ⊆ t := by rw [←finset.coe_subset, finite.coe_to_finset] @[simp] lemma ssubset_to_finset {s : finset α} : s ⊂ ht.to_finset ↔ ↑s ⊂ t := by rw [←finset.coe_ssubset, finite.coe_to_finset] @[mono] protected lemma to_finset_subset_to_finset : hs.to_finset ⊆ ht.to_finset ↔ s ⊆ t := by simp only [← finset.coe_subset, finite.coe_to_finset] @[mono] protected lemma to_finset_ssubset_to_finset : hs.to_finset ⊂ ht.to_finset ↔ s ⊂ t := by simp only [← finset.coe_ssubset, finite.coe_to_finset] alias finite.to_finset_subset_to_finset ↔ _ to_finset_mono alias finite.to_finset_ssubset_to_finset ↔ _ to_finset_strict_mono attribute [protected] to_finset_mono to_finset_strict_mono @[simp] protected lemma to_finset_set_of [fintype α] (p : α → Prop) [decidable_pred p] (h : {x | p x}.finite) : h.to_finset = finset.univ.filter p := by { ext, simp } @[simp] lemma disjoint_to_finset {hs : s.finite} {ht : t.finite} : disjoint hs.to_finset ht.to_finset ↔ disjoint s t := @disjoint_to_finset _ _ _ hs.fintype ht.fintype protected lemma to_finset_inter [decidable_eq α] (hs : s.finite) (ht : t.finite) (h : (s ∩ t).finite) : h.to_finset = hs.to_finset ∩ ht.to_finset := by { ext, simp } protected lemma to_finset_union [decidable_eq α] (hs : s.finite) (ht : t.finite) (h : (s ∪ t).finite) : h.to_finset = hs.to_finset ∪ ht.to_finset := by { ext, simp } protected lemma to_finset_diff [decidable_eq α] (hs : s.finite) (ht : t.finite) (h : (s \ t).finite) : h.to_finset = hs.to_finset \ ht.to_finset := by { ext, simp } protected lemma to_finset_symm_diff [decidable_eq α] (hs : s.finite) (ht : t.finite) (h : (s ∆ t).finite) : h.to_finset = hs.to_finset ∆ ht.to_finset := by { ext, simp [mem_symm_diff, finset.mem_symm_diff] } protected lemma to_finset_compl [decidable_eq α] [fintype α] (hs : s.finite) (h : sᶜ.finite) : h.to_finset = hs.to_finsetᶜ := by { ext, simp } @[simp] protected lemma to_finset_empty (h : (∅ : set α).finite) : h.to_finset = ∅ := by { ext, simp } @[simp] protected lemma to_finset_univ [fintype α] (h : (set.univ : set α).finite) : h.to_finset = finset.univ := by { ext, simp } @[simp] protected lemma to_finset_eq_empty {h : s.finite} : h.to_finset = ∅ ↔ s = ∅ := @to_finset_eq_empty _ _ h.fintype @[simp] protected lemma to_finset_eq_univ [fintype α] {h : s.finite} : h.to_finset = finset.univ ↔ s = univ := @to_finset_eq_univ _ _ _ h.fintype protected lemma to_finset_image [decidable_eq β] (f : α → β) (hs : s.finite) (h : (f '' s).finite) : h.to_finset = hs.to_finset.image f := by { ext, simp } @[simp] protected lemma to_finset_range [decidable_eq α] [fintype β] (f : β → α) (h : (range f).finite) : h.to_finset = finset.univ.image f := by { ext, simp } end finite /-! ### Fintype instances Every instance here should have a corresponding `set.finite` constructor in the next section. -/ section fintype_instances instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α (equiv.set.univ α).symm /-- If `(set.univ : set α)` is finite then `α` is a finite type. -/ noncomputable def fintype_of_finite_univ (H : (univ : set α).finite) : fintype α := @fintype.of_equiv _ (univ : set α) H.fintype (equiv.set.univ _) instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [decidable_eq α] [fintype s] [fintype t] : fintype (s ∩ t : set α) := fintype.of_finset (s.to_finset ∩ t.to_finset) $ by simp /-- A `fintype` instance for set intersection where the left set has a `fintype` instance. -/ instance fintype_inter_of_left (s t : set α) [fintype s] [decidable_pred (∈ t)] : fintype (s ∩ t : set α) := fintype.of_finset (s.to_finset.filter (∈ t)) $ by simp /-- A `fintype` instance for set intersection where the right set has a `fintype` instance. -/ instance fintype_inter_of_right (s t : set α) [fintype t] [decidable_pred (∈ s)] : fintype (s ∩ t : set α) := fintype.of_finset (t.to_finset.filter (∈ s)) $ by simp [and_comm] /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred (∈ t)] (h : t ⊆ s) : fintype t := by { rw ← inter_eq_self_of_subset_right h, apply set.fintype_inter_of_left } instance fintype_diff [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s \ t : set α) := fintype.of_finset (s.to_finset \ t.to_finset) $ by simp instance fintype_diff_left (s t : set α) [fintype s] [decidable_pred (∈ t)] : fintype (s \ t : set α) := set.fintype_sep s (∈ tᶜ) instance fintype_Union [decidable_eq α] [fintype (plift ι)] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bUnion (λ i : plift ι, (f i.down).to_finset)) $ by simp instance fintype_sUnion [decidable_eq α] {s : set (set α)} [fintype s] [H : ∀ (t : s), fintype (t : set α)] : fintype (⋃₀ s) := by { rw sUnion_eq_Union, exact @set.fintype_Union _ _ _ _ _ H } /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ def fintype_bUnion [decidable_eq α] {ι : Type*} (s : set ι) [fintype s] (t : ι → set α) (H : ∀ i ∈ s, fintype (t i)) : fintype (⋃(x ∈ s), t x) := fintype.of_finset (s.to_finset.attach.bUnion (λ x, by { haveI := H x (by simpa using x.property), exact (t x).to_finset })) $ by simp instance fintype_bUnion' [decidable_eq α] {ι : Type*} (s : set ι) [fintype s] (t : ι → set α) [∀ i, fintype (t i)] : fintype (⋃(x ∈ s), t x) := fintype.of_finset (s.to_finset.bUnion (λ x, (t x).to_finset)) $ by simp /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion s f H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := set.fintype_bUnion' s f instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp instance fintype_singleton (a : α) : fintype ({a} : set α) := fintype.of_finset {a} $ by simp instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton /-- A `fintype` instance for inserting an element into a `set` using the corresponding `insert` function on `finset`. This requires `decidable_eq α`. There is also `set.fintype_insert'` when `a ∈ s` is decidable. -/ instance fintype_insert (a : α) (s : set α) [decidable_eq α] [fintype s] : fintype (insert a s : set α) := fintype.of_finset (insert a s.to_finset) $ by simp /-- A `fintype` structure on `insert a s` when inserting a new element. -/ def fintype_insert_of_not_mem {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a ::ₘ s.to_finset.1, s.to_finset.nodup.cons (by simp [h]) ⟩ $ by simp /-- A `fintype` structure on `insert a s` when inserting a pre-existing element. -/ def fintype_insert_of_mem {a : α} (s : set α) [fintype s] (h : a ∈ s) : fintype (insert a s : set α) := fintype.of_finset s.to_finset $ by simp [h] /-- The `set.fintype_insert` instance requires decidable equality, but when `a ∈ s` is decidable for this particular `a` we can still get a `fintype` instance by using `set.fintype_insert_of_not_mem` or `set.fintype_insert_of_mem`. This instance pre-dates `set.fintype_insert`, and it is less efficient. When `decidable_mem_of_fintype` is made a local instance, then this instance would override `set.fintype_insert` if not for the fact that its priority has been adjusted. See Note [lower instance priority]. -/ @[priority 100] instance fintype_insert' (a : α) (s : set α) [decidable $ a ∈ s] [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then fintype_insert_of_mem s h else fintype_insert_of_not_mem s h instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, (f '' s).to_finset.2.filter_map g $ injective_of_partial_inv_right I⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end instance fintype_range [decidable_eq α] (f : ι → α) [fintype (plift ι)] : fintype (range f) := fintype.of_finset (finset.univ.image $ f ∘ plift.down) $ by simp [equiv.plift.exists_congr_left] instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) /-- This is not an instance so that it does not conflict with the one in src/order/locally_finite. -/ def nat.fintype_Iio (n : ℕ) : fintype (Iio n) := set.fintype_lt_nat n instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (s ×ˢ t : set (α × β)) := fintype.of_finset (s.to_finset ×ˢ t.to_finset) $ by simp instance fintype_off_diag [decidable_eq α] (s : set α) [fintype s] : fintype s.off_diag := fintype.of_finset s.to_finset.off_diag $ by simp /-- `image2 f s t` is `fintype` if `s` and `t` are. -/ instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) := by { rw ← image_prod, apply set.fintype_image } instance fintype_seq [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f.seq s) := by { rw seq_def, apply set.fintype_bUnion' } instance fintype_seq' {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := set.fintype_seq f s instance fintype_mem_finset (s : finset α) : fintype {a | a ∈ s} := finset.fintype_coe_sort s end fintype_instances end set lemma equiv.set_finite_iff {s : set α} {t : set β} (hst : s ≃ t) : s.finite ↔ t.finite := by simp_rw [← set.finite_coe_iff, hst.finite_iff] /-! ### Finset -/ namespace finset /-- Gives a `set.finite` for the `finset` coerced to a `set`. This is a wrapper around `set.to_finite`. -/ @[simp] lemma finite_to_set (s : finset α) : (s : set α).finite := set.to_finite _ @[simp] lemma finite_to_set_to_finset (s : finset α) : s.finite_to_set.to_finset = s := by { ext, rw [set.finite.mem_to_finset, mem_coe] } end finset namespace multiset @[simp] lemma finite_to_set (s : multiset α) : {x | x ∈ s}.finite := by { classical, simpa only [← multiset.mem_to_finset] using s.to_finset.finite_to_set } @[simp] lemma finite_to_set_to_finset [decidable_eq α] (s : multiset α) : s.finite_to_set.to_finset = s.to_finset := by { ext x, simp } end multiset @[simp] lemma list.finite_to_set (l : list α) : {x | x ∈ l}.finite := (show multiset α, from ⟦l⟧).finite_to_set /-! ### Finite instances There is seemingly some overlap between the following instances and the `fintype` instances in `data.set.finite`. While every `fintype` instance gives a `finite` instance, those instances that depend on `fintype` or `decidable` instances need an additional `finite` instance to be able to generally apply. Some set instances do not appear here since they are consequences of others, for example `subtype.finite` for subsets of a finite type. -/ namespace finite.set open_locale classical example {s : set α} [finite α] : finite s := infer_instance example : finite (∅ : set α) := infer_instance example (a : α) : finite ({a} : set α) := infer_instance instance finite_union (s t : set α) [finite s] [finite t] : finite (s ∪ t : set α) := by { casesI nonempty_fintype s, casesI nonempty_fintype t, apply_instance } instance finite_sep (s : set α) (p : α → Prop) [finite s] : finite ({a ∈ s | p a} : set α) := by { casesI nonempty_fintype s, apply_instance } protected lemma subset (s : set α) {t : set α} [finite s] (h : t ⊆ s) : finite t := by { rw ←sep_eq_of_subset h, apply_instance } instance finite_inter_of_right (s t : set α) [finite t] : finite (s ∩ t : set α) := finite.set.subset t (inter_subset_right s t) instance finite_inter_of_left (s t : set α) [finite s] : finite (s ∩ t : set α) := finite.set.subset s (inter_subset_left s t) instance finite_diff (s t : set α) [finite s] : finite (s \ t : set α) := finite.set.subset s (diff_subset s t) instance finite_range (f : ι → α) [finite ι] : finite (range f) := by { haveI := fintype.of_finite (plift ι), apply_instance } instance finite_Union [finite ι] (f : ι → set α) [∀ i, finite (f i)] : finite (⋃ i, f i) := begin rw [Union_eq_range_psigma], apply set.finite_range end instance finite_sUnion {s : set (set α)} [finite s] [H : ∀ (t : s), finite (t : set α)] : finite (⋃₀ s) := by { rw sUnion_eq_Union, exact @finite.set.finite_Union _ _ _ _ H } lemma finite_bUnion {ι : Type*} (s : set ι) [finite s] (t : ι → set α) (H : ∀ i ∈ s, finite (t i)) : finite (⋃(x ∈ s), t x) := begin rw [bUnion_eq_Union], haveI : ∀ (i : s), finite (t i) := λ i, H i i.property, apply_instance, end instance finite_bUnion' {ι : Type*} (s : set ι) [finite s] (t : ι → set α) [∀ i, finite (t i)] : finite (⋃(x ∈ s), t x) := finite_bUnion s t (λ i h, infer_instance) /-- Example: `finite (⋃ (i < n), f i)` where `f : ℕ → set α` and `[∀ i, finite (f i)]` (when given instances from `data.nat.interval`). -/ instance finite_bUnion'' {ι : Type*} (p : ι → Prop) [h : finite {x | p x}] (t : ι → set α) [∀ i, finite (t i)] : finite (⋃ x (h : p x), t x) := @finite.set.finite_bUnion' _ _ (set_of p) h t _ instance finite_Inter {ι : Sort*} [nonempty ι] (t : ι → set α) [∀ i, finite (t i)] : finite (⋂ i, t i) := finite.set.subset (t $ classical.arbitrary ι) (Inter_subset _ _) instance finite_insert (a : α) (s : set α) [finite s] : finite (insert a s : set α) := finite.set.finite_union {a} s instance finite_image (s : set α) (f : α → β) [finite s] : finite (f '' s) := by { casesI nonempty_fintype s, apply_instance } instance finite_replacement [finite α] (f : α → β) : finite {(f x) | (x : α)} := finite.set.finite_range f instance finite_prod (s : set α) (t : set β) [finite s] [finite t] : finite (s ×ˢ t : set (α × β)) := finite.of_equiv _ (equiv.set.prod s t).symm instance finite_image2 (f : α → β → γ) (s : set α) (t : set β) [finite s] [finite t] : finite (image2 f s t : set γ) := by { rw ← image_prod, apply_instance } instance finite_seq (f : set (α → β)) (s : set α) [finite f] [finite s] : finite (f.seq s) := by { rw seq_def, apply_instance } end finite.set namespace set /-! ### Constructors for `set.finite` Every constructor here should have a corresponding `fintype` instance in the previous section (or in the `fintype` module). The implementation of these constructors ideally should be no more than `set.to_finite`, after possibly setting up some `fintype` and classical `decidable` instances. -/ section set_finite_constructors @[nontriviality] lemma finite.of_subsingleton [subsingleton α] (s : set α) : s.finite := s.to_finite theorem finite_univ [finite α] : (@univ α).finite := set.to_finite _ theorem finite_univ_iff : (@univ α).finite ↔ finite α := finite_coe_iff.symm.trans (equiv.set.univ α).finite_iff alias finite_univ_iff ↔ _root_.finite.of_finite_univ _ theorem finite.union {s t : set α} (hs : s.finite) (ht : t.finite) : (s ∪ t).finite := by { casesI hs, casesI ht, apply to_finite } theorem finite.finite_of_compl {s : set α} (hs : s.finite) (hsc : sᶜ.finite) : finite α := by { rw [← finite_univ_iff, ← union_compl_self s], exact hs.union hsc } lemma finite.sup {s t : set α} : s.finite → t.finite → (s ⊔ t).finite := finite.union theorem finite.sep {s : set α} (hs : s.finite) (p : α → Prop) : {a ∈ s | p a}.finite := by { casesI hs, apply to_finite } theorem finite.inter_of_left {s : set α} (hs : s.finite) (t : set α) : (s ∩ t).finite := by { casesI hs, apply to_finite } theorem finite.inter_of_right {s : set α} (hs : s.finite) (t : set α) : (t ∩ s).finite := by { casesI hs, apply to_finite } theorem finite.inf_of_left {s : set α} (h : s.finite) (t : set α) : (s ⊓ t).finite := h.inter_of_left t theorem finite.inf_of_right {s : set α} (h : s.finite) (t : set α) : (t ⊓ s).finite := h.inter_of_right t theorem finite.subset {s : set α} (hs : s.finite) {t : set α} (ht : t ⊆ s) : t.finite := by { casesI hs, haveI := finite.set.subset _ ht, apply to_finite } theorem finite.diff {s : set α} (hs : s.finite) (t : set α) : (s \ t).finite := by { casesI hs, apply to_finite } theorem finite.of_diff {s t : set α} (hd : (s \ t).finite) (ht : t.finite) : s.finite := (hd.union ht).subset $ subset_diff_union _ _ theorem finite_Union [finite ι] {f : ι → set α} (H : ∀ i, (f i).finite) : (⋃ i, f i).finite := by { haveI := λ i, (H i).fintype, apply to_finite } theorem finite.sUnion {s : set (set α)} (hs : s.finite) (H : ∀ t ∈ s, set.finite t) : (⋃₀ s).finite := by { casesI hs, haveI := λ (i : s), (H i i.2).to_subtype, apply to_finite } theorem finite.bUnion {ι} {s : set ι} (hs : s.finite) {t : ι → set α} (ht : ∀ i ∈ s, (t i).finite) : (⋃(i ∈ s), t i).finite := by { classical, casesI hs, haveI := fintype_bUnion s t (λ i hi, (ht i hi).fintype), apply to_finite } /-- Dependent version of `finite.bUnion`. -/ theorem finite.bUnion' {ι} {s : set ι} (hs : s.finite) {t : Π (i ∈ s), set α} (ht : ∀ i ∈ s, (t i ‹_›).finite) : (⋃(i ∈ s), t i ‹_›).finite := by { casesI hs, rw [bUnion_eq_Union], apply finite_Union (λ (i : s), ht i.1 i.2), } theorem finite.sInter {α : Type*} {s : set (set α)} {t : set α} (ht : t ∈ s) (hf : t.finite) : (⋂₀ s).finite := hf.subset (sInter_subset_of_mem ht) /-- If sets `s i` are finite for all `i` from a finite set `t` and are empty for `i ∉ t`, then the union `⋃ i, s i` is a finite set. -/ lemma finite.Union {ι : Type*} {s : ι → set α} {t : set ι} (ht : t.finite) (hs : ∀ i ∈ t, (s i).finite) (he : ∀ i ∉ t, s i = ∅) : (⋃ i, s i).finite := begin suffices : (⋃ i, s i) ⊆ (⋃ i ∈ t, s i), { exact (ht.bUnion hs).subset this, }, refine Union_subset (λ i x hx, _), by_cases hi : i ∈ t, { exact mem_bUnion hi hx }, { rw [he i hi, mem_empty_iff_false] at hx, contradiction, }, end theorem finite.bind {α β} {s : set α} {f : α → set β} (h : s.finite) (hf : ∀ a ∈ s, (f a).finite) : (s >>= f).finite := h.bUnion hf @[simp] theorem finite_empty : (∅ : set α).finite := to_finite _ protected lemma infinite.nonempty {s : set α} (h : s.infinite) : s.nonempty := nonempty_iff_ne_empty.2 $ by { rintro rfl, exact h finite_empty } @[simp] theorem finite_singleton (a : α) : ({a} : set α).finite := to_finite _ theorem finite_pure (a : α) : (pure a : set α).finite := to_finite _ @[simp] theorem finite.insert (a : α) {s : set α} (hs : s.finite) : (insert a s).finite := by { casesI hs, apply to_finite } theorem finite.image {s : set α} (f : α → β) (hs : s.finite) : (f '' s).finite := by { casesI hs, apply to_finite } theorem finite_range (f : ι → α) [finite ι] : (range f).finite := to_finite _ lemma finite.dependent_image {s : set α} (hs : s.finite) (F : Π i ∈ s, β) : {y : β | ∃ x (hx : x ∈ s), y = F x hx}.finite := by { casesI hs, simpa [range, eq_comm] using finite_range (λ x : s, F x x.2) } theorem finite.map {α β} {s : set α} : ∀ (f : α → β), s.finite → (f <$> s).finite := finite.image theorem finite.of_finite_image {s : set α} {f : α → β} (h : (f '' s).finite) (hi : set.inj_on f s) : s.finite := by { casesI h, exact ⟨fintype.of_injective (λ a, (⟨f a.1, mem_image_of_mem f a.2⟩ : f '' s)) (λ a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq)⟩ } lemma finite_of_finite_preimage {f : α → β} {s : set β} (h : (f ⁻¹' s).finite) (hs : s ⊆ range f) : s.finite := by { rw [← image_preimage_eq_of_subset hs], exact finite.image f h } theorem finite.of_preimage {f : α → β} {s : set β} (h : (f ⁻¹' s).finite) (hf : surjective f) : s.finite := hf.image_preimage s ▸ h.image _ theorem finite.preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : s.finite) : (f ⁻¹' s).finite := (h.subset (image_preimage_subset f s)).of_finite_image I theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite := h.preimage (λ _ _ _ _ h', f.injective h') lemma finite_lt_nat (n : ℕ) : set.finite {i | i < n} := to_finite _ lemma finite_le_nat (n : ℕ) : set.finite {i | i ≤ n} := to_finite _ section prod variables {s : set α} {t : set β} protected lemma finite.prod (hs : s.finite) (ht : t.finite) : (s ×ˢ t : set (α × β)).finite := by { casesI hs, casesI ht, apply to_finite } lemma finite.of_prod_left (h : (s ×ˢ t : set (α × β)).finite) : t.nonempty → s.finite := λ ⟨b, hb⟩, (h.image prod.fst).subset $ λ a ha, ⟨(a, b), ⟨ha, hb⟩, rfl⟩ lemma finite.of_prod_right (h : (s ×ˢ t : set (α × β)).finite) : s.nonempty → t.finite := λ ⟨a, ha⟩, (h.image prod.snd).subset $ λ b hb, ⟨(a, b), ⟨ha, hb⟩, rfl⟩ protected lemma infinite.prod_left (hs : s.infinite) (ht : t.nonempty) : (s ×ˢ t).infinite := λ h, hs $ h.of_prod_left ht protected lemma infinite.prod_right (ht : t.infinite) (hs : s.nonempty) : (s ×ˢ t).infinite := λ h, ht $ h.of_prod_right hs protected lemma infinite_prod : (s ×ˢ t).infinite ↔ s.infinite ∧ t.nonempty ∨ t.infinite ∧ s.nonempty := begin refine ⟨λ h, _, _⟩, { simp_rw [set.infinite, and_comm (¬ _), ←not_imp], by_contra', exact h ((this.1 h.nonempty.snd).prod $ this.2 h.nonempty.fst) }, { rintro (h | h), { exact h.1.prod_left h.2 }, { exact h.1.prod_right h.2 } } end lemma finite_prod : (s ×ˢ t).finite ↔ (s.finite ∨ t = ∅) ∧ (t.finite ∨ s = ∅) := by simp only [←not_infinite, set.infinite_prod, not_or_distrib, not_and_distrib, not_nonempty_iff_eq_empty] protected lemma finite.off_diag (hs : s.finite) : s.off_diag.finite := by { classical, casesI hs, apply set.to_finite } protected lemma finite.image2 (f : α → β → γ) (hs : s.finite) (ht : t.finite) : (image2 f s t).finite := by { casesI hs, casesI ht, apply to_finite } end prod theorem finite.seq {f : set (α → β)} {s : set α} (hf : f.finite) (hs : s.finite) : (f.seq s).finite := by { classical, casesI hf, casesI hs, apply to_finite } theorem finite.seq' {α β : Type u} {f : set (α → β)} {s : set α} (hf : f.finite) (hs : s.finite) : (f <*> s).finite := hf.seq hs theorem finite_mem_finset (s : finset α) : {a | a ∈ s}.finite := to_finite _ lemma subsingleton.finite {s : set α} (h : s.subsingleton) : s.finite := h.induction_on finite_empty finite_singleton lemma finite_preimage_inl_and_inr {s : set (α ⊕ β)} : (sum.inl ⁻¹' s).finite ∧ (sum.inr ⁻¹' s).finite ↔ s.finite := ⟨λ h, image_preimage_inl_union_image_preimage_inr s ▸ (h.1.image _).union (h.2.image _), λ h, ⟨h.preimage (sum.inl_injective.inj_on _), h.preimage (sum.inr_injective.inj_on _)⟩⟩ theorem exists_finite_iff_finset {p : set α → Prop} : (∃ s : set α, s.finite ∧ p s) ↔ ∃ s : finset α, p ↑s := ⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩, λ ⟨s, hs⟩, ⟨s, s.finite_to_set, hs⟩⟩ /-- There are finitely many subsets of a given finite set -/ lemma finite.finite_subsets {α : Type u} {a : set α} (h : a.finite) : {b | b ⊆ a}.finite := ⟨fintype.of_finset ((finset.powerset h.to_finset).map finset.coe_emb.1) $ λ s, by simpa [← @exists_finite_iff_finset α (λ t, t ⊆ a ∧ t = s), finite.subset_to_finset, ← and.assoc] using h.subset⟩ /-- Finite product of finite sets is finite -/ lemma finite.pi {δ : Type*} [finite δ] {κ : δ → Type*} {t : Π d, set (κ d)} (ht : ∀ d, (t d).finite) : (pi univ t).finite := begin casesI nonempty_fintype δ, lift t to Π d, finset (κ d) using ht, classical, rw ← fintype.coe_pi_finset, apply finset.finite_to_set end /-- A finite union of finsets is finite. -/ lemma union_finset_finite_of_range_finite (f : α → finset β) (h : (range f).finite) : (⋃ a, (f a : set β)).finite := by { rw ← bUnion_range, exact h.bUnion (λ y hy, y.finite_to_set) } lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : (range f).finite) (hg : (range g).finite) : (range (λ x, if p x then f x else g x)).finite := (hf.union hg).subset range_ite_subset lemma finite_range_const {c : β} : (range (λ x : α, c)).finite := (finite_singleton c).subset range_const_subset end set_finite_constructors /-! ### Properties -/ instance finite.inhabited : inhabited {s : set α // s.finite} := ⟨⟨∅, finite_empty⟩⟩ @[simp] lemma finite_union {s t : set α} : (s ∪ t).finite ↔ s.finite ∧ t.finite := ⟨λ h, ⟨h.subset (subset_union_left _ _), h.subset (subset_union_right _ _)⟩, λ ⟨hs, ht⟩, hs.union ht⟩ theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : (f '' s).finite ↔ s.finite := ⟨λ h, h.of_finite_image hi, finite.image _⟩ lemma univ_finite_iff_nonempty_fintype : (univ : set α).finite ↔ nonempty (fintype α) := ⟨λ h, ⟨fintype_of_finite_univ h⟩, λ ⟨_i⟩, by exactI finite_univ⟩ @[simp] lemma finite.to_finset_singleton {a : α} (ha : ({a} : set α).finite := finite_singleton _) : ha.to_finset = {a} := finset.ext $ by simp @[simp] lemma finite.to_finset_insert [decidable_eq α] {s : set α} {a : α} (hs : (insert a s).finite) : hs.to_finset = insert a (hs.subset $ subset_insert _ _).to_finset := finset.ext $ by simp lemma finite.to_finset_insert' [decidable_eq α] {a : α} {s : set α} (hs : s.finite) : (hs.insert a).to_finset = insert a hs.to_finset := finite.to_finset_insert _ lemma finite.to_finset_prod {s : set α} {t : set β} (hs : s.finite) (ht : t.finite) : hs.to_finset ×ˢ ht.to_finset = (hs.prod ht).to_finset := finset.ext $ by simp lemma finite.to_finset_off_diag {s : set α} [decidable_eq α] (hs : s.finite) : hs.off_diag.to_finset = hs.to_finset.off_diag := finset.ext $ by simp lemma finite.fin_embedding {s : set α} (h : s.finite) : ∃ (n : ℕ) (f : fin n ↪ α), range f = s := ⟨_, (fintype.equiv_fin (h.to_finset : set α)).symm.as_embedding, by simp⟩ lemma finite.fin_param {s : set α} (h : s.finite) : ∃ (n : ℕ) (f : fin n → α), injective f ∧ range f = s := let ⟨n, f, hf⟩ := h.fin_embedding in ⟨n, f, f.injective, hf⟩ lemma finite_option {s : set (option α)} : s.finite ↔ {x : α | some x ∈ s}.finite := ⟨λ h, h.preimage_embedding embedding.some, λ h, ((h.image some).insert none).subset $ λ x, option.cases_on x (λ _, or.inl rfl) (λ x hx, or.inr $ mem_image_of_mem _ hx)⟩ lemma finite_image_fst_and_snd_iff {s : set (α × β)} : (prod.fst '' s).finite ∧ (prod.snd '' s).finite ↔ s.finite := ⟨λ h, (h.1.prod h.2).subset $ λ x h, ⟨mem_image_of_mem _ h, mem_image_of_mem _ h⟩, λ h, ⟨h.image _, h.image _⟩⟩ lemma forall_finite_image_eval_iff {δ : Type*} [finite δ] {κ : δ → Type*} {s : set (Π d, κ d)} : (∀ d, (eval d '' s).finite) ↔ s.finite := ⟨λ h, (finite.pi h).subset $ subset_pi_eval_image _ _, λ h d, h.image _⟩ lemma finite_subset_Union {s : set α} (hs : s.finite) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, I.finite ∧ s ⊆ ⋃ i ∈ I, t i := begin casesI hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, λ x hx, _⟩, rw [bUnion_range, mem_Union], exact ⟨⟨x, hx⟩, hf _⟩ end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : t.finite) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, I.finite ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, (σ i).finite) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, tfin.subset (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : s.finite) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → set.finite s → C s → C (insert a s)) : C s := begin lift s to finset α using h, induction s using finset.cons_induction_on with a s ha hs, { rwa [finset.coe_empty] }, { rw [finset.coe_cons], exact @H1 a s ha (set.to_finite _) hs } end /-- Analogous to `finset.induction_on'`. -/ @[elab_as_eliminator] theorem finite.induction_on' {C : set α → Prop} {S : set α} (h : S.finite) (H0 : C ∅) (H1 : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → C s → C (insert a s)) : C S := begin refine @set.finite.induction_on α (λ s, s ⊆ S → C s) S h (λ _, H0) _ subset.rfl, intros a s has hsf hCs haS, rw insert_subset at haS, exact H1 haS.1 haS.2 has (hCs haS.2) end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀ (s : set α), s.finite → Prop} {s : set α} (h : s.finite) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀ h : set.finite s, C s h → C (insert a s) (h.insert a)) : C s h := have ∀ h : s.finite, C s h, from finite.induction_on h (λ h, H0) (λ a s has hs ih h, H1 has hs (ih _)), this h section local attribute [instance] nat.fintype_Iio /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ lemma seq_of_forall_finite_exists {γ : Type*} {P : γ → set γ → Prop} (h : ∀ t : set γ, t.finite → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := ⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h (range $ λ m : Iio n, ih m.1 m.2) (finite_range _), λ n, begin classical, refine nat.strong_rec_on' n (λ n ih, _), rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _), ext x, split, { rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ }, { rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ } end⟩ end /-! ### Cardinality -/ theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card theorem card_fintype_insert_of_not_mem {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert_of_not_mem s h) = fintype.card s + 1 := by rw [fintype_insert_of_not_mem, fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert_of_not_mem s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := fintype.card_lt_of_injective_not_surjective (set.inclusion h.1) (set.inclusion_injective h.1) $ λ hst, (ssubset_iff_subset_ne.1 h).2 (eq_of_inclusion_surjective hst) lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := fintype.card_le_of_injective (set.inclusion hsub) (set.inclusion_injective hsub) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.of_injective f hf lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset.card = fintype.card s := begin rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], refine fintype.card_congr (equiv.set_congr _), ext x, show x ∈ h.to_finset ↔ x ∈ s, simp, end lemma card_ne_eq [fintype α] (a : α) [fintype {x : α | x ≠ a}] : fintype.card {x : α | x ≠ a} = fintype.card α - 1 := begin haveI := classical.dec_eq α, rw [←to_finset_card, to_finset_set_of, finset.filter_ne', finset.card_erase_of_mem (finset.mem_univ _), finset.card_univ], end /-! ### Infinite sets -/ theorem infinite_univ_iff : (@univ α).infinite ↔ infinite α := by rw [set.infinite, finite_univ_iff, not_finite_iff_infinite] theorem infinite_univ [h : infinite α] : (@univ α).infinite := infinite_univ_iff.2 h theorem infinite_coe_iff {s : set α} : infinite s ↔ s.infinite := not_finite_iff_infinite.symm.trans finite_coe_iff.not alias infinite_coe_iff ↔ _ infinite.to_subtype /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def infinite.nat_embedding (s : set α) (h : s.infinite) : ℕ ↪ s := by { haveI := h.to_subtype, exact infinite.nat_embedding s } lemma infinite.exists_subset_card_eq {s : set α} (hs : s.infinite) (n : ℕ) : ∃ t : finset α, ↑t ⊆ s ∧ t.card = n := ⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩ lemma infinite_of_finite_compl [infinite α] {s : set α} (hs : sᶜ.finite) : s.infinite := λ h, set.infinite_univ (by simpa using hs.union h) lemma finite.infinite_compl [infinite α] {s : set α} (hs : s.finite) : sᶜ.infinite := λ h, set.infinite_univ (by simpa using hs.union h) protected theorem infinite.mono {s t : set α} (h : s ⊆ t) : s.infinite → t.infinite := mt (λ ht, ht.subset h) lemma infinite.diff {s t : set α} (hs : s.infinite) (ht : t.finite) : (s \ t).infinite := λ h, hs $ h.of_diff ht @[simp] lemma infinite_union {s t : set α} : (s ∪ t).infinite ↔ s.infinite ∨ t.infinite := by simp only [set.infinite, finite_union, not_and_distrib] theorem infinite.of_image (f : α → β) {s : set α} (hs : (f '' s).infinite) : s.infinite := mt (finite.image f) hs theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : (f '' s).infinite ↔ s.infinite := not_congr $ finite_image_iff hi alias infinite_image_iff ↔ _ infinite.image attribute [protected] infinite.image section image2 variables {f : α → β → γ} {s : set α} {t : set β} {a : α} {b : β} protected lemma infinite.image2_left (hs : s.infinite) (hb : b ∈ t) (hf : inj_on (λ a, f a b) s) : (image2 f s t).infinite := (hs.image hf).mono $ image_subset_image2_left hb protected lemma infinite.image2_right (ht : t.infinite) (ha : a ∈ s) (hf : inj_on (f a) t) : (image2 f s t).infinite := (ht.image hf).mono $ image_subset_image2_right ha theorem infinite_image2 (hfs : ∀ b ∈ t, inj_on (λ a, f a b) s) (hft : ∀ a ∈ s, inj_on (f a) t) : (image2 f s t).infinite ↔ s.infinite ∧ t.nonempty ∨ t.infinite ∧ s.nonempty := begin refine ⟨λ h, set.infinite_prod.1 _, _⟩, { rw ←image_uncurry_prod at h, exact h.of_image _ }, { rintro (⟨hs, b, hb⟩ | ⟨ht, a, ha⟩), { exact hs.image2_left hb (hfs _ hb) }, { exact ht.image2_right ha (hft _ ha) } } end end image2 theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β} (hi : inj_on f s) (hm : maps_to f s t) (hs : s.infinite) : t.infinite := ((infinite_image_iff hi).2 hs).mono (maps_to'.mp hm) theorem infinite.exists_ne_map_eq_of_maps_to {s : set α} {t : set β} {f : α → β} (hs : s.infinite) (hf : maps_to f s t) (ht : t.finite) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin contrapose! ht, exact infinite_of_inj_on_maps_to (λ x hx y hy, not_imp_not.1 (ht x hx y hy)) hf hs end theorem infinite_range_of_injective [infinite α] {f : α → β} (hi : injective f) : (range f).infinite := by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ } theorem infinite_of_injective_forall_mem [infinite α] {s : set β} {f : α → β} (hi : injective f) (hf : ∀ x : α, f x ∈ s) : s.infinite := by { rw ←range_subset_iff at hf, exact (infinite_range_of_injective hi).mono hf } lemma infinite.exists_not_mem_finset {s : set α} (hs : s.infinite) (f : finset α) : ∃ a ∈ s, a ∉ f := let ⟨a, has, haf⟩ := (hs.diff (to_finite f)).nonempty in ⟨a, has, λ h, haf $ finset.mem_coe.1 h⟩ lemma not_inj_on_infinite_finite_image {f : α → β} {s : set α} (h_inf : s.infinite) (h_fin : (f '' s).finite) : ¬ inj_on f s := begin haveI : finite (f '' s) := finite_coe_iff.mpr h_fin, haveI : infinite s := infinite_coe_iff.mpr h_inf, have := not_injective_infinite_finite ((f '' s).cod_restrict (s.restrict f) $ λ x, ⟨x, x.property, rfl⟩), contrapose! this, rwa [injective_cod_restrict, ← inj_on_iff_injective], end /-! ### Order properties -/ section preorder variables [preorder α] [nonempty α] {s : set α} lemma infinite_of_forall_exists_gt (h : ∀ a, ∃ b ∈ s, a < b) : s.infinite := begin inhabit α, set f : ℕ → α := λ n, nat.rec_on n (h default).some (λ n a, (h a).some), have hf : ∀ n, f n ∈ s := by rintro (_ | _); exact (h _).some_spec.some, refine infinite_of_injective_forall_mem (strict_mono_nat_of_lt_succ $ λ n, _).injective hf, exact (h _).some_spec.some_spec, end lemma infinite_of_forall_exists_lt (h : ∀ a, ∃ b ∈ s, b < a) : s.infinite := @infinite_of_forall_exists_gt αᵒᵈ _ _ _ h end preorder lemma finite_is_top (α : Type*) [partial_order α] : {x : α | is_top x}.finite := (subsingleton_is_top α).finite lemma finite_is_bot (α : Type*) [partial_order α] : {x : α | is_bot x}.finite := (subsingleton_is_bot α).finite theorem infinite.exists_lt_map_eq_of_maps_to [linear_order α] {s : set α} {t : set β} {f : α → β} (hs : s.infinite) (hf : maps_to f s t) (ht : t.finite) : ∃ (x ∈ s) (y ∈ s), x < y ∧ f x = f y := let ⟨x, hx, y, hy, hxy, hf⟩ := hs.exists_ne_map_eq_of_maps_to hf ht in hxy.lt_or_lt.elim (λ hxy, ⟨x, hx, y, hy, hxy, hf⟩) (λ hyx, ⟨y, hy, x, hx, hyx, hf.symm⟩) lemma finite.exists_lt_map_eq_of_forall_mem [linear_order α] [infinite α] {t : set β} {f : α → β} (hf : ∀ a, f a ∈ t) (ht : t.finite) : ∃ a b, a < b ∧ f a = f b := begin rw ←maps_univ_to at hf, obtain ⟨a, -, b, -, h⟩ := (@infinite_univ α _).exists_lt_map_eq_of_maps_to hf ht, exact ⟨a, b, h⟩, end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : s.finite) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_min_image f ⟨x, h1.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : s.finite) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_max_image f ⟨x, h1.mem_to_finset.2 hx⟩ theorem exists_lower_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f a ≤ f b := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_min_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end theorem exists_upper_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f b ≤ f a := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_max_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end lemma finite.supr_binfi_of_monotone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.frame α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, monotone (f i)) : (⨆ j, ⨅ i ∈ s, f i j) = ⨅ i ∈ s, ⨆ j, f i j := begin revert hf, refine hs.induction_on _ _, { intro hf, simp [supr_const] }, { intros a s has hs ihs hf, rw [ball_insert_iff] at hf, simp only [infi_insert, ← ihs hf.2], exact supr_inf_of_monotone hf.1 (λ j₁ j₂ hj, infi₂_mono $ λ i hi, hf.2 i hi hj) } end lemma finite.supr_binfi_of_antitone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.frame α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, antitone (f i)) : (⨆ j, ⨅ i ∈ s, f i j) = ⨅ i ∈ s, ⨆ j, f i j := @finite.supr_binfi_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ hs _ (λ i hi, (hf i hi).dual_left) lemma finite.infi_bsupr_of_monotone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.coframe α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, monotone (f i)) : (⨅ j, ⨆ i ∈ s, f i j) = ⨆ i ∈ s, ⨅ j, f i j := hs.supr_binfi_of_antitone (λ i hi, (hf i hi).dual_right) lemma finite.infi_bsupr_of_antitone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.coframe α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, antitone (f i)) : (⨅ j, ⨆ i ∈ s, f i j) = ⨆ i ∈ s, ⨅ j, f i j := hs.supr_binfi_of_monotone (λ i hi, (hf i hi).dual_right) lemma _root_.supr_infi_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.frame α] {f : ι → ι' → α} (hf : ∀ i, monotone (f i)) : (⨆ j, ⨅ i, f i j) = ⨅ i, ⨆ j, f i j := by simpa only [infi_univ] using finite_univ.supr_binfi_of_monotone (λ i hi, hf i) lemma _root_.supr_infi_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.frame α] {f : ι → ι' → α} (hf : ∀ i, antitone (f i)) : (⨆ j, ⨅ i, f i j) = ⨅ i, ⨆ j, f i j := @supr_infi_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ _ (λ i, (hf i).dual_left) lemma _root_.infi_supr_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.coframe α] {f : ι → ι' → α} (hf : ∀ i, monotone (f i)) : (⨅ j, ⨆ i, f i j) = ⨆ i, ⨅ j, f i j := supr_infi_of_antitone (λ i, (hf i).dual_right) lemma _root_.infi_supr_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.coframe α] {f : ι → ι' → α} (hf : ∀ i, antitone (f i)) : (⨅ j, ⨆ i, f i j) = ⨆ i, ⨅ j, f i j := supr_infi_of_monotone (λ i, (hf i).dual_right) /-- An increasing union distributes over finite intersection. -/ lemma Union_Inter_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (≤)] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := supr_infi_of_monotone hs /-- A decreasing union distributes over finite intersection. -/ lemma Union_Inter_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (swap (≤))] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, antitone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := supr_infi_of_antitone hs /-- An increasing intersection distributes over finite union. -/ lemma Inter_Union_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (swap (≤))] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋂ j : ι', ⋃ i : ι, s i j) = ⋃ i : ι, ⋂ j : ι', s i j := infi_supr_of_monotone hs /-- A decreasing intersection distributes over finite union. -/ lemma Inter_Union_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (≤)] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, antitone (s i)) : (⋂ j : ι', ⋃ i : ι, s i j) = ⋃ i : ι, ⋂ j : ι', s i j := infi_supr_of_antitone hs lemma Union_pi_of_monotone {ι ι' : Type*} [linear_order ι'] [nonempty ι'] {α : ι → Type*} {I : set ι} {s : Π i, ι' → set (α i)} (hI : I.finite) (hs : ∀ i ∈ I, monotone (s i)) : (⋃ j : ι', I.pi (λ i, s i j)) = I.pi (λ i, ⋃ j, s i j) := begin simp only [pi_def, bInter_eq_Inter, preimage_Union], haveI := hI.fintype, exact Union_Inter_of_monotone (λ i j₁ j₂ h, preimage_mono $ hs i i.2 h) end lemma Union_univ_pi_of_monotone {ι ι' : Type*} [linear_order ι'] [nonempty ι'] [finite ι] {α : ι → Type*} {s : Π i, ι' → set (α i)} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', pi univ (λ i, s i j)) = pi univ (λ i, ⋃ j, s i j) := Union_pi_of_monotone finite_univ (λ i _, hs i) lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : (range (λ x, nat.find_greatest (P x) b)).finite := (finite_le_nat b).subset $ range_subset_iff.2 $ λ x, nat.find_greatest_le _ lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃ a ∈ s, ∀ a' ∈ s, f a ≤ f a' → f a = f a' := begin refine h.induction_on _ _, { exact λ h, absurd h not_nonempty_empty }, intros a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, λ c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, λ c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end section variables [preorder α] [is_directed α (≤)] [nonempty α] {s : set α} /--A finite set is bounded above.-/ protected lemma finite.bdd_above (hs : s.finite) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : I.finite) : bdd_above (⋃ i ∈ I, S i) ↔ ∀ i ∈ I, bdd_above (S i) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) lemma infinite_of_not_bdd_above : ¬ bdd_above s → s.infinite := mt finite.bdd_above end section variables [preorder α] [is_directed α (≥)] [nonempty α] {s : set α} /--A finite set is bounded below.-/ protected lemma finite.bdd_below (hs : s.finite) : bdd_below s := @finite.bdd_above αᵒᵈ _ _ _ _ hs /--A finite union of sets which are all bounded below is still bounded below.-/ lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : I.finite) : bdd_below (⋃ i ∈ I, S i) ↔ ∀ i ∈ I, bdd_below (S i) := @finite.bdd_above_bUnion αᵒᵈ _ _ _ _ _ _ H lemma infinite_of_not_bdd_below : ¬ bdd_below s → s.infinite := mt finite.bdd_below end end set namespace finset /-- A finset is bounded above. -/ protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := s.finite_to_set.bdd_above /-- A finset is bounded below. -/ protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := s.finite_to_set.bdd_below end finset variables [linear_order α] /-- If a linear order does not contain any triple of elements `x < y < z`, then this type is finite. -/ lemma finite.of_forall_not_lt_lt (h : ∀ ⦃x y z : α⦄, x < y → y < z → false) : finite α := begin nontriviality α, rcases exists_pair_ne α with ⟨x, y, hne⟩, refine @finite.of_fintype α ⟨{x, y}, λ z , _⟩, simpa [hne] using eq_or_eq_or_eq_of_forall_not_lt_lt h z x y end /-- If a set `s` does not contain any triple of elements `x < y < z`, then `s` is finite. -/ lemma set.finite_of_forall_not_lt_lt {s : set α} (h : ∀ (x y z ∈ s), x < y → y < z → false) : set.finite s := @set.to_finite _ s $ finite.of_forall_not_lt_lt $ by simpa only [set_coe.forall'] using h lemma set.finite_diff_Union_Ioo (s : set α) : (s \ ⋃ (x ∈ s) (y ∈ s), Ioo x y).finite := set.finite_of_forall_not_lt_lt $ λ x hx y hy z hz hxy hyz, hy.2 $ mem_Union₂_of_mem hx.1 $ mem_Union₂_of_mem hz.1 ⟨hxy, hyz⟩ lemma set.finite_diff_Union_Ioo' (s : set α) : (s \ ⋃ x : s × s, Ioo x.1 x.2).finite := by simpa only [Union, supr_prod, supr_subtype] using s.finite_diff_Union_Ioo
ce8bd65c10c0c5acd4ef574efb16cc80b3b26d21
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/finset/pimage.lean
d2a0656906b33d4cc46ffd7f0467379d5fda1d21
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,007
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.finset.basic import data.pfun /-! # Image of a `finset α` under a partially defined function In this file we define `part.to_finset` and `finset.pimage`. We also prove some trivial lemmas about these definitions. ## Tags finite set, image, partial function -/ variables {α β : Type*} namespace part /-- Convert a `o : part α` with decidable `part.dom o` to `finset α`. -/ def to_finset (o : part α) [decidable o.dom] : finset α := o.to_option.to_finset @[simp] lemma mem_to_finset {o : part α} [decidable o.dom] {x : α} : x ∈ o.to_finset ↔ x ∈ o := by simp [to_finset] @[simp] theorem to_finset_none [decidable (none : part α).dom] : none.to_finset = (∅ : finset α) := by simp [to_finset] @[simp] theorem to_finset_some {a : α} [decidable (some a).dom] : (some a).to_finset = {a} := by simp [to_finset] @[simp] lemma coe_to_finset (o : part α) [decidable o.dom] : (o.to_finset : set α) = {x | x ∈ o} := set.ext $ λ x, mem_to_finset end part namespace finset variables [decidable_eq β] {f g : α →. β} [∀ x, decidable (f x).dom] [∀ x, decidable (g x).dom] {s t : finset α} {b : β} /-- Image of `s : finset α` under a partially defined function `f : α →. β`. -/ def pimage (f : α →. β) [∀ x, decidable (f x).dom] (s : finset α) : finset β := s.bUnion (λ x, (f x).to_finset) @[simp] lemma mem_pimage : b ∈ s.pimage f ↔ ∃ (a ∈ s), b ∈ f a := by simp [pimage] @[simp, norm_cast] lemma coe_pimage : (s.pimage f : set β) = f.image s := set.ext $ λ x, mem_pimage @[simp] lemma pimage_some (s : finset α) (f : α → β) [∀ x, decidable (part.some $ f x).dom] : s.pimage (λ x, part.some (f x)) = s.image f := by { ext, simp [eq_comm] } lemma pimage_congr (h₁ : s = t) (h₂ : ∀ x ∈ t, f x = g x) : s.pimage f = t.pimage g := by { subst s, ext y, simp [h₂] { contextual := tt } } /-- Rewrite `s.pimage f` in terms of `finset.filter`, `finset.attach`, and `finset.image`. -/ lemma pimage_eq_image_filter : s.pimage f = (filter (λ x, (f x).dom) s).attach.image (λ x, (f x).get (mem_filter.1 x.coe_prop).2) := by { ext x, simp [part.mem_eq, and.exists, -exists_prop] } lemma pimage_union [decidable_eq α] : (s ∪ t).pimage f = s.pimage f ∪ t.pimage f := coe_inj.1 $ by simp only [coe_pimage, pfun.image_union, coe_union] @[simp] lemma pimage_empty : pimage f ∅ = ∅ := by { ext, simp } lemma pimage_subset {t : finset β} : s.pimage f ⊆ t ↔ ∀ (x ∈ s) (y ∈ f x), y ∈ t := by simp [subset_iff, @forall_swap _ β] @[mono] lemma pimage_mono (h : s ⊆ t) : s.pimage f ⊆ t.pimage f := pimage_subset.2 $ λ x hx y hy, mem_pimage.2 ⟨x, h hx, hy⟩ lemma pimage_inter [decidable_eq α] : (s ∩ t).pimage f ⊆ s.pimage f ∩ t.pimage f := by simp only [← coe_subset, coe_pimage, coe_inter, pfun.image_inter] end finset
aae2d438967dd1311d301c5e7dfe912457890018
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0207/Q0207.lean
9f20d71db8a615910484d4a6ad6cdea322d79164
[ "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
424
lean
/- Q7 : are the following numbers rational or irrational (a) sqrt(2)+sqrt(3/2) (b) 1+sqrt(2)+sqrt(3/2) (c) 2sqrt(18)-3sqrt(8) -/ theorem Q7a : M1F.is_irrational (square_root.sqrt_abs 2 + square_root.sqrt_abs (3/2)) := sorry theorem Q7b : M1F.is_irrational (1+square_root.sqrt_abs 2+square_root.sqrt_abs (3/2)) := sorry theorem Q7c : exists q:ℚ, (q:ℝ) = 2*square_root.sqrt_abs 18 - 3 * square_root.sqrt_abs 8 := sorry
3acc36705049c67ef777cd88e61790851ce7c56e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/function/special_functions/is_R_or_C.lean
105fbac18bb909f916b9c85bd0e6fd7b2c9ef485
[ "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
2,569
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.function.special_functions.basic import data.is_R_or_C.lemmas /-! # Measurability of the basic `is_R_or_C` functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ noncomputable theory open_locale nnreal ennreal namespace is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] @[measurability] lemma measurable_re : measurable (re : 𝕜 → ℝ) := continuous_re.measurable @[measurability] lemma measurable_im : measurable (im : 𝕜 → ℝ) := continuous_im.measurable end is_R_or_C section is_R_or_C_composition variables {α 𝕜 : Type*} [is_R_or_C 𝕜] {m : measurable_space α} {f : α → 𝕜} {μ : measure_theory.measure α} include m @[measurability] lemma measurable.re (hf : measurable f) : measurable (λ x, is_R_or_C.re (f x)) := is_R_or_C.measurable_re.comp hf @[measurability] lemma ae_measurable.re (hf : ae_measurable f μ) : ae_measurable (λ x, is_R_or_C.re (f x)) μ := is_R_or_C.measurable_re.comp_ae_measurable hf @[measurability] lemma measurable.im (hf : measurable f) : measurable (λ x, is_R_or_C.im (f x)) := is_R_or_C.measurable_im.comp hf @[measurability] lemma ae_measurable.im (hf : ae_measurable f μ) : ae_measurable (λ x, is_R_or_C.im (f x)) μ := is_R_or_C.measurable_im.comp_ae_measurable hf omit m end is_R_or_C_composition section variables {α 𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space α] {f : α → 𝕜} {μ : measure_theory.measure α} @[measurability] lemma is_R_or_C.measurable_of_real : measurable (coe : ℝ → 𝕜) := is_R_or_C.continuous_of_real.measurable lemma measurable_of_re_im (hre : measurable (λ x, is_R_or_C.re (f x))) (him : measurable (λ x, is_R_or_C.im (f x))) : measurable f := begin convert (is_R_or_C.measurable_of_real.comp hre).add ((is_R_or_C.measurable_of_real.comp him).mul_const is_R_or_C.I), { ext1 x, exact (is_R_or_C.re_add_im _).symm }, all_goals { apply_instance }, end lemma ae_measurable_of_re_im (hre : ae_measurable (λ x, is_R_or_C.re (f x)) μ) (him : ae_measurable (λ x, is_R_or_C.im (f x)) μ) : ae_measurable f μ := begin convert (is_R_or_C.measurable_of_real.comp_ae_measurable hre).add ((is_R_or_C.measurable_of_real.comp_ae_measurable him).mul_const is_R_or_C.I), { ext1 x, exact (is_R_or_C.re_add_im _).symm }, all_goals { apply_instance }, end end
6ccc5c0bab97bb00dc6ba0878a4f38aef1958670
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/matrix/basic.lean
564ed2d436c492917b79070f4b2aaa13b9dba76d
[ "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
19,135
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin Matrices -/ import algebra.pi_instances universes u v w open_locale big_operators @[nolint unused_arguments] def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) := m → n → α namespace matrix variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix def col (w : m → α) : matrix m punit α | x y := w x def row (v : n → α) : matrix punit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl section diagonal variables [decidable_eq n] def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_val_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_val_ne' h] } end section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i @[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_val_ne theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_val_ne' end one end diagonal @[simp] theorem diagonal_add [decidable_eq n] [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases i = j; simp [h] section dot_product /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) : dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [comm_semiring α] (v w : m → α) : dot_product v w = dot_product w v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : dot_product v w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] @[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 := zero_dot_product v @[simp] lemma add_dot_product [semiring α] (u v w : m → α) : dot_product (u + v) w = dot_product u w + dot_product v w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add [semiring α] (u v w : m → α) : dot_product u (v + w) = dot_product u v + dot_product u w := by simp [dot_product, mul_add, finset.sum_add_distrib] @[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product (diagonal v i) w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_val_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (diagonal w i) = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_val_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_val_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w := by simp [dot_product] @[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w := by simp [dot_product] @[simp] lemma smul_dot_product [semiring α] (x : α) (v w : m → α) : dot_product (x • v) w = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc] @[simp] lemma dot_product_smul [comm_semiring α] (x : α) (v w : m → α) : dot_product v (x • w) = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc, mul_comm, mul_left_comm] end dot_product protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, dot_product (λ j, M i j) (λ j, N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ lemma is_add_monoid_hom_mul_left (M : matrix l m α) : is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) := { to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ } lemma is_add_monoid_hom_mul_right (M : matrix m n α) : is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) := { to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ } protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : s.sum f ⬝ M = s.sum (λ a, f a ⬝ M) := (@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ s.sum f = s.sum (λ a, M ⬝ f a) := (@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm @[simp] lemma row_mul_col_val (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w := rfl end semiring section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar instance {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] : semimodule α (matrix m n β) := pi.semimodule _ _ _ instance {β : Type w} [ring α] [add_comm_group β] [module α β] : module α (matrix m n β) := { .. matrix.semimodule } @[simp] lemma smul_val [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl section comm_semiring variables [comm_semiring α] lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } end comm_semiring section semiring variables [semiring α] def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y def mul_vec (M : matrix m n α) (v : n → α) : m → α | i := dot_product (λ j, M i j) v def vec_mul (v : m → α) (M : matrix m n α) : n → α | j := dot_product v (λ i, M i j) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, apply add_dot_product end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x @[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } @[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp [vec_mul_vec, mul_val], refl } end semiring section ring variables [ring α] lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } end ring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_val`, `diagonal_val_eq`, etc. -/ @[simp] lemma transpose_val (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_val_eq] }, { simp only [diagonal_val_ne h, diagonal_val_ne (λ p, h (symm p))] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul [comm_ring α] (c : α)(M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl end transpose def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_val (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_val (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl} @[simp] lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl} lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} end row_col end matrix
a7aa772c7302603dd175d67a456ca2ac65ea21ae
6e4b1527dfc11d1b56419f0d747c66d3b258260b
/src/parsing/expr.lean
1b7d663440549f8377bd7257046795300f49ad8b
[ "Apache-2.0" ]
permissive
jroesch/parsing
7860046a3b96dd3695f25e274034de518a2da7c6
8ac39e59498d33b674fda526bfef44af66ca9df8
refs/heads/master
1,626,501,031,276
1,508,386,101,000
1,508,386,101,000
107,495,434
1
0
null
null
null
null
UTF-8
Lean
false
false
4,005
lean
import .core namespace parser namespace expr inductive assoc | none | left | right inductive operator (elem a : Type) | inf : parser elem (a → a → a) → assoc → operator | pre : parser elem (a → a) → operator | post : parser elem (a → a) → operator @[reducible] def op_table (elem a : Type) := (list (parser elem (a → a → a)) × list (parser elem (a → a → a)) × list (parser elem (a → a → a)) × list (parser elem (a → a)) × list (parser elem (a → a))) def op_table.empty {elem a : Type} : op_table elem a := ([],[],[],[],[]) def split_op {elem a : Type} : operator elem a → op_table elem a → op_table elem a | (operator.inf op assoc.none) (rassoc, lassoc, nassoc, pre, post) := (rassoc,lassoc,op::nassoc,pre,post) | (operator.inf op assoc.left) (rassoc, lassoc, nassoc, pre, post):= (rassoc, op::lassoc,nassoc,pre,post) | (operator.inf op assoc.right) (rassoc, lassoc, nassoc, pre, post):= (op::rassoc,lassoc,nassoc,pre,post) | (operator.pre op) (rassoc, lassoc, nassoc, pre, post) := (rassoc,lassoc,nassoc,op::pre,post) | (operator.post op) (rassoc, lassoc, nassoc, pre, post) := (rassoc,lassoc,nassoc,pre,op::post). @[reducible] def operator_table (elem a : Type) := list $ list $ operator elem a def ambigious {elem a b : Type} (assoc : string) (op : parser elem a) : parser elem b := parser.try $ do op, parser.fail $ "ambigous use of a " ++ assoc ++ " associative operator" def rassoc_p' {elem a : Type} (rassoc_op : parser elem (a → a → a)) (amb_left amb_non term_p : parser elem a) (x : a) : parser elem a := @parser.fix_fn elem a a (fun rassoc_p x, let rassoc_p1 := fun (x : a), rassoc_p x <|> return x in (do f ← rassoc_op, y ← (do z ← term_p, rassoc_p1 z), return (f x y)) <|> amb_left <|> amb_non) x -- lassocP x = do{ f <- lassocOp -- ; y <- termP -- ; lassocP1 (f x y) -- } -- <|> ambigiousRight -- <|> ambigiousNon -- -- <|> return x -- lassocP1 x = lassocP x <|> return x def lassoc_p' {elem a : Type} (lassoc_op : parser elem (a → a → a)) (amb_right amb_non term_p : parser elem a) (x : a) : parser elem a := @parser.fix_fn elem a a (fun lassoc_p x, let lassoc_p1 := fun (x : a), lassoc_p x <|> pure x in (do f ← lassoc_op, y ← term_p, lassoc_p1 (f x y)) <|> amb_right <|> amb_non) x private def make_parser {elem a : Type} (term : parser elem a) (ops : list $ operator elem a) : parser elem a := let (rassoc, lassoc, nassoc, pre, post) := list.foldr split_op op_table.empty ops, rassoc_op := parser.choice rassoc, lassoc_op := parser.choice lassoc, nassoc_op := parser.choice nassoc, prefix_op := parser.choice pre, -- <?> "" postfix_op := parser.choice post, -- <?> "" ambigious_right := @ambigious _ _ a "right" rassoc_op, ambigious_left := @ambigious _ _ a "left" lassoc_op, ambigious_non := @ambigious _ _ a"non" nassoc_op, prefix_p := prefix_op <|> return id, postfix_p := postfix_op <|> return id, term_p := (do pre <- prefix_p, x ← term, post ← postfix_p, return (post (pre x))), rassoc_p := rassoc_p' rassoc_op ambigious_left ambigious_non term_p, lassoc_p := lassoc_p' lassoc_op ambigious_right ambigious_non term_p, nassoc_p := (fun (x : a), (do f ← nassoc_op, y ← term_p, ambigious_right <|> ambigious_left <|> ambigious_non <|> pure (f x y))) in do x ← term_p, rassoc_p x <|> lassoc_p x <|> nassoc_p x <|> return x def mk_expr_parser {elem a : Type} : operator_table elem a → parser elem a → parser elem a | table simple_expr := table.foldl make_parser simple_expr end expr end parser
b4c2ec8cd022c73ce37547e9c092c23c10933b4e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/bernstein.lean
e84fbc01ca3d0e638a72703c1fd51d9dc47af3c6
[ "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
12,806
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.order.field.basic import ring_theory.polynomial.bernstein import topology.continuous_function.polynomial import topology.continuous_function.compact /-! # Bernstein approximations and Weierstrass' theorem We prove that the Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. Our proof follows [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D. The original proof, due to [Bernstein](bernstein1912) in 1912, is probabilistic, and relies on Bernoulli's theorem, which gives bounds for how quickly the observed frequencies in a Bernoulli trial approach the underlying probability. The proof here does not directly rely on Bernoulli's theorem, but can also be given a probabilistic account. * Consider a weighted coin which with probability `x` produces heads, and with probability `1-x` produces tails. * The value of `bernstein n k x` is the probability that such a coin gives exactly `k` heads in a sequence of `n` tosses. * If such an appearance of `k` heads results in a payoff of `f(k / n)`, the `n`-th Bernstein approximation for `f` evaluated at `x` is the expected payoff. * The main estimate in the proof bounds the probability that the observed frequency of heads differs from `x` by more than some `δ`, obtaining a bound of `(4 * n * δ^2)⁻¹`, irrespective of `x`. * This ensures that for `n` large, the Bernstein approximation is (uniformly) close to the payoff function `f`. (You don't need to think in these terms to follow the proof below: it's a giant `calc` block!) This result proves Weierstrass' theorem that polynomials are dense in `C([0,1], ℝ)`, although we defer an abstract statement of this until later. -/ noncomputable theory open_locale classical open_locale big_operators open_locale bounded_continuous_function open_locale unit_interval /-- The Bernstein polynomials, as continuous functions on `[0,1]`. -/ def bernstein (n ν : ℕ) : C(I, ℝ) := (bernstein_polynomial ℝ n ν).to_continuous_map_on I @[simp] lemma bernstein_apply (n ν : ℕ) (x : I) : bernstein n ν x = n.choose ν * x^ν * (1-x)^(n-ν) := begin dsimp [bernstein, polynomial.to_continuous_map_on, polynomial.to_continuous_map, bernstein_polynomial], simp, end lemma bernstein_nonneg {n ν : ℕ} {x : I} : 0 ≤ bernstein n ν x := begin simp only [bernstein_apply], exact mul_nonneg (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (by unit_interval) _)) (pow_nonneg (by unit_interval) _), end /-! We now give a slight reformulation of `bernstein_polynomial.variance`. -/ namespace bernstein /-- Send `k : fin (n+1)` to the equally spaced points `k/n` in the unit interval. -/ def z {n : ℕ} (k : fin (n+1)) : I := ⟨(k : ℝ) / n, begin cases n, { norm_num }, { have h₁ : 0 < (n.succ : ℝ) := by exact_mod_cast (nat.succ_pos _), have h₂ : ↑k ≤ n.succ := by exact_mod_cast (fin.le_last k), rw [set.mem_Icc, le_div_iff h₁, div_le_iff h₁], norm_cast, simp [h₂], }, end⟩ local postfix `/ₙ`:90 := z lemma probability (n : ℕ) (x : I) : ∑ k : fin (n+1), bernstein n k x = 1 := begin have := bernstein_polynomial.sum ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range] at this, exact this, end lemma variance {n : ℕ} (h : 0 < (n : ℝ)) (x : I) : ∑ k : fin (n+1), (x - k/ₙ : ℝ)^2 * bernstein n k x = x * (1-x) / n := begin have h' : (n : ℝ) ≠ 0 := ne_of_gt h, apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', dsimp, conv_lhs { simp only [finset.sum_mul, z], }, conv_rhs { rw div_mul_cancel _ h', }, have := bernstein_polynomial.variance ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range, ←polynomial.nat_cast_mul] at this, convert this using 1, { congr' 1, funext k, rw [mul_comm _ (n : ℝ), mul_comm _ (n : ℝ), ←mul_assoc, ←mul_assoc], congr' 1, field_simp [h], ring, }, { ring, }, end end bernstein open bernstein local postfix `/ₙ`:2000 := z /-- The `n`-th approximation of a continuous function on `[0,1]` by Bernstein polynomials, given by `∑ k, f (k/n) * bernstein n k x`. -/ def bernstein_approximation (n : ℕ) (f : C(I, ℝ)) : C(I, ℝ) := ∑ k : fin (n+1), f k/ₙ • bernstein n k /-! We now set up some of the basic machinery of the proof that the Bernstein approximations converge uniformly. A key player is the set `S f ε h n x`, for some function `f : C(I, ℝ)`, `h : 0 < ε`, `n : ℕ` and `x : I`. This is the set of points `k` in `fin (n+1)` such that `k/n` is within `δ` of `x`, where `δ` is the modulus of uniform continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. We show that if `k ∉ S`, then `1 ≤ δ^-2 * (x - k/n)^2`. -/ namespace bernstein_approximation @[simp] lemma apply (n : ℕ) (f : C(I, ℝ)) (x : I) : bernstein_approximation n f x = ∑ k : fin (n+1), f k/ₙ * bernstein n k x := by simp [bernstein_approximation] /-- The modulus of (uniform) continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. -/ def δ (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) : ℝ := f.modulus (ε/2) (half_pos h) lemma δ_pos {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} : 0 < δ f ε h := f.modulus_pos /-- The set of points `k` so `k/n` is within `δ` of `x`. -/ def S (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) (n : ℕ) (x : I) : finset (fin (n+1)) := { k : fin (n+1) | dist k/ₙ x < δ f ε h }.to_finset /-- If `k ∈ S`, then `f(k/n)` is close to `f x`. -/ lemma lt_of_mem_S {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ S f ε h n x) : |f k/ₙ - f x| < ε/2 := begin apply f.dist_lt_of_dist_lt_modulus (ε/2) (half_pos h), simpa [S] using m, end /-- If `k ∉ S`, then as `δ ≤ |x - k/n|`, we have the inequality `1 ≤ δ^-2 * (x - k/n)^2`. This particular formulation will be helpful later. -/ lemma le_of_mem_S_compl {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ (S f ε h n x)ᶜ) : (1 : ℝ) ≤ (δ f ε h)^(-2 : ℤ) * (x - k/ₙ) ^ 2 := begin simp only [finset.mem_compl, not_lt, set.mem_to_finset, set.mem_set_of_eq, S] at m, erw [zpow_neg, ← div_eq_inv_mul, one_le_div (pow_pos δ_pos 2), sq_le_sq, abs_of_pos δ_pos], rwa [dist_comm] at m end end bernstein_approximation open bernstein_approximation open bounded_continuous_function open filter open_locale topological_space /-- The Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. This is the proof given in [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D, and reproduced on wikipedia. -/ theorem bernstein_approximation_uniform (f : C(I, ℝ)) : tendsto (λ n : ℕ, bernstein_approximation n f) at_top (𝓝 f) := begin simp only [metric.nhds_basis_ball.tendsto_right_iff, metric.mem_ball, dist_eq_norm], intros ε h, let δ := δ f ε h, have nhds_zero := tendsto_const_div_at_top_nhds_0_nat (2 * ‖f‖ * δ ^ (-2 : ℤ)), filter_upwards [nhds_zero.eventually (gt_mem_nhds (half_pos h)), eventually_gt_at_top 0] with n nh npos', have npos : 0 < (n:ℝ) := by exact_mod_cast npos', -- Two easy inequalities we'll need later: have w₁ : 0 ≤ 2 * ‖f‖ := mul_nonneg (by norm_num) (norm_nonneg f), have w₂ : 0 ≤ 2 * ‖f‖ * δ^(-2 : ℤ) := mul_nonneg w₁ pow_minus_two_nonneg, -- As `[0,1]` is compact, it suffices to check the inequality pointwise. rw (continuous_map.norm_lt_iff _ h), intro x, -- The idea is to split up the sum over `k` into two sets, -- `S`, where `x - k/n < δ`, and its complement. let S := S f ε h n x, calc |(bernstein_approximation n f - f) x| = |bernstein_approximation n f x - f x| : rfl ... = |bernstein_approximation n f x - f x * 1| : by rw mul_one ... = |bernstein_approximation n f x - f x * (∑ k : fin (n+1), bernstein n k x)| : by rw bernstein.probability ... = |∑ k : fin (n+1), (f k/ₙ - f x) * bernstein n k x| : by simp [bernstein_approximation, finset.mul_sum, sub_mul] ... ≤ ∑ k : fin (n+1), |(f k/ₙ - f x) * bernstein n k x| : finset.abs_sum_le_sum_abs _ _ ... = ∑ k : fin (n+1), |f k/ₙ - f x| * bernstein n k x : by simp_rw [abs_mul, abs_eq_self.mpr bernstein_nonneg] ... = ∑ k in S, |f k/ₙ - f x| * bernstein n k x + ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x : (S.sum_add_sum_compl _).symm -- We'll now deal with the terms in `S` and the terms in `Sᶜ` in separate calc blocks. ... < ε/2 + ε/2 : add_lt_add_of_le_of_lt _ _ ... = ε : add_halves ε, { -- We now work on the terms in `S`: uniform continuity and `bernstein.probability` -- quickly give us a bound. calc ∑ k in S, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in S, ε/2 * bernstein n k x : finset.sum_le_sum (λ k m, (mul_le_mul_of_nonneg_right (le_of_lt (lt_of_mem_S m)) bernstein_nonneg)) ... = ε/2 * ∑ k in S, bernstein n k x : by rw finset.mul_sum -- In this step we increase the sum over `S` back to a sum over all of `fin (n+1)`, -- so that we can use `bernstein.probability`. ... ≤ ε/2 * ∑ k : fin (n+1), bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, bernstein_nonneg)) (le_of_lt (half_pos h)) ... = ε/2 : by rw [bernstein.probability, mul_one] }, { -- We now turn to working on `Sᶜ`: we control the difference term just using `‖f‖`, -- and then insert a `δ^(-2) * (x - k/n)^2` factor -- (which is at least one because we are not in `S`). calc ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in Sᶜ, (2 * ‖f‖) * bernstein n k x : finset.sum_le_sum (λ k m, mul_le_mul_of_nonneg_right (f.dist_le_two_norm _ _) bernstein_nonneg) ... = (2 * ‖f‖) * ∑ k in Sᶜ, bernstein n k x : by rw finset.mul_sum ... ≤ (2 * ‖f‖) * ∑ k in Sᶜ, δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_sum (λ k m, begin conv_lhs { rw ←one_mul (bernstein _ _ _), }, exact mul_le_mul_of_nonneg_right (le_of_mem_S_compl m) bernstein_nonneg, end)) w₁ -- Again enlarging the sum from `Sᶜ` to all of `fin (n+1)` ... ≤ (2 * ‖f‖) * ∑ k : fin (n+1), δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, mul_nonneg (mul_nonneg pow_minus_two_nonneg (sq_nonneg _)) bernstein_nonneg)) w₁ ... = (2 * ‖f‖) * δ^(-2 : ℤ) * ∑ k : fin (n+1), (x - k/ₙ)^2 * bernstein n k x : by conv_rhs { rw [mul_assoc, finset.mul_sum], simp only [←mul_assoc], } -- `bernstein.variance` and `x ∈ [0,1]` gives the uniform bound ... = (2 * ‖f‖) * δ^(-2 : ℤ) * x * (1-x) / n : by { rw variance npos, ring, } ... ≤ (2 * ‖f‖) * δ^(-2 : ℤ) / n : (div_le_div_right npos).mpr $ by refine mul_le_of_le_of_le_one' (mul_le_of_le_one_right w₂ _) _ _ w₂; unit_interval ... < ε/2 : nh, } end
543a64f2ddcb434f4c13b0a407c36e9ef7b436e2
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/deps/galois_stdlib/src/Galois/Category/Coe1.lean
f91bcdc96e3604693ad5fcd7b1819a72d041478e
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
614
lean
universe variables u v w -- This defines a class for "parameterized" coercisions in which we -- want to allow coercising `f tp` to some `g tp` while preserving the -- type `tp`. This allows coercing even when `tp` contains meta variables, -- and using unification across the coercision. class has_coe1 {α:Sort w} (f : α → Sort u) (g : α → Sort v) := (coe : ∀{a : α}, f a → g a) namespace has_coe1 instance refl (α:Sort w) (f : α → Sort u) : has_coe1 f f := ⟨fun a f => f⟩ end has_coe1 def coe1 {α:Type u} {f g : α → Type u} [h:has_coe1 f g] {a:α} (x : f a) : g a := has_coe1.coe g x
afceea823d67dfc98d0d27646685d2fb1e9ebedb
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/function/ae_measurable_sequence.lean
659ab55518ae62ee716400bb85421505714a9c5d
[ "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
6,233
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.measurable_space /-! # Sequence of measurable functions associated to a sequence of a.e.-measurable functions We define here tools to prove statements about limits (infi, supr...) of sequences of `ae_measurable` functions. Given a sequence of a.e.-measurable functions `f : ι → α → β` with hypothesis `hf : ∀ i, ae_measurable (f i) μ`, and a pointwise property `p : α → (ι → β) → Prop` such that we have `hp : ∀ᵐ x ∂μ, p x (λ n, f n x)`, we define a sequence of measurable functions `ae_seq hf p` and a measurable set `ae_seq_set hf p`, such that * `μ (ae_seq_set hf p)ᶜ = 0` * `x ∈ ae_seq_set hf p → ∀ i : ι, ae_seq hf hp i x = f i x` * `x ∈ ae_seq_set hf p → p x (λ n, f n x)` -/ open measure_theory open_locale classical variables {α β γ ι : Type*} [measurable_space α] [measurable_space β] {f : ι → α → β} {μ : measure α} {p : α → (ι → β) → Prop} /-- If we have the additional hypothesis `∀ᵐ x ∂μ, p x (λ n, f n x)`, this is a measurable set whose complement has measure 0 such that for all `x ∈ ae_seq_set`, `f i x` is equal to `(hf i).mk (f i) x` for all `i` and we have the pointwise property `p x (λ n, f n x)`. -/ def ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) : set α := (to_measurable μ {x | (∀ i, f i x = (hf i).mk (f i) x) ∧ p x (λ n, f n x)}ᶜ)ᶜ /-- A sequence of measurable functions that are equal to `f` and verify property `p` on the measurable set `ae_seq_set hf p`. -/ noncomputable def ae_seq (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) : ι → α → β := λ i x, ite (x ∈ ae_seq_set hf p) ((hf i).mk (f i) x) (⟨f i x⟩ : nonempty β).some namespace ae_seq section mem_ae_seq_set lemma mk_eq_fun_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : (hf i).mk (f i) x = f i x := begin have h_ss : ae_seq_set hf p ⊆ {x | ∀ i, f i x = (hf i).mk (f i) x}, { rw [ae_seq_set, ←compl_compl {x | ∀ i, f i x = (hf i).mk (f i) x}, set.compl_subset_compl], refine set.subset.trans (set.compl_subset_compl.mpr (λ x h, _)) (subset_to_measurable _ _), exact h.1, }, exact (h_ss hx i).symm, end lemma ae_seq_eq_mk_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : ae_seq hf p i x = (hf i).mk (f i) x := by simp only [ae_seq, hx, if_true] lemma ae_seq_eq_fun_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) (i : ι) : ae_seq hf p i x = f i x := by simp only [ae_seq_eq_mk_of_mem_ae_seq_set hf hx i, mk_eq_fun_of_mem_ae_seq_set hf hx i] lemma prop_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) : p x (λ n, ae_seq hf p n x) := begin simp only [ae_seq, hx, if_true], rw funext (λ n, mk_eq_fun_of_mem_ae_seq_set hf hx n), have h_ss : ae_seq_set hf p ⊆ {x | p x (λ n, f n x)}, { rw [←compl_compl {x | p x (λ n, f n x)}, ae_seq_set, set.compl_subset_compl], refine set.subset.trans (set.compl_subset_compl.mpr _) (subset_to_measurable _ _), exact λ x hx, hx.2, }, have hx' := set.mem_of_subset_of_mem h_ss hx, exact hx', end lemma fun_prop_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α} (hx : x ∈ ae_seq_set hf p) : p x (λ n, f n x) := begin have h_eq : (λ n, f n x) = λ n, ae_seq hf p n x, from funext (λ n, (ae_seq_eq_fun_of_mem_ae_seq_set hf hx n).symm), rw h_eq, exact prop_of_mem_ae_seq_set hf hx, end end mem_ae_seq_set lemma ae_seq_set_measurable_set {hf : ∀ i, ae_measurable (f i) μ} : measurable_set (ae_seq_set hf p) := (measurable_set_to_measurable _ _).compl lemma measurable (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) (i : ι) : measurable (ae_seq hf p i) := measurable.ite ae_seq_set_measurable_set (hf i).measurable_mk $ measurable_const' $ λ x y, rfl lemma measure_compl_ae_seq_set_eq_zero [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : μ (ae_seq_set hf p)ᶜ = 0 := begin rw [ae_seq_set, compl_compl, measure_to_measurable], have hf_eq := λ i, (hf i).ae_eq_mk, simp_rw [filter.eventually_eq, ←ae_all_iff] at hf_eq, exact filter.eventually.and hf_eq hp, end lemma ae_seq_eq_mk_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : ∀ᵐ (a : α) ∂μ, ∀ (i : ι), ae_seq hf p i a = (hf i).mk (f i) a := begin have h_ss : ae_seq_set hf p ⊆ {a : α | ∀ i, ae_seq hf p i a = (hf i).mk (f i) a}, from λ x hx i, by simp only [ae_seq, hx, if_true], exact le_antisymm (le_trans (measure_mono (set.compl_subset_compl.mpr h_ss)) (le_of_eq (measure_compl_ae_seq_set_eq_zero hf hp))) (zero_le _), end lemma ae_seq_eq_fun_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : ∀ᵐ (a : α) ∂μ, ∀ (i : ι), ae_seq hf p i a = f i a := begin have h_ss : {a : α | ¬∀ (i : ι), ae_seq hf p i a = f i a} ⊆ (ae_seq_set hf p)ᶜ, from λ x, mt (λ hx i, (ae_seq_eq_fun_of_mem_ae_seq_set hf hx i)), exact measure_mono_null h_ss (measure_compl_ae_seq_set_eq_zero hf hp), end lemma ae_seq_n_eq_fun_n_ae [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) (n : ι) : ae_seq hf p n =ᵐ[μ] f n:= ae_all_iff.mp (ae_seq_eq_fun_ae hf hp) n lemma supr [complete_lattice β] [encodable ι] (hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) : (⨆ n, ae_seq hf p n) =ᵐ[μ] ⨆ n, f n := begin simp_rw [filter.eventually_eq, ae_iff, supr_apply], have h_ss : ae_seq_set hf p ⊆ {a : α | (⨆ (i : ι), ae_seq hf p i a) = ⨆ (i : ι), f i a}, { intros x hx, congr, exact funext (λ i, ae_seq_eq_fun_of_mem_ae_seq_set hf hx i), }, exact measure_mono_null (set.compl_subset_compl.mpr h_ss) (measure_compl_ae_seq_set_eq_zero hf hp), end end ae_seq
5f350befb1750429c9c532687a210d8b53a6cb13
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/algebra/relation.lean
ae485882577bf6f4a02dedc9096a4cb3b6512899
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
4,665
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad General properties of relations, and classes for equivalence relations and congruences. -/ import ..init universes u v w hott_theory namespace hott namespace relation /- properties of binary relations -/ section variables {T : Type _} (R : T → T → Type _) @[hott] def reflexive : Type _ := Πx, R x x @[hott] def symmetric : Type _ := Π⦃x y⦄, R x y → R y x @[hott] def transitive : Type _ := Π⦃x y z⦄, R x y → R y z → R x z end /- classes for equivalence relations -/ @[hott, class] structure is_reflexive {T : Type _} (R : T → T → Type _) := (refl : reflexive R) @[hott, class] structure is_symmetric {T : Type _} (R : T → T → Type _) := (symm : symmetric R) @[hott, class] structure is_transitive {T : Type _} (R : T → T → Type _) := (trans : transitive R) @[hott, class] structure is_equivalence {T : Type _} (R : T → T → Type _) extends is_reflexive R, is_symmetric R, is_transitive R -- partial equivalence relation @[hott, class] structure is_PER {T : Type _} (R : T → T → Type _) extends is_symmetric R, is_transitive R -- Generic notation. For example, is_refl R is the reflexivity of R, if that can be -- inferred by type class inference section variables {T : Type _} (R : T → T → Type _) @[hott] def rel_refl [C : is_reflexive R] := is_reflexive.refl R @[hott] def rel_symm [C : is_symmetric R] := is_symmetric.symm R @[hott] def rel_trans [C : is_transitive R] := is_transitive.trans R end /- classes for unary and binary congruences with respect to arbitrary relations -/ @[hott, class] structure is_congruence {T1 : Type _} (R1 : T1 → T1 → Type _) {T2 : Type _} (R2 : T2 → T2 → Type _) (f : T1 → T2) := (congr : Π⦃x y⦄, R1 x y → R2 (f x) (f y)) @[hott, class] structure is_congruence2 {T1 : Type _} (R1 : T1 → T1 → Type _) {T2 : Type _} (R2 : T2 → T2 → Type _) {T3 : Type _} (R3 : T3 → T3 → Type _) (f : T1 → T2 → T3) := (congr2 : Π{x1 y1 : T1} {x2 y2 : T2}, R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2)) namespace is_congruence -- makes the type class explicit @[hott] def app {T1 : Type _} {R1 : T1 → T1 → Type _} {T2 : Type _} {R2 : T2 → T2 → Type _} {f : T1 → T2} (C : is_congruence R1 R2 f) : Π⦃x y : T1⦄, R1 x y → R2 (f x) (f y) := C.congr @[hott] def app2 {T1 : Type _} {R1 : T1 → T1 → Type _} {T2 : Type _} {R2 : T2 → T2 → Type _} {T3 : Type _} {R3 : T3 → T3 → Type _} {f : T1 → T2 → T3} (C : is_congruence2 R1 R2 R3 f) : Π⦃x1 y1 : T1⦄ ⦃x2 y2 : T2⦄, R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2) := C.congr2 /- tools to build instances -/ @[hott] def compose {T2 : Type _} {R2 : T2 → T2 → Type _} {T3 : Type _} {R3 : T3 → T3 → Type _} {g : T2 → T3} (C2 : is_congruence R2 R3 g) ⦃T1 : Type _⦄ {R1 : T1 → T1 → Type _} {f : T1 → T2} [C1 : is_congruence R1 R2 f] : is_congruence R1 R3 (λx, g (f x)) := is_congruence.mk (λx1 x2 H, app C2 (app C1 H)) @[hott] def compose21 {T2 : Type _} {R2 : T2 → T2 → Type _} {T3 : Type _} {R3 : T3 → T3 → Type _} {T4 : Type _} {R4 : T4 → T4 → Type _} {g : T2 → T3 → T4} (C3 : is_congruence2 R2 R3 R4 g) ⦃T1 : Type _⦄ {R1 : T1 → T1 → Type _} {f1 : T1 → T2} [C1 : is_congruence R1 R2 f1] {f2 : T1 → T3} [C2 : is_congruence R1 R3 f2] : is_congruence R1 R4 (λx, g (f1 x) (f2 x)) := is_congruence.mk (λx1 x2 H, app2 C3 (app C1 H) (app C2 H)) @[hott] def const {T2 : Type _} (R2 : T2 → T2 → Type _) (H : relation.reflexive R2) ⦃T1 : Type _⦄ (R1 : T1 → T1 → Type _) (c : T2) : is_congruence R1 R2 (λu : T1, c) := is_congruence.mk (λx y H1, H c) end is_congruence @[hott, instance] def congruence_const {T2 : Type _} (R2 : T2 → T2 → Type _) [C : is_reflexive R2] ⦃T1 : Type _⦄ (R1 : T1 → T1 → Type _) (c : T2) : is_congruence R1 R2 (λu : T1, c) := is_congruence.const R2 (is_reflexive.refl R2) R1 c @[hott, instance] def congruence_star {T : Type _} (R : T → T → Type _) : is_congruence R R (λu, u) := is_congruence.mk (λx y H, H) /- relations that can be coerced to functions / implications-/ @[hott, class] structure mp_like (R : Type _ → Type _ → Type _) := (app : Π{a b : Type _}, R a b → (a → b)) @[hott] def rel_mp (R : Type _ → Type _ → Type _) [C : mp_like R] {a b : Type _} (H : R a b) := mp_like.app H end relation end hott
e9e0c6b21edbd96aa26067daa2f3719a4fcf0bb5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/mv_polynomial/counit.lean
8488c8ff2b48280b437fb2170dcead4d81527999
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
2,855
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.mv_polynomial.basic /-! ## Counit morphisms for multivariate polynomials One may consider the ring of multivariate polynomials `mv_polynomial A R` with coefficients in `R` and variables indexed by `A`. If `A` is not just a type, but an algebra over `R`, then there is a natural surjective algebra homomorphism `mv_polynomial A R →ₐ[R] A` obtained by `X a ↦ a`. ### Main declarations * `mv_polynomial.acounit R A` is the natural surjective algebra homomorphism `mv_polynomial A R →ₐ[R] A` obtained by `X a ↦ a` * `mv_polynomial.counit` is an “absolute” variant with `R = ℤ` * `mv_polynomial.counit_nat` is an “absolute” variant with `R = ℕ` -/ namespace mv_polynomial open function variables (A B R : Type*) [comm_semiring A] [comm_semiring B] [comm_ring R] [algebra A B] /-- `mv_polynomial.acounit A B` is the natural surjective algebra homomorphism `mv_polynomial B A →ₐ[A] B` obtained by `X a ↦ a`. See `mv_polynomial.counit` for the “absolute” variant with `A = ℤ`, and `mv_polynomial.counit_nat` for the “absolute” variant with `A = ℕ`. -/ noncomputable def acounit : mv_polynomial B A →ₐ[A] B := aeval id variables {B} @[simp] lemma acounit_X (b : B) : acounit A B (X b) = b := aeval_X _ b variables {A} (B) @[simp] lemma acounit_C (a : A) : acounit A B (C a) = algebra_map A B a := aeval_C _ a variables (A) lemma acounit_surjective : surjective (acounit A B) := λ b, ⟨X b, acounit_X A b⟩ /-- `mv_polynomial.counit R` is the natural surjective ring homomorphism `mv_polynomial R ℤ →+* R` obtained by `X r ↦ r`. See `mv_polynomial.acounit` for a “relative” variant for algebras over a base ring, and `mv_polynomial.counit_nat` for the “absolute” variant with `R = ℕ`. -/ noncomputable def counit : mv_polynomial R ℤ →+* R := acounit ℤ R /-- `mv_polynomial.counit_nat A` is the natural surjective ring homomorphism `mv_polynomial A ℕ →+* A` obtained by `X a ↦ a`. See `mv_polynomial.acounit` for a “relative” variant for algebras over a base ring and `mv_polynomial.counit` for the “absolute” variant with `A = ℤ`. -/ noncomputable def counit_nat : mv_polynomial A ℕ →+* A := acounit ℕ A lemma counit_surjective : surjective (counit R) := acounit_surjective ℤ R lemma counit_nat_surjective : surjective (counit_nat A) := acounit_surjective ℕ A lemma counit_C (n : ℤ) : counit R (C n) = n := acounit_C _ _ lemma counit_nat_C (n : ℕ) : counit_nat A (C n) = n := acounit_C _ _ variables {R A} @[simp] lemma counit_X (r : R) : counit R (X r) = r := acounit_X _ _ @[simp] lemma counit_nat_X (a : A) : counit_nat A (X a) = a := acounit_X _ _ end mv_polynomial
c210e6b10845b77d69ecc38d22bf66c6b0a597e7
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Elab/Syntax.lean
ef60a800c9e225d3d4b0f91d108152963e50d687
[ "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
28,994
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Command import Lean.Parser.Syntax namespace Lean.Elab.Term /- Expand `optional «precedence»` where «precedence» := leading_parser " : " >> precedenceParser -/ def expandOptPrecedence (stx : Syntax) : MacroM (Option Nat) := if stx.isNone then return none else return some (← evalPrec stx[0][1]) private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := do if ds.size == 0 then throwUnsupportedSyntax else if ds.size == 1 then pure ds[0] else let mut r := ds[0] for d in ds[1:ds.size] do r ← `(ParserDescr.binary `andthen $r $d) return r structure ToParserDescrContext where catName : Name first : Bool leftRec : Bool -- true iff left recursion is allowed /- See comment at `Parser.ParserCategory`. -/ behavior : Parser.LeadingIdentBehavior abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT (Option Nat) TermElabM) private def markAsTrailingParser (lhsPrec : Nat) : ToParserDescrM Unit := set (some lhsPrec) @[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with first := false }) x @[inline] private def withNestedParser {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with leftRec := false, first := false }) x def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do let ctx ← read unless ctx.first && stx.getKind == `Lean.Parser.Syntax.cat do return false let cat := stx[0].getId.eraseMacroScopes unless cat == ctx.catName do return false let prec? ← liftMacroM <| expandOptPrecedence stx[1] unless ctx.leftRec do throwErrorAt stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion" markAsTrailingParser (prec?.getD 0) return true /-- Given a `stx` of category `syntax`, return a pair `(newStx, lhsPrec?)`, where `newStx` is of category `term`. After elaboration, `newStx` should have type `TrailingParserDescr` if `lhsPrec?.isSome`, and `ParserDescr` otherwise. -/ partial def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Option Nat) := do let env ← getEnv let behavior := Parser.leadingIdentBehavior env catName (process stx { catName := catName, first := true, leftRec := true, behavior := behavior }).run none where process (stx : Syntax) : ToParserDescrM Syntax := withRef stx do let kind := stx.getKind if kind == nullKind then processSeq stx else if kind == choiceKind then process stx[0] else if kind == `Lean.Parser.Syntax.paren then process stx[1] else if kind == `Lean.Parser.Syntax.cat then processNullaryOrCat stx else if kind == `Lean.Parser.Syntax.unary then processUnary stx else if kind == `Lean.Parser.Syntax.binary then processBinary stx else if kind == `Lean.Parser.Syntax.sepBy then processSepBy stx else if kind == `Lean.Parser.Syntax.sepBy1 then processSepBy1 stx else if kind == `Lean.Parser.Syntax.atom then processAtom stx else if kind == `Lean.Parser.Syntax.nonReserved then processNonReserved stx else let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _) match stxNew? with | some stxNew => process stxNew | none => throwErrorAt stx "unexpected syntax kind of category `syntax`: {kind}" /- Sequence (aka NullNode) -/ processSeq (stx : Syntax) := do let args := stx.getArgs if (← checkLeftRec stx[0]) then if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax" let args := args.eraseIdx 0 let args ← args.mapM fun arg => withNestedParser do process arg mkParserSeq args else let args ← args.mapIdxM fun i arg => withReader (fun ctx => { ctx with first := ctx.first && i.val == 0 }) do process arg mkParserSeq args /- Resolve the given parser name and return a list of candidates. Each candidate is a pair `(resolvedParserName, isDescr)`. `isDescr == true` if the type of `resolvedParserName` is a `ParserDescr`. -/ resolveParserName (parserName : Name) : ToParserDescrM (List (Name × Bool)) := do try let candidates ← resolveGlobalConstWithInfos (← getRef) parserName /- Convert `candidates` in a list of pairs `(c, isDescr)`, where `c` is the parser name, and `isDescr` is true iff `c` has type `Lean.ParserDescr` or `Lean.TrailingParser` -/ let env ← getEnv candidates.filterMap fun c => match env.find? c with | none => none | some info => match info.type with | Expr.const `Lean.Parser.TrailingParser _ _ => (c, false) | Expr.const `Lean.Parser.Parser _ _ => (c, false) | Expr.const `Lean.ParserDescr _ _ => (c, true) | Expr.const `Lean.TrailingParserDescr _ _ => (c, true) | _ => none catch _ => return [] ensureNoPrec (stx : Syntax) := unless stx[1].isNone do throwErrorAt stx[1] "unexpected precedence" processParserCategory (stx : Syntax) := do let catName := stx[0].getId.eraseMacroScopes if (← read).first && catName == (← read).catName then throwErrorAt stx "invalid atomic left recursive syntax" let prec? ← liftMacroM <| expandOptPrecedence stx[1] let prec := prec?.getD 0 `(ParserDescr.cat $(quote catName) $(quote prec)) processNullaryOrCat (stx : Syntax) := do let id := stx[0].getId.eraseMacroScopes match (← withRef stx[0] <| resolveParserName id) with | [(c, true)] => ensureNoPrec stx; return mkIdentFrom stx c | [(c, false)] => ensureNoPrec stx; `(ParserDescr.parser $(quote c)) | cs@(_ :: _ :: _) => throwError "ambiguous parser declaration {cs.map (·.1)}" | [] => if Parser.isParserCategory (← getEnv) id then processParserCategory stx else if (← Parser.isParserAlias id) then ensureNoPrec stx Parser.ensureConstantParserAlias id `(ParserDescr.const $(quote id)) else throwError "unknown parser declaration/category/alias '{id}'" processUnary (stx : Syntax) := do let aliasName := (stx[0].getId).eraseMacroScopes Parser.ensureUnaryParserAlias aliasName let d ← withNestedParser do process stx[2] `(ParserDescr.unary $(quote aliasName) $d) processBinary (stx : Syntax) := do let aliasName := (stx[0].getId).eraseMacroScopes Parser.ensureBinaryParserAlias aliasName let d₁ ← withNestedParser do process stx[2] let d₂ ← withNestedParser do process stx[4] `(ParserDescr.binary $(quote aliasName) $d₁ $d₂) processSepBy (stx : Syntax) := do let p ← withNestedParser $ process stx[1] let sep := stx[3] let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1] let allowTrailingSep := !stx[5].isNone `(ParserDescr.sepBy $p $sep $psep $(quote allowTrailingSep)) processSepBy1 (stx : Syntax) := do let p ← withNestedParser do process stx[1] let sep := stx[3] let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1] let allowTrailingSep := !stx[5].isNone `(ParserDescr.sepBy1 $p $sep $psep $(quote allowTrailingSep)) processAtom (stx : Syntax) := do match stx[0].isStrLit? with | some atom => /- For syntax categories where initialized with `LeadingIdentBehavior` different from default (e.g., `tactic`), we automatically mark the first symbol as nonReserved. -/ if (← read).behavior != Parser.LeadingIdentBehavior.default && (← read).first then `(ParserDescr.nonReservedSymbol $(quote atom) false) else `(ParserDescr.symbol $(quote atom)) | none => throwUnsupportedSyntax processNonReserved (stx : Syntax) := do match stx[1].isStrLit? with | some atom => `(ParserDescr.nonReservedSymbol $(quote atom) false) | none => throwUnsupportedSyntax end Term namespace Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command private def getCatSuffix (catName : Name) : String := match catName with | Name.str _ s _ => s | _ => unreachable! private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do let quotSymbol := "`(" ++ getCatSuffix catName ++ "|" let name := catName ++ `quot -- TODO(Sebastian): this might confuse the pretty printer, but it lets us reuse the elaborator let kind := ``Lean.Parser.Term.quot let cmd ← `( @[termParser] def $(mkIdent name) : Lean.ParserDescr := Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol)) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.cat $(quote catName) 0) (Lean.ParserDescr.symbol ")")))) elabCommand cmd @[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do let catName := stx[1].getId let attrName := catName.appendAfter "Parser" let env ← getEnv let env ← liftIO $ Parser.registerParserCategory env attrName catName setEnv env declareSyntaxCatQuotParser catName /-- Auxiliary function for creating declaration names from parser descriptions. Example: Given ``` syntax term "+" term : term syntax "[" sepBy(term, ", ") "]" : term ``` It generates the names `term_+_` and `term[_,]` -/ partial def mkNameFromParserSyntax (catName : Name) (stx : Syntax) : CommandElabM Name := mkUnusedBaseName <| Name.mkSimple <| appendCatName <| visit stx "" where visit (stx : Syntax) (acc : String) : String := match stx.isStrLit? with | some val => acc ++ (val.trim.map fun c => if c.isWhitespace then '_' else c).capitalize | none => match stx with | Syntax.node k args => if k == `Lean.Parser.Syntax.cat then acc ++ "_" else args.foldl (init := acc) fun acc arg => visit arg acc | Syntax.ident .. => acc | Syntax.atom .. => acc | Syntax.missing => acc appendCatName (str : String) := match catName with | Name.str _ s _ => s ++ str | _ => str /- We assume a new syntax can be treated as an atom when it starts and ends with a token. Here are examples of atom-like syntax. ``` syntax "(" term ")" : term syntax "[" (sepBy term ",") "]" : term syntax "foo" : term ``` -/ private partial def isAtomLikeSyntax (stx : Syntax) : Bool := let kind := stx.getKind if kind == nullKind then isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1] else if kind == choiceKind then isAtomLikeSyntax stx[0] -- see toParserDescr else if kind == `Lean.Parser.Syntax.paren then isAtomLikeSyntax stx[1] else kind == `Lean.Parser.Syntax.atom @[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do let `($attrKind:attrKind syntax $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $[$ps:stx]* : $catStx) ← pure stx | throwUnsupportedSyntax let cat := catStx.getId.eraseMacroScopes unless (Parser.isParserCategory (← getEnv) cat) do throwErrorAt catStx "unknown category '{cat}'" let syntaxParser := mkNullNode ps -- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise. let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec let prec ← match prec? with | some prec => liftMacroM <| evalPrec prec | none => precDefault let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax cat syntaxParser let prio ← liftMacroM <| evalOptPrio prio? let stxNodeKind := (← getCurrNamespace) ++ name let catParserId := mkIdentFrom stx (cat.appendAfter "Parser") let (val, lhsPrec?) ← runTermElabM none fun _ => Term.toParserDescr syntaxParser cat let declName := mkIdentFrom stx name let d ← if let some lhsPrec := lhsPrec? then `(@[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName : Lean.TrailingParserDescr := ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $(quote lhsPrec) $val) else `(@[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName : Lean.ParserDescr := ParserDescr.node $(quote stxNodeKind) $(quote prec) $val) trace `Elab fun _ => d withMacroExpansion stx d <| elabCommand d /- def syntaxAbbrev := leading_parser "syntax " >> ident >> " := " >> many1 syntaxParser -/ @[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do let declName := stx[1] -- TODO: nonatomic names let (val, _) ← runTermElabM none $ fun _ => Term.toParserDescr stx[3] Name.anonymous let stxNodeKind := (← getCurrNamespace) ++ declName.getId let stx' ← `(def $declName : Lean.ParserDescr := ParserDescr.nodeWithAntiquot $(quote (toString declName.getId)) $(quote stxNodeKind) $val) withMacroExpansion stx stx' $ elabCommand stx' /- Remark: `k` is the user provided kind with the current namespace included. Recall that syntax node kinds contain the current namespace. -/ def elabMacroRulesAux (k : SyntaxNodeKind) (alts : Array Syntax) : CommandElabM Syntax := do let alts ← alts.mapM fun alt => match alt with | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0] if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat let k' := quoted.getKind if k' == k then pure alt else if k' == choiceKind then match quoted.getArgs.find? fun quotAlt => quotAlt.getKind == k with | none => throwErrorAt alt "invalid macro_rules alternative, expected syntax node kind '{k}'" | some quoted => let pat := pat.setArg 1 quoted let pats := pats.elemsAndSeps.set! 0 pat `(matchAltExpr| | $pats,* => $rhs) else throwErrorAt alt "invalid macro_rules alternative, unexpected syntax node kind '{k'}'" | _ => throwUnsupportedSyntax `(@[macro $(Lean.mkIdent k)] def myMacro : Macro := fun $alts:matchAlt* | _ => throw Lean.Macro.Exception.unsupportedSyntax) def inferMacroRulesAltKind : Syntax → CommandElabM SyntaxNodeKind | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0] if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat pure quoted.getKind | _ => throwUnsupportedSyntax def elabNoKindMacroRulesAux (alts : Array Syntax) : CommandElabM Syntax := do let k ← inferMacroRulesAltKind alts[0] if k == choiceKind then throwErrorAt alts[0] "invalid macro_rules alternative, multiple interpretations for pattern (solution: specify node kind using `macro_rules [<kind>] ...`)" else let altsK ← alts.filterM fun alt => do pure $ k == (← inferMacroRulesAltKind alt) let altsNotK ← alts.filterM fun alt => do pure $ k != (← inferMacroRulesAltKind alt) let defCmd ← elabMacroRulesAux k altsK if altsNotK.isEmpty then pure defCmd else `($defCmd:command macro_rules $altsNotK:matchAlt*) @[builtinCommandElab «macro_rules»] def elabMacroRules : CommandElab := adaptExpander fun stx => match stx with | `(macro_rules $alts:matchAlt*) => elabNoKindMacroRulesAux alts | `(macro_rules [$kind] $alts:matchAlt*) => do elabMacroRulesAux ((← getCurrNamespace) ++ kind.getId) alts | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Command.mixfix] def expandMixfix : Macro := fun stx => withAttrKindGlobal stx fun stx => do match stx with | `(infixl $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs$[:$prec]? $op:strLit rhs:$prec1 => $f lhs rhs) | `(infix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs:$prec1 => $f lhs rhs) | `(infixr $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs $[: $prec]? => $f lhs rhs) | `(prefix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op:strLit arg $[: $prec]? => $f arg) | `(postfix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? arg$[:$prec]? $op:strLit => $f arg) | _ => Macro.throwUnsupported where -- set "global" `attrKind`, apply `f`, and restore `attrKind` to result withAttrKindGlobal stx f := do let attrKind := stx[0] let stx := stx.setArg 0 mkAttrKindGlobal let stx ← f stx return stx.setArg 0 attrKind /- Wrap all occurrences of the given `ident` nodes in antiquotations -/ private partial def antiquote (vars : Array Syntax) : Syntax → Syntax | stx => match stx with | `($id:ident) => if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then mkAntiquotNode id else stx | _ => match stx with | Syntax.node k args => Syntax.node k (args.map (antiquote vars)) | stx => stx /- Convert `notation` command lhs item into a `syntax` command item -/ def expandNotationItemIntoSyntaxItem (stx : Syntax) : CommandElabM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then pure $ Syntax.node `Lean.Parser.Syntax.cat #[mkIdentFrom stx `term, stx[1]] else if k == strLitKind then pure $ Syntax.node `Lean.Parser.Syntax.atom #[stx] else throwUnsupportedSyntax def strLitToPattern (stx: Syntax) : MacroM Syntax := match stx.isStrLit? with | some str => pure $ mkAtomFrom stx str | none => Macro.throwUnsupported /- Convert `notation` command lhs item into a pattern element -/ def expandNotationItemIntoPattern (stx : Syntax) : CommandElabM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then mkAntiquotNode stx[0] else if k == strLitKind then liftMacroM <| strLitToPattern stx else throwUnsupportedSyntax /-- Try to derive a `SimpleDelab` from a notation. The notation must be of the form `notation ... => c var_1 ... var_n` where `c` is a declaration in the current scope and the `var_i` are a permutation of the LHS vars. -/ def mkSimpleDelab (attrKind : Syntax) (vars : Array Syntax) (pat qrhs : Syntax) : OptionT CommandElabM Syntax := do match qrhs with | `($c:ident $args*) => let [(c, [])] ← resolveGlobalName c.getId | failure guard <| args.all (Syntax.isIdent ∘ getAntiquotTerm) guard <| args.allDiff -- replace head constant with (unused) antiquotation so we're not dependent on the exact pretty printing of the head let qrhs ← `($(mkAntiquotNode (← `(_))) $args*) `(@[$attrKind:attrKind appUnexpander $(mkIdent c):ident] def unexpand : Lean.PrettyPrinter.Unexpander := fun | `($qrhs) => `($pat) | _ => throw ()) | `($c:ident) => let [(c, [])] ← resolveGlobalName c.getId | failure `(@[$attrKind:attrKind appUnexpander $(mkIdent c):ident] def unexpand : Lean.PrettyPrinter.Unexpander := fun _ => `($pat)) | _ => failure private def expandNotationAux (ref : Syntax) (currNamespace : Name) (attrKind : Syntax) (prec? : Option Syntax) (name? : Option Syntax) (prio? : Option Syntax) (items : Array Syntax) (rhs : Syntax) : CommandElabM Syntax := do let prio ← liftMacroM <| evalOptPrio prio? -- build parser let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem let cat := mkIdentFrom ref `term let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax `term (mkNullNode syntaxParts) -- build macro rules let vars := items.filter fun item => item.getKind == `Lean.Parser.Command.identPrec let vars := vars.map fun var => var[0] let qrhs := antiquote vars rhs let patArgs ← items.mapM expandNotationItemIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let fullName := currNamespace ++ name let pat := Syntax.node fullName patArgs let stxDecl ← `($attrKind:attrKind syntax $[: $prec?]? (name := $(mkIdent name)) (priority := $(quote prio):numLit) $[$syntaxParts]* : $cat) let macroDecl ← `(macro_rules | `($pat) => `($qrhs)) match (← mkSimpleDelab attrKind vars pat qrhs |>.run) with | some delabDecl => mkNullNode #[stxDecl, macroDecl, delabDecl] | none => mkNullNode #[stxDecl, macroDecl] @[builtinCommandElab «notation»] def expandNotation : CommandElab := adaptExpander fun stx => do let currNamespace ← getCurrNamespace match stx with | `($attrKind:attrKind notation $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $items* => $rhs) => -- trigger scoped checks early and only once let _ ← toAttributeKind attrKind expandNotationAux stx currNamespace attrKind prec? name? prio? items rhs | _ => throwUnsupportedSyntax /- Convert `macro` argument into a `syntax` command item -/ def expandMacroArgIntoSyntaxItem : Macro | `(macroArg|$id:ident:$stx) => stx -- can't match against `$s:strLit%$id` because the latter part would be interpreted as an antiquotation on the token -- `strLit`. | `(macroArg|$s:macroArgSymbol) => `(stx|$(s[0]):strLit) | _ => Macro.throwUnsupported /- Convert `macro` arg into a pattern element -/ def expandMacroArgIntoPattern (stx : Syntax) : MacroM Syntax := do match (← expandMacros stx) with | `(macroArg|$id:ident:optional($stx)) => mkSplicePat `optional id "?" | `(macroArg|$id:ident:many($stx)) => mkSplicePat `many id "*" | `(macroArg|$id:ident:many1($stx)) => mkSplicePat `many id "*" | `(macroArg|$id:ident:sepBy($stx, $sep:strLit $[, $stxsep]? $[, allowTrailingSep]?)) => mkSplicePat `sepBy id ((isStrLit? sep).get! ++ "*") | `(macroArg|$id:ident:sepBy1($stx, $sep:strLit $[, $stxsep]? $[, allowTrailingSep]?)) => mkSplicePat `sepBy id ((isStrLit? sep).get! ++ "*") | `(macroArg|$id:ident:$stx) => mkAntiquotNode id | `(macroArg|$s:strLit) => strLitToPattern s -- `"tk"%id` ~> `"tk"%$id` | `(macroArg|$s:macroArgSymbol) => mkNode `token_antiquot #[← strLitToPattern s[0], mkAtom "%", mkAtom "$", s[1][1]] | _ => Macro.throwUnsupported where mkSplicePat kind id suffix := mkNullNode #[mkAntiquotSuffixSpliceNode kind (mkAntiquotNode id) suffix] /- «macro» := leading_parser suppressInsideQuot (Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> macroHead >> many macroArg >> macroTail) -/ def expandMacro (currNamespace : Name) (stx : Syntax) : CommandElabM Syntax := do let attrKind := stx[0] let prec := stx[2].getOptional? let name? ← liftMacroM <| expandOptNamedName stx[3] let prio ← liftMacroM <| expandOptNamedPrio stx[4] let head := stx[5] let args := stx[6].getArgs let cat := stx[8] -- build parser let stxPart ← liftMacroM <| expandMacroArgIntoSyntaxItem head let stxParts ← liftMacroM <| args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- name let name ← match name? with | some name => pure name | none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts) -- build macro rules let patHead ← liftMacroM <| expandMacroArgIntoPattern head let patArgs ← liftMacroM <| args.mapM expandMacroArgIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let pat := Syntax.node (currNamespace ++ name) (#[patHead] ++ patArgs) if stx.getArgs.size == 11 then -- `stx` is of the form `macro $head $args* : $cat => term` let rhs := stx[10] let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let macroRulesCmd ← `(macro_rules | `($pat) => $rhs) return mkNullNode #[stxCmd, macroRulesCmd] else -- `stx` is of the form `macro $head $args* : $cat => `( $body )` let rhsBody := stx[11] let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let macroRulesCmd ← `(macro_rules | `($pat) => `($rhsBody)) return mkNullNode #[stxCmd, macroRulesCmd] @[builtinCommandElab «macro»] def elabMacro : CommandElab := adaptExpander fun stx => do expandMacro (← getCurrNamespace) stx builtin_initialize registerTraceClass `Elab.syntax @[inline] def withExpectedType (expectedType? : Option Expr) (x : Expr → TermElabM Expr) : TermElabM Expr := do Term.tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "expected type must be known" x expectedType /- def elabTail := try (" : " >> ident) >> darrow >> termParser def «elab» := leading_parser suppressInsideQuot (Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> elabHead >> many elabArg >> elabTail) -/ def expandElab (currNamespace : Name) (stx : Syntax) : CommandElabM Syntax := do let ref := stx let attrKind := stx[0] let prec := stx[2].getOptional? let name? ← liftMacroM <| expandOptNamedName stx[3] let prio ← liftMacroM <| expandOptNamedPrio stx[4] let head := stx[5] let args := stx[6].getArgs let cat := stx[8] let expectedTypeSpec := stx[9] let rhs := stx[11] let catName := cat.getId -- build parser let stxPart ← liftMacroM <| expandMacroArgIntoSyntaxItem head let stxParts ← liftMacroM <| args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- name let name ← match name? with | some name => pure name | none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts) -- build pattern for `martch_syntax let patHead ← liftMacroM <| expandMacroArgIntoPattern head let patArgs ← liftMacroM <| args.mapM expandMacroArgIntoPattern let pat := Syntax.node (currNamespace ++ name) (#[patHead] ++ patArgs) let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let elabCmd ← if expectedTypeSpec.hasArgs then if catName == `term then let expId := expectedTypeSpec[1] `(@[termElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Term.TermElab := fun stx expectedType? => match stx with | `($pat) => Lean.Elab.Command.withExpectedType expectedType? fun $expId => $rhs | _ => throwUnsupportedSyntax) else throwErrorAt expectedTypeSpec "syntax category '{catName}' does not support expected type specification" else if catName == `term then `(@[termElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Term.TermElab := fun stx _ => match stx with | `($pat) => $rhs | _ => throwUnsupportedSyntax) else if catName == `command then `(@[commandElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Command.CommandElab := fun | `($pat) => $rhs | _ => throwUnsupportedSyntax) else if catName == `tactic then `(@[tactic $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Tactic.Tactic := fun | `(tactic|$pat) => $rhs | _ => throwUnsupportedSyntax) else -- We considered making the command extensible and support new user-defined categories. We think it is unnecessary. -- If users want this feature, they add their own `elab` macro that uses this one as a fallback. throwError "unsupported syntax category '{catName}'" return mkNullNode #[stxCmd, elabCmd] @[builtinCommandElab «elab»] def elabElab : CommandElab := adaptExpander fun stx => do expandElab (← getCurrNamespace) stx end Lean.Elab.Command
490aa67914bb0bc3bba8e2c43e5c6c75f88d34d8
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab.lean
62ab7fdcf97f37678752debdd5858ea2242eccfb
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,285
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.Elab.Import import Lean.Elab.Exception import Lean.Elab.Config import Lean.Elab.Command import Lean.Elab.Term import Lean.Elab.App import Lean.Elab.Binders import Lean.Elab.LetRec import Lean.Elab.Frontend import Lean.Elab.BuiltinNotation import Lean.Elab.Declaration import Lean.Elab.Tactic import Lean.Elab.Match -- HACK: must come after `Match` because builtin elaborators (for `match` in this case) do not take priorities import Lean.Elab.Quotation import Lean.Elab.Syntax import Lean.Elab.Do import Lean.Elab.StructInst import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.Print import Lean.Elab.MutualDef import Lean.Elab.AuxDef import Lean.Elab.PreDefinition import Lean.Elab.Deriving import Lean.Elab.DeclarationRange import Lean.Elab.Extra import Lean.Elab.GenInjective import Lean.Elab.BuiltinTerm import Lean.Elab.Arg import Lean.Elab.PatternVar import Lean.Elab.ElabRules import Lean.Elab.Macro import Lean.Elab.Notation import Lean.Elab.Mixfix import Lean.Elab.MacroRules import Lean.Elab.BuiltinCommand import Lean.Elab.RecAppSyntax import Lean.Elab.Eval import Lean.Elab.Calc
1225a25af3b521db4eb7c685b8c333aefa6fa03f
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/typeclass_coerce.lean
adfe916d97785d9d2f098768f24396a22ee7908c
[ "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
3,833
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Leonardo de Moura Declare new, simpler coercion class without the special support for transitivity. Test that new tabled typeclass resolution deals with loops and diamonds correctly. -/ new_frontend class HasCoerce (a b : Type) := (coerce : a → b) def coerce {a b : Type} [HasCoerce a b] : a → b := @HasCoerce.coerce a b _ instance coerceTrans {a b c : Type} [HasCoerce b c] [HasCoerce a b] : HasCoerce a c := ⟨fun x => coerce (coerce x : b)⟩ instance coerceBoolToProp : HasCoerce Bool Prop := ⟨fun y => y = true⟩ instance coerceDecidableEq (x : Bool) : Decidable (coerce x) := inferInstanceAs (Decidable (x = true)) instance coerceSubtype {a : Type} {p : a → Prop} : HasCoerce {x // p x} a := ⟨Subtype.val⟩ instance liftCoerceFn {a₁ a₂ b₁ b₂ : Type} [HasCoerce a₂ a₁] [HasCoerce b₁ b₂] : HasCoerce (a₁ → b₁) (a₂ → b₂) := ⟨fun f x => coerce (f (coerce x))⟩ instance liftCoerceFnRange {a b₁ b₂ : Type} [HasCoerce b₁ b₂] : HasCoerce (a → b₁) (a → b₂) := ⟨fun f x => coerce (f x)⟩ instance liftCoerceFnDom {a₁ a₂ b : Type} [HasCoerce a₂ a₁] : HasCoerce (a₁ → b) (a₂ → b) := ⟨fun f x => f (coerce x)⟩ instance liftCoercePair {a₁ a₂ b₁ b₂ : Type} [HasCoerce a₁ a₂] [HasCoerce b₁ b₂] : HasCoerce (a₁ × b₁) (a₂ × b₂) := ⟨fun p => match p with | (x, y) => (coerce x, coerce y)⟩ instance liftCoercePair₁ {a₁ a₂ b : Type} [HasCoerce a₁ a₂] : HasCoerce (a₁ × b) (a₂ × b) := ⟨fun p => match p with | (x, y) => (coerce x, y)⟩ instance liftCoercePair₂ {a b₁ b₂ : Type} [HasCoerce b₁ b₂] : HasCoerce (a × b₁) (a × b₂) := ⟨fun p => match p with | (x, y) => (x, coerce y)⟩ instance liftCoerceList {a b : Type} [HasCoerce a b] : HasCoerce (List a) (List b) := ⟨fun l => List.map (@coerce a b _) l⟩ -- Tests axiom Bot (α : Type) (n : Nat) : Type axiom Left (α : Type) (n : Nat) : Type axiom Right (α : Type) (n : Nat) : Type axiom Top (α : Type) (n : Nat) : Type @[instance] axiom BotToTopSucc (α : Type) (n : Nat) : HasCoerce (Bot α n) (Top α n.succ) @[instance] axiom TopSuccToBot (α : Type) (n : Nat) : HasCoerce (Top α n.succ) (Bot α n) @[instance] axiom TopToRight (α : Type) (n : Nat) : HasCoerce (Top α n) (Right α n) @[instance] axiom TopToLeft (α : Type) (n : Nat) : HasCoerce (Top α n) (Left α n) @[instance] axiom LeftToTop (α : Type) (n : Nat) : HasCoerce (Left α n) (Top α n) @[instance] axiom RightToTop (α : Type) (n : Nat) : HasCoerce (Right α n) (Top α n) @[instance] axiom LeftToBot (α : Type) (n : Nat) : HasCoerce (Left α n) (Bot α n) @[instance] axiom RightToBot (α : Type) (n : Nat) : HasCoerce (Right α n) (Bot α n) @[instance] axiom BotToLeft (α : Type) (n : Nat) : HasCoerce (Bot α n) (Left α n) @[instance] axiom BotToRight (α : Type) (n : Nat) : HasCoerce (Bot α n) (Right α n) #print "-----" set_option synthInstance.maxSteps 10000 #synth HasCoerce (Top Unit Nat.zero) (Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ) #synth HasCoerce (Top Unit Nat.zero × Top Unit Nat.zero × Top Unit Nat.zero) (Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ × Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ × Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ) #synth HasCoerce (Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ → Top Unit Nat.zero) (Top Unit Nat.zero → Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ)
8090f1a0922c2438e6976e8b5e156ac477027615
026eca3e4f104406f03192524c0ebed8b40e468b
/library/init/algebra/order.lean
c85182f7f991ba04daa720a62d85d38d99bf5d12
[ "Apache-2.0" ]
permissive
jpablo/lean
99bebe8f1c3e3df37e19fc4af27d4261efa40bc6
bec8f0688552bc64f9c08fe0459f3fb20f93cb33
refs/heads/master
1,679,677,848,004
1,615,913,211,000
1,615,913,211,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,869
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.logic init.classical init.meta.name init.algebra.classes /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u variables {α : Type u} set_option auto_param.check_exists false section preorder /-! ### Definition of `preorder` and lemmas about types with a `preorder` -/ /-- A preorder is a reflexive, transitive relation `≤` with `a < b` defined in the obvious way. -/ class preorder (α : Type u) extends has_le α, has_lt α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (lt := λ a b, a ≤ b ∧ ¬ b ≤ a) (lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) . order_laws_tac) variables [preorder α] /-- The relation `≤` on a preorder is reflexive. -/ @[refl] lemma le_refl : ∀ a : α, a ≤ a := preorder.le_refl /-- The relation `≤` on a preorder is transitive. -/ @[trans] lemma le_trans : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := preorder.le_trans lemma lt_iff_le_not_le : ∀ {a b : α}, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := preorder.lt_iff_le_not_le lemma lt_of_le_not_le : ∀ {a b : α}, a ≤ b → ¬ b ≤ a → a < b | a b hab hba := lt_iff_le_not_le.mpr ⟨hab, hba⟩ lemma le_not_le_of_lt : ∀ {a b : α}, a < b → a ≤ b ∧ ¬ b ≤ a | a b hab := lt_iff_le_not_le.mp hab lemma le_of_eq {a b : α} : a = b → a ≤ b := λ h, h ▸ le_refl a @[trans] lemma ge_trans : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ a b c h₁ h₂, le_trans h₂ h₁ lemma lt_irrefl : ∀ a : α, ¬ a < a | a haa := match le_not_le_of_lt haa with | ⟨h1, h2⟩ := false.rec _ (h2 h1) end lemma gt_irrefl : ∀ a : α, ¬ a > a := lt_irrefl @[trans] lemma lt_trans : ∀ {a b c : α}, a < b → b < c → a < c | a b c hab hbc := match le_not_le_of_lt hab, le_not_le_of_lt hbc with | ⟨hab, hba⟩, ⟨hbc, hcb⟩ := lt_of_le_not_le (le_trans hab hbc) (λ hca, hcb (le_trans hca hab)) end @[trans] lemma gt_trans : ∀ {a b c : α}, a > b → b > c → a > c := λ a b c h₁ h₂, lt_trans h₂ h₁ lemma ne_of_lt {a b : α} (h : a < b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma ne_of_gt {a b : α} (h : b < a) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma lt_asymm {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a, lt_irrefl a (lt_trans h h1) lemma le_of_lt : ∀ {a b : α}, a < b → a ≤ b | a b hab := (le_not_le_of_lt hab).left @[trans] lemma lt_of_lt_of_le : ∀ {a b c : α}, a < b → b ≤ c → a < c | a b c hab hbc := let ⟨hab, hba⟩ := le_not_le_of_lt hab in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hba (le_trans hbc hca) @[trans] lemma lt_of_le_of_lt : ∀ {a b c : α}, a ≤ b → b < c → a < c | a b c hab hbc := let ⟨hbc, hcb⟩ := le_not_le_of_lt hbc in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hcb (le_trans hca hab) @[trans] lemma gt_of_gt_of_ge {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ @[trans] lemma gt_of_ge_of_gt {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ lemma not_le_of_gt {a b : α} (h : a > b) : ¬ a ≤ b := (le_not_le_of_lt h).right lemma not_lt_of_ge {a b : α} (h : a ≥ b) : ¬ a < b := λ hab, not_le_of_gt hab h lemma le_of_lt_or_eq : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b | a b (or.inl hab) := le_of_lt hab | a b (or.inr hab) := hab ▸ le_refl _ lemma le_of_eq_or_lt {a b : α} (h : a = b ∨ a < b) : a ≤ b := or.elim h le_of_eq le_of_lt instance decidable_lt_of_decidable_le [decidable_rel ((≤) : α → α → Prop)] : decidable_rel ((<) : α → α → Prop) | a b := if hab : a ≤ b then if hba : b ≤ a then is_false $ λ hab', not_le_of_gt hab' hba else is_true $ lt_of_le_not_le hab hba else is_false $ λ hab', hab (le_of_lt hab') end preorder section partial_order /-! ### Definition of `partial_order` and lemmas about types with a partial order -/ /-- A partial order is a reflexive, transitive, antisymmetric relation `≤`. -/ class partial_order (α : Type u) extends preorder α := (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) variables [partial_order α] lemma le_antisymm : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := partial_order.le_antisymm lemma le_antisymm_iff {a b : α} : a = b ↔ a ≤ b ∧ b ≤ a := ⟨λe, ⟨le_of_eq e, le_of_eq e.symm⟩, λ⟨h1, h2⟩, le_antisymm h1 h2⟩ lemma lt_or_eq_of_le : ∀ {a b : α}, a ≤ b → a < b ∨ a = b | a b hab := classical.by_cases (λ hba : b ≤ a, or.inr (le_antisymm hab hba)) (λ hba, or.inl (lt_of_le_not_le hab hba)) lemma le_iff_lt_or_eq : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b | a b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma lt_of_le_of_ne {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂, lt_of_le_not_le h₁ $ mt (le_antisymm h₁) h₂ instance decidable_eq_of_decidable_le [decidable_rel ((≤) : α → α → Prop)] : decidable_eq α | a b := if hab : a ≤ b then if hba : b ≤ a then is_true (le_antisymm hab hba) else is_false (λ heq, hba (heq ▸ le_refl _)) else is_false (λ heq, hab (heq ▸ le_refl _)) end partial_order section linear_order /-! ### Definition of `linear_order` and lemmas about types with a linear order -/ /-- A linear order is reflexive, transitive, antisymmetric and total relation `≤`. We assume that every linear ordered type has decidable `(≤)`, `(<)`, and `(=)`. -/ class linear_order (α : Type u) extends partial_order α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) (decidable_le : decidable_rel (≤)) (decidable_eq : decidable_eq α := @decidable_eq_of_decidable_le _ _ decidable_le) (decidable_lt : decidable_rel ((<) : α → α → Prop) := @decidable_lt_of_decidable_le _ _ decidable_le) variables [linear_order α] lemma le_total : ∀ a b : α, a ≤ b ∨ b ≤ a := linear_order.le_total lemma le_of_not_ge {a b : α} : ¬ a ≥ b → a ≤ b := or.resolve_left (le_total b a) lemma le_of_not_le {a b : α} : ¬ a ≤ b → b ≤ a := or.resolve_left (le_total a b) lemma not_lt_of_gt {a b : α} (h : a > b) : ¬ a < b := lt_asymm h lemma lt_trichotomy (a b : α) : a < b ∨ a = b ∨ b < a := or.elim (le_total a b) (λ h : a ≤ b, or.elim (lt_or_eq_of_le h) (λ h : a < b, or.inl h) (λ h : a = b, or.inr (or.inl h))) (λ h : b ≤ a, or.elim (lt_or_eq_of_le h) (λ h : b < a, or.inr (or.inr h)) (λ h : b = a, or.inr (or.inl h.symm))) lemma le_of_not_gt {a b : α} (h : ¬ a > b) : a ≤ b := match lt_trichotomy a b with | or.inl hlt := le_of_lt hlt | or.inr (or.inl heq) := heq ▸ le_refl a | or.inr (or.inr hgt) := absurd hgt h end lemma lt_of_not_ge {a b : α} (h : ¬ a ≥ b) : a < b := lt_of_le_not_le ((le_total _ _).resolve_right h) h lemma lt_or_ge (a b : α) : a < b ∨ a ≥ b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := or.inr (heq ▸ le_refl a) | or.inr (or.inr hgt) := or.inr (le_of_lt hgt) end lemma le_or_gt (a b : α) : a ≤ b ∨ a > b := or.swap (lt_or_ge b a) lemma lt_or_gt_of_ne {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := absurd heq h | or.inr (or.inr hgt) := or.inr hgt end lemma ne_iff_lt_or_gt {a b : α} : a ≠ b ↔ a < b ∨ a > b := ⟨lt_or_gt_of_ne, λo, or.elim o ne_of_lt ne_of_gt⟩ lemma lt_iff_not_ge (x y : α) : x < y ↔ ¬ x ≥ y := ⟨not_le_of_gt, lt_of_not_ge⟩ @[simp] lemma not_lt {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_gt, not_lt_of_ge⟩ @[simp] lemma not_le {a b : α} : ¬ a ≤ b ↔ b < a := (lt_iff_not_ge _ _).symm instance (a b : α) : decidable (a < b) := linear_order.decidable_lt a b instance (a b : α) : decidable (a ≤ b) := linear_order.decidable_le a b instance (a b : α) : decidable (a = b) := linear_order.decidable_eq a b lemma eq_or_lt_of_not_lt {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then or.inl h₁ else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁))) instance : is_total_preorder α (≤) := {trans := @le_trans _ _, total := le_total} /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_weak_order_of_linear_order : is_strict_weak_order α (<) := is_strict_weak_order_of_is_total_preorder lt_iff_not_ge /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_total_order_of_linear_order : is_strict_total_order α (<) := { trichotomous := lt_trichotomy } end linear_order namespace decidable lemma lt_or_eq_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a < b ∨ a = b := if hba : b ≤ a then or.inr (le_antisymm hab hba) else or.inl (lt_of_le_not_le hab hba) lemma eq_or_lt_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le hab).swap lemma le_iff_lt_or_eq [partial_order α] [@decidable_rel α (≤)] {a b : α} : a ≤ b ↔ a < b ∨ a = b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma le_of_not_lt [linear_order α] {a b : α} (h : ¬ b < a) : a ≤ b := decidable.by_contradiction $ λ h', h $ lt_of_le_not_le ((le_total _ _).resolve_right h') h' lemma not_lt [linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_lt, not_lt_of_ge⟩ lemma lt_or_le [linear_order α] (a b : α) : a < b ∨ b ≤ a := if hba : b ≤ a then or.inr hba else or.inl $ lt_of_not_ge hba lemma le_or_lt [linear_order α] (a b : α) : a ≤ b ∨ b < a := (lt_or_le b a).swap lemma lt_trichotomy [linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := (lt_or_le _ _).imp_right $ λ h, (eq_or_lt_of_le h).imp_left eq.symm lemma lt_or_gt_of_ne [linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ b < a := (lt_trichotomy a b).imp_right $ λ h', h'.resolve_left h /-- Perform a case-split on the ordering of `x` and `y` in a decidable linear order. -/ def lt_by_cases [linear_order α] (x y : α) {P : Sort*} (h₁ : x < y → P) (h₂ : x = y → P) (h₃ : y < x → P) : P := if h : x < y then h₁ h else if h' : y < x then h₃ h' else h₂ (le_antisymm (le_of_not_gt h') (le_of_not_gt h)) lemma ne_iff_lt_or_gt [linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ b < a := ⟨lt_or_gt_of_ne, λo, o.elim ne_of_lt ne_of_gt⟩ lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_lt $ λ h', not_le_of_gt (H h') h end decidable
f640d683568d1f175df4a578195735e74fb43942
e16d4df4c2baa34ab203178cea2c27905a3b63d3
/src/day6.lean
46c01621c902c1c1f50af0440df1fc12573ed8de
[]
no_license
jembishop/advent-of-code-2020
ea29eecb7f1d676dc1fd34b1a66efdbd23248aec
32fd5bc28e7c178277e85dc034b55fce6dd4afce
refs/heads/main
1,675,354,147,711
1,608,705,139,000
1,608,705,139,000
317,705,877
0
0
null
null
null
null
UTF-8
Lean
false
false
1,065
lean
import system.io import utils import data.list.sort open io meta def group_by : list char → list (list char) | [] := [] | (x::xs) := let (ys, zs) := list.span (=x) xs in (x::ys) :: group_by zs def qgroup := list (list char) def parse : string → list (list (list char)) | s := list.map (list.map (λx: string, x.data)) $ list.map ((filter (≠""))∘ (string.split (=' '))) (split_para s) def part : list char → char × (list char) | [] := ('#', []) | (x::xs) := (x, xs) def concat_l {α} : list (list α ) → list α := list.foldr (++) [] meta def qs : qgroup → list (list char) | q := (group_by (list.insertion_sort (≤) (concat_l q))) meta def n_unique : qgroup → ℕ | a := (qs a).length meta def n_all : qgroup → ℕ | a := (filter (λ x, list.length x = a.length) (qs a)).length meta def main : io unit := do contents ← fs.read_file "inputs/day6.txt", let parsed := parse contents.to_string, put_str_ln $ to_string $ suml $ list.map n_unique parsed, put_str_ln $ to_string $ suml $ list.map n_all parsed
c0caecb2fe3bf0f30c0fccc0dee984dc287fd547
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/order/complete_lattice.lean
c3c8c685bdfc60564673528a41829d0354b0ff32
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
52,129
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.bounds /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we also use `bsupr`/`binfi` for "bounded" supremum or infimum, i.e. one of `⨆ i ∈ s, f i`, `⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set variables {α β β₂ : Type*} {ι ι₂ : Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ /-- Note that we rarely use `complete_semilattice_Sup` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ class complete_semilattice_Sup (α : Type*) extends partial_order α, has_Sup α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) section variables [complete_semilattice_Sup α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_semilattice_Sup.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_semilattice_Sup.Sup_le s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_Sup s) lemma le_Sup_iff : a ≤ Sup s ↔ (∀ b, (∀ x ∈ s, x ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (Sup_le hb), λ hb, hb _ (λ x, le_Sup)⟩ theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_of_forall_le' begin simp only [Sup_le_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y,hy,hy'⟩, solve_by_elim [le_trans hy'] end -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq end /-- Note that we rarely use `complete_semilattice_Inf` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ class complete_semilattice_Inf (α : Type*) extends partial_order α, has_Inf α := (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) section variables [complete_semilattice_Inf α] {s t : set α} {a b : α} @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_semilattice_Inf.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_semilattice_Inf.le_Inf s a lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_Inf s) lemma Inf_le_iff : Inf s ≤ a ↔ (∀ b, (∀ x ∈ s, b ≤ x) → b ≤ a) := ⟨λ h b hb, le_trans (le_Inf hb) h, λ hb, hb _ (λ x, Inf_le)⟩ theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le begin simp only [le_Inf_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y,hy,hy'⟩, solve_by_elim [le_trans _ hy'] end -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq end /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ @[protect_proj] class complete_lattice (α : Type*) extends bounded_lattice α, complete_semilattice_Sup α, complete_semilattice_Inf α. /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Sup, bot, top ..complete_lattice_of_Inf my_T _ } ``` -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Inf` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Inf`. -/ def complete_lattice_of_complete_semilattice_Inf (α : Type*) [complete_semilattice_Inf α] : complete_lattice α := complete_lattice_of_Inf α (λ s, is_glb_Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Inf, bot, top ..complete_lattice_of_Sup my_T _ } ``` -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Sup` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Sup`. -/ def complete_lattice_of_complete_semilattice_Sup (α : Type*) [complete_semilattice_Sup α] : complete_lattice α := complete_lattice_of_Sup α (λ s, is_lub_Sup s) /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice (order_dual α) := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α } instance [complete_linear_order α] : complete_linear_order (order_dual α) := { .. order_dual.complete_lattice α, .. order_dual.linear_order α } end order_dual section variables [complete_lattice α] {s t : set α} {a b : α} theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := by finish /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @Sup_inter_le (order_dual α) _ _ _ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := (@is_lub_empty α _).Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := (@is_glb_univ α _).Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq theorem Sup_le_Sup_of_subset_insert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t := le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq)) theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s := le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h) theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := iff.intro (assume h a ha, top_unique $ h ▸ Inf_le ha) (assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha) lemma eq_singleton_top_of_Inf_eq_top_of_nonempty {s : set α} (h_inf : Inf s = ⊤) (hne : s.nonempty) : s = {⊤} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Inf_eq_top at h_inf, exact ⟨hne, h_inf⟩, } @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := @Inf_eq_top (order_dual α) _ _ lemma eq_singleton_bot_of_Sup_eq_bot_of_nonempty {s : set α} (h_sup : Sup s = ⊥) (hne : s.nonempty) : s = {⊥} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Sup_eq_bot at h_sup, exact ⟨hne, h_sup⟩, } /--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`. See `cSup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem Sup_eq_of_forall_le_of_forall_lt_exists_gt (_ : ∀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 (Sup_le ‹∀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_Sup ‹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`. See `cInf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem Inf_eq_of_forall_ge_of_forall_gt_exists_lt (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := @Sup_eq_of_forall_le_of_forall_lt_exists_gt (order_dual α) _ _ ‹_› ‹_› ‹_› end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := is_glb_lt_iff (is_glb_Inf s) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := lt_is_lub_iff (is_lub_Sup s) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) := @Sup_eq_top (order_dual α) _ _ lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- ### supr & infi -/ section variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _ lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _ lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) : f i hi ≤ ⨆ i hi, f i hi := le_supr_of_le i $ le_supr (f i) hi theorem le_bsupr_of_le {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) (h : a ≤ f i hi) : a ≤ ⨆ i hi, f i hi := le_trans h (le_bsupr i hi) theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) : (⨆ i (hi : p i), f i hi) ≤ a := supr_le $ λ i, supr_le $ h i theorem bsupr_le_supr (p : ι → Prop) (f : ι → α) : (⨆ i (H : p i), f i) ≤ ⨆ i, f i := bsupr_le (λ i hi, le_supr f i) theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi := bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi) theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h theorem bsupr_le_bsupr' {p q : ι → Prop} (hpq : ∀ i, p i → q i) {f : ι → α} : (⨆ i (hpi : p i), f i) ≤ ⨆ i (hqi : q i), f i := supr_le_supr $ λ i, supr_le_supr_const (hpq i) @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := (is_lub_le_iff is_lub_supr).trans forall_range_iff theorem supr_lt_iff : supr s < a ↔ ∃ b < a, ∀ i, s i ≤ b := ⟨λ h, ⟨supr s, h, λ i, le_supr s i⟩, λ ⟨b, hba, hsb⟩, (supr_le hsb).trans_lt hba⟩ theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma Sup_sUnion {s : set (set α)} : Sup (⋃₀ s) = ⨆ (t ∈ s), Sup t := begin apply le_antisymm, { apply Sup_le (λ b hb, _), rcases hb with ⟨t, ts, bt⟩, apply le_trans _ (le_supr _ t), exact le_trans (le_Sup bt) (le_supr _ ts), }, { apply supr_le (λ t, _), exact supr_le (λ ts, Sup_le_Sup (λ x xt, ⟨t, ts, xt⟩)) } end lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : (⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) := calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) : supr_le_supr $ λ i, hf.le_map_supr ... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆a∈s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr2 _ lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_le_supr2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi) lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨆ x, g (f x)) = ⨆ y, g y := by simp only [supr, hf.range_comp] lemma supr_congr {α : Type*} [has_Sup α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { convert h1.supr_comp g, exact (funext h2).symm } -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin have := propext pq, subst this, congr' with x, apply f end theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) : (⨅ i hi, f i hi) ≤ f i hi := infi_le_of_le i $ infi_le (f i) hi theorem binfi_le_of_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) (h : f i hi ≤ a) : (⨅ i hi, f i hi) ≤ a := le_trans (binfi_le i hi) h theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) : a ≤ ⨅ i hi, f i hi := le_infi $ λ i, le_infi $ h i theorem infi_le_binfi (p : ι → Prop) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (H : p i), f i := le_binfi (λ i hi, infi_le f i) theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi := le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi) theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := @Sup_eq_supr (order_dual α) _ _ lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) : f (infi s) ≤ (⨅ i, f (s i)) := le_infi $ λ i, hf $ infi_le _ _ lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) := @monotone.le_map_supr2 (order_dual α) (order_dual β) _ _ _ f hf.order_dual _ _ lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a∈s, f a := by rw [Inf_eq_infi]; exact hf.map_infi2_le _ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_le_infi2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨅ x, g (f x)) = ⨅ y, g y := @function.surjective.supr_comp _ _ (order_dual α) _ f hf g lemma infi_congr {α : Type*} [has_Inf α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := @supr_congr _ _ (order_dual α) _ _ _ h h1 h2 @[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := @supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f lemma supr_const_le {x : α} : (⨆ (h : ι), x) ≤ x := supr_le (λ _, le_rfl) lemma le_infi_const {x : α} : x ≤ (⨅ (h : ι), x) := le_infi (λ _, le_rfl) -- We will generalize this to conditionally complete lattices in `cinfi_const`. theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, Inf_singleton] -- We will generalize this to conditionally complete lattices in `csupr_const`. theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := @infi_const (order_dual α) _ _ _ _ @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := @infi_top (order_dual α) _ _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := Inf_eq_top.trans forall_range_iff @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := Sup_eq_bot.trans forall_range_iff @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le /--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b` is larger than `f i` for all `i`, and that this is not the case of any `w<b`. See `csupr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem supr_eq_of_forall_le_of_forall_lt_exists_gt {f : ι → α} (h₁ : ∀ i, f i ≤ b) (h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b := Sup_eq_of_forall_le_of_forall_lt_exists_gt (forall_range_iff.mpr h₁) (λ w hw, exists_range_iff.mpr $ h₂ w hw) /--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b` is smaller than `f i` for all `i`, and that this is not the case of any `w>b`. See `cinfi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem infi_eq_of_forall_ge_of_forall_gt_exists_lt {f : ι → α} (h₁ : ∀ i, b ≤ f i) (h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b := @supr_eq_of_forall_le_of_forall_lt_exists_gt (order_dual α) _ _ _ ‹_› ‹_› ‹_› lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆h:p, a h) = (if h : p then a h else ⊥) := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆h:p, a) = (if p then a else ⊥) := supr_eq_dif (λ _, a) lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅h:p, a h) = (if h : p then a h else ⊤) := @supr_eq_dif (order_dual α) _ _ _ _ lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := infi_eq_dif (λ _, a) -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := @infi_comm (order_dual α) _ _ _ _ @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := @infi_infi_eq_left (order_dual α) _ _ _ _ @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := @infi_infi_eq_right (order_dual α) _ _ _ _ attribute [ematch] le_refl theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_of_left_le $ infi_le _ _) (inf_le_of_right_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := by rw [infi_inf_eq, infi_const] lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf]; simp [inf_comm] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩); rw [infi_subtype', infi_subtype', infi_inf] lemma inf_binfi {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : a ⊓ (⨅i (h : p i), f i h) = (⨅ i (h : p i), a ⊓ f i h) := by simpa only [inf_comm] using binfi_inf h theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := @infi_inf_eq (order_dual α) β _ _ _ lemma supr_sup [h : nonempty ι] {f : ι → α} {a : α} : (⨆ x, f x) ⊔ a = (⨆ x, f x ⊔ a) := @infi_inf (order_dual α) _ _ _ _ _ lemma sup_supr [nonempty ι] {f : ι → α} {a : α} : a ⊔ (⨆ x, f x) = (⨆ x, a ⊔ f x) := @inf_infi (order_dual α) _ _ _ _ _ /-! ### `supr` and `infi` under `Prop` -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le theorem infi_true {s : true → α} : infi s = s trivial := infi_pos trivial theorem supr_true {s : true → α} : supr s = s trivial := supr_pos trivial @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := @infi_exists (order_dual α) _ _ _ _ theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact infi_and } theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := @infi_and (order_dual α) _ _ _ _ /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact supr_and } theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_of_left_le $ infi_le _ _ | or.inr j := inf_le_of_right_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := @infi_or (order_dual α) _ _ _ _ lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := le_antisymm (supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i) (supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _)) lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := @supr_range (order_dual α) _ _ _ _ _ theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := by rw [← infi_subtype'', infi, range_comp, subtype.range_coe] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := @Inf_image (order_dual α) _ _ _ _ /- ### supr and infi under set constructions -/ theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := by simp theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := by simp only [← infi_inf_eq, infi_or] lemma infi_split (f : β → α) (p : β → Prop) : (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) := by convert infi_split _ _; simp theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := @infi_union (order_dual α) _ _ _ _ _ lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := @infi_split (order_dual α) _ _ _ _ lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) := @infi_split_single (order_dual α) _ _ _ _ theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := @infi_le_infi_of_subset (order_dual α) _ _ _ _ _ h theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := @infi_singleton (order_dual α) _ _ _ _ theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := by rw [← Inf_image, ← Inf_image, ← image_comp] lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := @infi_image (order_dual α) _ _ _ _ _ _ /-! ### `supr` and `infi` under `Type` -/ theorem infi_of_empty' (h : ι → false) {s : ι → α} : infi s = ⊤ := top_unique (le_infi $ assume i, (h i).elim) theorem supr_of_empty' (h : ι → false) {s : ι → α} : supr s = ⊥ := bot_unique (supr_le $ assume i, (h i).elim) theorem infi_of_empty (h : ¬nonempty ι) {s : ι → α} : infi s = ⊤ := infi_of_empty' (λ i, h ⟨i⟩) theorem supr_of_empty (h : ¬nonempty ι) {s : ι → α} : supr s = ⊥ := supr_of_empty' (λ i, h ⟨i⟩) @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := infi_of_empty nonempty_empty @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := supr_of_empty nonempty_empty lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := le_antisymm (supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end) (sup_le (le_supr _ _) (le_supr _ _)) lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq (order_dual α) _ _ lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_subtype (order_dual α) _ _ _ _ lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma supr_subtype'' {ι} (s : set ι) (f : ι → α) : (⨆ i : s, f i) = ⨆ (t : ι) (H : t ∈ s), f t := supr_subtype lemma Sup_eq_supr' {s : set α} : Sup s = ⨆ x : s, (x : α) := by rw [Sup_eq_supr, supr_subtype']; refl lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_sigma (order_dual α) _ _ _ _ theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := @infi_prod (order_dual α) _ _ _ _ theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := le_antisymm (le_inf (infi_le_infi2 $ assume i, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume s, match s with | sum.inl i := inf_le_of_left_le $ infi_le _ _ | sum.inr j := inf_le_of_right_le $ infi_le _ _ end) theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := @infi_sum (order_dual α) _ _ _ _ theorem supr_option (f : option β → α) : (⨆ o, f o) = f none ⊔ ⨆ b, f (option.some b) := eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, sup_le_iff, option.forall] theorem infi_option (f : option β → α) : (⨅ o, f o) = f none ⊓ ⨅ b, f (option.some b) := @supr_option (order_dual α) _ _ _ /-! ### `supr` and `infi` under `ℕ` -/ lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) := begin apply le_antisymm; simp only [supr_le_iff], { exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw nat.sub_add_cancel hi }⟩ }, { exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ } end lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) := @supr_ge_eq_supr_nat_add (order_dual α) _ _ _ lemma monotone.supr_nat_add {f : ℕ → α} (hf : monotone f) (k : ℕ) : (⨆ n, f (n + k)) = ⨆ n, f n := le_antisymm (supr_le (λ i, (le_refl _).trans (le_supr _ (i + k)))) (supr_le_supr (λ i, hf (nat.le_add_right i k))) @[simp] lemma supr_infi_ge_nat_add (f : ℕ → α) (k : ℕ) : (⨆ n, ⨅ i ≥ n, f (i + k)) = ⨆ n, ⨅ i ≥ n, f i := begin have hf : monotone (λ n, ⨅ i ≥ n, f i), from λ n m hnm, le_infi (λ i, (infi_le _ i).trans (le_infi (λ h, infi_le _ (hnm.trans h)))), rw ←monotone.supr_nat_add hf k, { simp_rw [infi_ge_eq_infi_nat_add, ←nat.add_assoc], }, end lemma sup_supr_nat_succ (u : ℕ → α) : u 0 ⊔ (⨆ i, u (i + 1)) = ⨆ i, u i := begin refine eq_of_forall_ge_iff (λ c, _), simp only [sup_le_iff, supr_le_iff], refine ⟨λ h, _, λ h, ⟨h _, λ i, h _⟩⟩, rintro (_|i), exacts [h.1, h.2 i] end lemma inf_infi_nat_succ (u : ℕ → α) : u 0 ⊓ (⨅ i, u (i + 1)) = ⨅ i, u i := @sup_supr_nat_succ (order_dual α) _ u end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /-! ### Instances -/ instance Prop.complete_lattice : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, .. Prop.bounded_distrib_lattice } @[simp] lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl @[simp] lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl @[simp] lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) := le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i) @[simp] lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_lattice } lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅ f : s, (f : Πa, β a) a) := rfl @[simp] lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f:s, (f : Πa, β a) a) := rfl lemma unary_relation_Sup_iff {α : Type*} (s : set (α → Prop)) {a : α} : Sup s a ↔ ∃ (r : α → Prop), r ∈ s ∧ r a := by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] } lemma binary_relation_Sup_iff {α β : Type*} (s : set (α → β → Prop)) {a : α} {b : β} : Sup s a b ↔ ∃ (r : α → β → Prop), r ∈ s ∧ r a b := by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] } @[simp] lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := @infi_apply α (λ i, order_dual (β i)) _ _ f a section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h end complete_lattice namespace prod variables (α β) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := assume s p h, ⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := assume s p h, ⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, .. prod.bounded_lattice α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod section complete_lattice variables [complete_lattice α] {a : α} {s : set α} /-- This is a weaker version of `sup_Inf_eq` -/ lemma sup_Inf_le_infi_sup : a ⊔ Inf s ≤ (⨅ b ∈ s, a ⊔ b) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_left (Inf_le h) _ /-- This is a weaker version of `Inf_sup_eq` -/ lemma Inf_sup_le_infi_sup : Inf s ⊔ a ≤ (⨅ b ∈ s, b ⊔ a) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_right (Inf_le h) _ /-- This is a weaker version of `inf_Sup_eq` -/ lemma supr_inf_le_inf_Sup : (⨆ b ∈ s, a ⊓ b) ≤ a ⊓ Sup s := supr_le $ assume i, supr_le $ assume h, inf_le_inf_left _ (le_Sup h) /-- This is a weaker version of `Sup_inf_eq` -/ lemma supr_inf_le_Sup_inf : (⨆ b ∈ s, b ⊓ a) ≤ Sup s ⊓ a := supr_le $ assume i, supr_le $ assume h, inf_le_inf_right _ (le_Sup h) lemma disjoint_Sup_left {a : set α} {b : α} (d : disjoint (Sup a) b) {i} (hi : i ∈ a) : disjoint i b := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_Sup_inf.trans (d : _)) i : _) hi : _) lemma disjoint_Sup_right {a : set α} {b : α} (d : disjoint b (Sup a)) {i} (hi : i ∈ a) : disjoint b i := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_inf_Sup.trans (d : _)) i : _) hi : _) end complete_lattice namespace complete_lattice variables [complete_lattice α] /-- An independent set of elements in a complete lattice is one in which every element is disjoint from the `Sup` of the rest. -/ def set_independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a})) variables {s : set α} (hs : set_independent s) @[simp] lemma set_independent_empty : set_independent (∅ : set α) := λ x hx, (set.not_mem_empty x hx).elim theorem set_independent.mono {t : set α} (hst : t ⊆ s) : set_independent t := λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst)) /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma set_independent.disjoint {x y : α} (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : disjoint x y := disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, by simp [h.symm]⟩) include hs /-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some subset of the rest. -/ lemma set_independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) : disjoint x (Sup y) := begin have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _), rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this, exact this, end omit hs /-- An independent indexed family of elements in a complete lattice is one in which every element is disjoint from the `supr` of the rest. Example: an indexed family of non-zero elements in a vector space is linearly independent iff the indexed family of subspaces they generate is independent in this sense. Example: an indexed family of submodules of a module is independent in this sense if and only the natural map from the direct sum of the submodules to the module is injective. -/ def independent {ι : Sort*} {α : Type*} [complete_lattice α] (t : ι → α) : Prop := ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) lemma set_independent_iff {α : Type*} [complete_lattice α] (s : set α) : set_independent s ↔ independent (coe : s → α) := begin simp_rw [independent, set_independent, set_coe.forall, Sup_eq_supr], apply forall_congr, intro a, apply forall_congr, intro ha, congr' 2, convert supr_subtype.symm, simp [supr_and], end variables {t : ι → α} (ht : independent t) theorem independent_def : independent t ↔ ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) := iff.rfl theorem independent_def' {ι : Type*} {t : ι → α} : independent t ↔ ∀ i, disjoint (t i) (Sup (t '' {j | j ≠ i})) := by {simp_rw Sup_image, refl} theorem independent_def'' {ι : Type*} {t : ι → α} : independent t ↔ ∀ i, disjoint (t i) (Sup {a | ∃ j ≠ i, t j = a}) := by {rw independent_def', tidy} @[simp] lemma independent_empty (t : empty → α) : independent t. @[simp] lemma independent_pempty (t : pempty → α) : independent t. /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma independent.disjoint {x y : ι} (h : x ≠ y) : disjoint (t x) (t y) := disjoint_Sup_right (ht x) ⟨y, by simp [h.symm]⟩ lemma independent.mono {ι : Type*} {α : Type*} [complete_lattice α] {s t : ι → α} (hs : independent s) (hst : t ≤ s) : independent t := λ i, (hs i).mono (hst i) (supr_le_supr $ λ j, supr_le_supr $ λ _, hst j) /-- Composing an indepedent indexed family with an injective function on the index results in another indepedendent indexed family. -/ lemma independent.comp {ι ι' : Sort*} {α : Type*} [complete_lattice α] {s : ι → α} (hs : independent s) (f : ι' → ι) (hf : function.injective f) : independent (s ∘ f) := λ i, (hs (f i)).mono_right begin refine (supr_le_supr $ λ i, _).trans (supr_comp_le _ f), exact supr_le_supr_const hf.ne, end /-- If the elements of a set are independent, then any element is disjoint from the `supr` of some subset of the rest. -/ lemma independent.disjoint_bsupr {ι : Type*} {α : Type*} [complete_lattice α] {t : ι → α} (ht : independent t) {x : ι} {y : set ι} (hx : x ∉ y) : disjoint (t x) (⨆ i ∈ y, t i) := disjoint.mono_right (bsupr_le_bsupr' $ λ i hi, (ne_of_mem_of_not_mem hi hx : _)) (ht x) end complete_lattice
1391b69133c9c53823ead2d32f5130d7ee0d0643
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/algebra/functions.lean
c8b3de6ee0a6ce5b859a6dafe619b6fa0dd0b232
[]
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
4,340
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.algebra.order import Mathlib.Lean3Lib.init.meta.default universes u namespace Mathlib def min {α : Type u} [linear_order α] (a : α) (b : α) : α := ite (a ≤ b) a b def max {α : Type u} [linear_order α] (a : α) (b : α) : α := ite (b ≤ a) a b theorem min_le_left {α : Type u} [linear_order α] (a : α) (b : α) : min a b ≤ a := sorry theorem min_le_right {α : Type u} [linear_order α] (a : α) (b : α) : min a b ≤ b := sorry theorem le_min {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) : c ≤ min a b := sorry theorem le_max_left {α : Type u} [linear_order α] (a : α) (b : α) : a ≤ max a b := sorry theorem le_max_right {α : Type u} [linear_order α] (a : α) (b : α) : b ≤ max a b := sorry theorem max_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) : max a b ≤ c := sorry theorem eq_min {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) (h₃ : ∀ {d : α}, d ≤ a → d ≤ b → d ≤ c) : c = min a b := le_antisymm (le_min h₁ h₂) (h₃ (min_le_left a b) (min_le_right a b)) theorem min_comm {α : Type u} [linear_order α] (a : α) (b : α) : min a b = min b a := eq_min (min_le_right a b) (min_le_left a b) fun (c : α) (h₁ : c ≤ b) (h₂ : c ≤ a) => le_min h₂ h₁ theorem min_assoc {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : min (min a b) c = min a (min b c) := sorry theorem min_left_comm {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : min a (min b c) = min b (min a c) := left_comm min min_comm min_assoc @[simp] theorem min_self {α : Type u} [linear_order α] (a : α) : min a a = a := sorry theorem min_eq_left {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) : min a b = a := Eq.symm (eq_min (le_refl a) h fun (d : α) (ᾰ : d ≤ a) (ᾰ_1 : d ≤ b) => ᾰ) theorem min_eq_right {α : Type u} [linear_order α] {a : α} {b : α} (h : b ≤ a) : min a b = b := min_comm b a ▸ min_eq_left h theorem eq_max {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) (h₃ : ∀ {d : α}, a ≤ d → b ≤ d → c ≤ d) : c = max a b := le_antisymm (h₃ (le_max_left a b) (le_max_right a b)) (max_le h₁ h₂) theorem max_comm {α : Type u} [linear_order α] (a : α) (b : α) : max a b = max b a := eq_max (le_max_right a b) (le_max_left a b) fun (c : α) (h₁ : b ≤ c) (h₂ : a ≤ c) => max_le h₂ h₁ theorem max_assoc {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : max (max a b) c = max a (max b c) := sorry theorem max_left_comm {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : max a (max b c) = max b (max a c) := left_comm max max_comm max_assoc @[simp] theorem max_self {α : Type u} [linear_order α] (a : α) : max a a = a := sorry theorem max_eq_left {α : Type u} [linear_order α] {a : α} {b : α} (h : b ≤ a) : max a b = a := Eq.symm (eq_max (le_refl a) h fun (d : α) (ᾰ : a ≤ d) (ᾰ_1 : b ≤ d) => ᾰ) theorem max_eq_right {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) : max a b = b := max_comm b a ▸ max_eq_left h /- these rely on lt_of_lt -/ theorem min_eq_left_of_lt {α : Type u} [linear_order α] {a : α} {b : α} (h : a < b) : min a b = a := min_eq_left (le_of_lt h) theorem min_eq_right_of_lt {α : Type u} [linear_order α] {a : α} {b : α} (h : b < a) : min a b = b := min_eq_right (le_of_lt h) theorem max_eq_left_of_lt {α : Type u} [linear_order α] {a : α} {b : α} (h : b < a) : max a b = a := max_eq_left (le_of_lt h) theorem max_eq_right_of_lt {α : Type u} [linear_order α] {a : α} {b : α} (h : a < b) : max a b = b := max_eq_right (le_of_lt h) /- these use the fact that it is a linear ordering -/ theorem lt_min {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : a < b) (h₂ : a < c) : a < min b c := sorry theorem max_lt {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : a < c) (h₂ : b < c) : max a b < c := sorry
cdf174defaffdbc0d184ce7cba1396d4af2e3520
e953c38599905267210b87fb5d82dcc3e52a4214
/library/data/rat/order.lean
3ffb228165105c9b18e80fbdf6907d53045c516d
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
14,142
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Adds the ordering, and instantiates the rationals as an ordered field. -/ import data.int algebra.ordered_field .basic open quot eq.ops /- the ordering on representations -/ namespace prerat section int_notation open int variables {a b : prerat} definition pos (a : prerat) : Prop := num a > 0 definition nonneg (a : prerat) : Prop := num a ≥ 0 theorem pos_of_int (a : ℤ) : pos (of_int a) ↔ (#int a > 0) := !iff.rfl theorem nonneg_of_int (a : ℤ) : nonneg (of_int a) ↔ (#int a ≥ 0) := !iff.rfl theorem pos_eq_pos_of_equiv {a b : prerat} (H1 : a ≡ b) : pos a = pos b := propext (iff.intro (num_pos_of_equiv H1) (num_pos_of_equiv H1⁻¹)) theorem nonneg_eq_nonneg_of_equiv (H : a ≡ b) : nonneg a = nonneg b := have H1 : (0 = num a) = (0 = num b), from propext (iff.intro (assume H2, eq.symm (num_eq_zero_of_equiv H H2⁻¹)) (assume H2, eq.symm (num_eq_zero_of_equiv H⁻¹ H2⁻¹))), calc nonneg a = (pos a ∨ 0 = num a) : propext !le_iff_lt_or_eq ... = (pos b ∨ 0 = num a) : pos_eq_pos_of_equiv H ... = (pos b ∨ 0 = num b) : H1 ... = nonneg b : propext !le_iff_lt_or_eq theorem nonneg_zero : nonneg zero := le.refl 0 theorem nonneg_add (H1 : nonneg a) (H2 : nonneg b) : nonneg (add a b) := show num a * denom b + num b * denom a ≥ 0, from add_nonneg (mul_nonneg H1 (le_of_lt (denom_pos b))) (mul_nonneg H2 (le_of_lt (denom_pos a))) theorem nonneg_antisymm (H1 : nonneg a) (H2 : nonneg (neg a)) : a ≡ zero := have H3 : num a = 0, from le.antisymm (nonpos_of_neg_nonneg H2) H1, equiv_zero_of_num_eq_zero H3 theorem nonneg_total (a : prerat) : nonneg a ∨ nonneg (neg a) := or.elim (le.total 0 (num a)) (suppose 0 ≤ num a, or.inl this) (suppose 0 ≥ num a, or.inr (neg_nonneg_of_nonpos this)) theorem nonneg_of_pos (H : pos a) : nonneg a := le_of_lt H theorem ne_zero_of_pos (H : pos a) : ¬ a ≡ zero := assume H', ne_of_gt H (num_eq_zero_of_equiv_zero H') theorem pos_of_nonneg_of_ne_zero (H1 : nonneg a) (H2 : ¬ a ≡ zero) : pos a := have num a ≠ 0, from suppose num a = 0, H2 (equiv_zero_of_num_eq_zero this), lt_of_le_of_ne H1 (ne.symm this) theorem nonneg_mul (H1 : nonneg a) (H2 : nonneg b) : nonneg (mul a b) := mul_nonneg H1 H2 theorem pos_mul (H1 : pos a) (H2 : pos b) : pos (mul a b) := mul_pos H1 H2 end int_notation end prerat local attribute prerat.setoid [instance] /- The ordering on the rationals. The definitions of pos and nonneg are kept private, because they are only meant for internal use. Users should use a > 0 and a ≥ 0 instead of pos and nonneg. -/ namespace rat variables {a b c : ℚ} /- transfer properties of pos and nonneg -/ private definition pos (a : ℚ) : Prop := quot.lift prerat.pos @prerat.pos_eq_pos_of_equiv a private definition nonneg (a : ℚ) : Prop := quot.lift prerat.nonneg @prerat.nonneg_eq_nonneg_of_equiv a private theorem pos_of_int (a : ℤ) : (#int a > 0) ↔ pos (of_int a) := prerat.pos_of_int a private theorem nonneg_of_int (a : ℤ) : (#int a ≥ 0) ↔ nonneg (of_int a) := prerat.nonneg_of_int a private theorem nonneg_zero : nonneg 0 := prerat.nonneg_zero private theorem nonneg_add : nonneg a → nonneg b → nonneg (a + b) := quot.induction_on₂ a b @prerat.nonneg_add private theorem nonneg_antisymm : nonneg a → nonneg (-a) → a = 0 := quot.induction_on a (take u, assume H1 H2, quot.sound (prerat.nonneg_antisymm H1 H2)) private theorem nonneg_total (a : ℚ) : nonneg a ∨ nonneg (-a) := quot.induction_on a @prerat.nonneg_total private theorem nonneg_of_pos : pos a → nonneg a := quot.induction_on a @prerat.nonneg_of_pos private theorem ne_zero_of_pos : pos a → a ≠ 0 := quot.induction_on a (take u, assume H1 H2, prerat.ne_zero_of_pos H1 (quot.exact H2)) private theorem pos_of_nonneg_of_ne_zero : nonneg a → ¬ a = 0 → pos a := quot.induction_on a (take u, assume h : nonneg ⟦u⟧, suppose ⟦u⟧ ≠ (rat.of_num 0), have ¬ (prerat.equiv u prerat.zero), from assume H, this (quot.sound H), prerat.pos_of_nonneg_of_ne_zero h this) private theorem nonneg_mul : nonneg a → nonneg b → nonneg (a * b) := quot.induction_on₂ a b @prerat.nonneg_mul private theorem pos_mul : pos a → pos b → pos (a * b) := quot.induction_on₂ a b @prerat.pos_mul private definition decidable_pos (a : ℚ) : decidable (pos a) := quot.rec_on_subsingleton a (take u, int.decidable_lt 0 (prerat.num u)) /- define order in terms of pos and nonneg -/ definition lt (a b : ℚ) : Prop := pos (b - a) definition le (a b : ℚ) : Prop := nonneg (b - a) definition gt [reducible] (a b : ℚ) := lt b a definition ge [reducible] (a b : ℚ) := le b a infix [priority rat.prio] < := rat.lt infix [priority rat.prio] <= := rat.le infix [priority rat.prio] ≤ := rat.le infix [priority rat.prio] >= := rat.ge infix [priority rat.prio] ≥ := rat.ge infix [priority rat.prio] > := rat.gt theorem of_int_lt_of_int (a b : ℤ) : of_int a < of_int b ↔ (#int a < b) := iff.symm (calc (#int a < b) ↔ (#int b - a > 0) : iff.symm !int.sub_pos_iff_lt ... ↔ pos (of_int (#int b - a)) : iff.symm !pos_of_int ... ↔ pos (of_int b - of_int a) : !of_int_sub ▸ iff.rfl ... ↔ of_int a < of_int b : iff.rfl) theorem of_int_le_of_int (a b : ℤ) : of_int a ≤ of_int b ↔ (#int a ≤ b) := iff.symm (calc (#int a ≤ b) ↔ (#int b - a ≥ 0) : iff.symm !int.sub_nonneg_iff_le ... ↔ nonneg (of_int (#int b - a)) : iff.symm !nonneg_of_int ... ↔ nonneg (of_int b - of_int a) : !of_int_sub ▸ iff.rfl ... ↔ of_int a ≤ of_int b : iff.rfl) theorem of_int_pos (a : ℤ) : (of_int a > 0) ↔ (#int a > 0) := !of_int_lt_of_int theorem of_int_nonneg (a : ℤ) : (of_int a ≥ 0) ↔ (#int a ≥ 0) := !of_int_le_of_int theorem of_nat_lt_of_nat (a b : ℕ) : of_nat a < of_nat b ↔ (#nat a < b) := by rewrite [*of_nat_eq, propext !of_int_lt_of_int]; apply int.of_nat_lt_of_nat theorem of_nat_le_of_nat (a b : ℕ) : of_nat a ≤ of_nat b ↔ (#nat a ≤ b) := by rewrite [*of_nat_eq, propext !of_int_le_of_int]; apply int.of_nat_le_of_nat theorem of_nat_pos (a : ℕ) : (of_nat a > 0) ↔ (#nat a > nat.zero) := !of_nat_lt_of_nat theorem of_nat_nonneg (a : ℕ) : (of_nat a ≥ 0) := iff.mpr !of_nat_le_of_nat !nat.zero_le theorem le.refl (a : ℚ) : a ≤ a := by rewrite [↑rat.le, sub_self]; apply nonneg_zero theorem le.trans (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c := assert H3 : nonneg (c - b + (b - a)), from nonneg_add H2 H1, begin revert H3, rewrite [↑rat.sub, add.assoc, neg_add_cancel_left], intro H3, apply H3 end theorem le.antisymm (H1 : a ≤ b) (H2 : b ≤ a) : a = b := have H3 : nonneg (-(a - b)), from !neg_sub⁻¹ ▸ H1, have H4 : a - b = 0, from nonneg_antisymm H2 H3, eq_of_sub_eq_zero H4 theorem le.total (a b : ℚ) : a ≤ b ∨ b ≤ a := or.elim (nonneg_total (b - a)) (assume H, or.inl H) (assume H, or.inr (!neg_sub ▸ H)) theorem le.by_cases {P : Prop} (a b : ℚ) (H : a ≤ b → P) (H2 : b ≤ a → P) : P := or.elim (!rat.le.total) H H2 theorem lt_iff_le_and_ne (a b : ℚ) : a < b ↔ a ≤ b ∧ a ≠ b := iff.intro (assume H : a < b, have b - a ≠ 0, from ne_zero_of_pos H, have a ≠ b, from ne.symm (assume H', this (H' ▸ !sub_self)), and.intro (nonneg_of_pos H) this) (assume H : a ≤ b ∧ a ≠ b, obtain aleb aneb, from H, have b - a ≠ 0, from (assume H', aneb (eq_of_sub_eq_zero H')⁻¹), pos_of_nonneg_of_ne_zero aleb this) theorem le_iff_lt_or_eq (a b : ℚ) : a ≤ b ↔ a < b ∨ a = b := iff.intro (assume h : a ≤ b, decidable.by_cases (suppose a = b, or.inr this) (suppose a ≠ b, or.inl (iff.mpr !lt_iff_le_and_ne (and.intro h this)))) (suppose a < b ∨ a = b, or.elim this (suppose a < b, and.left (iff.mp !lt_iff_le_and_ne this)) (suppose a = b, this ▸ !le.refl)) private theorem to_nonneg : a ≥ 0 → nonneg a := by intros; rewrite -sub_zero; eassumption theorem add_le_add_left (H : a ≤ b) (c : ℚ) : c + a ≤ c + b := have c + b - (c + a) = b - a, by rewrite [↑sub, neg_add, -add.assoc, add.comm c, add_neg_cancel_right], show nonneg (c + b - (c + a)), from this⁻¹ ▸ H theorem mul_nonneg (H1 : a ≥ (0 : ℚ)) (H2 : b ≥ (0 : ℚ)) : a * b ≥ (0 : ℚ) := have nonneg (a * b), from nonneg_mul (to_nonneg H1) (to_nonneg H2), !sub_zero⁻¹ ▸ this private theorem to_pos : a > 0 → pos a := by intros; rewrite -sub_zero; eassumption theorem mul_pos (H1 : a > (0 : ℚ)) (H2 : b > (0 : ℚ)) : a * b > (0 : ℚ) := have pos (a * b), from pos_mul (to_pos H1) (to_pos H2), !sub_zero⁻¹ ▸ this definition decidable_lt [instance] : decidable_rel rat.lt := take a b, decidable_pos (b - a) theorem le_of_lt (H : a < b) : a ≤ b := iff.mpr !le_iff_lt_or_eq (or.inl H) theorem lt_irrefl (a : ℚ) : ¬ a < a := take Ha, let Hand := (iff.mp !lt_iff_le_and_ne) Ha in (and.right Hand) rfl theorem not_le_of_gt (H : a < b) : ¬ b ≤ a := assume Hba, let Heq := le.antisymm (le_of_lt H) Hba in !lt_irrefl (Heq ▸ H) theorem lt_of_lt_of_le (Hab : a < b) (Hbc : b ≤ c) : a < c := let Hab' := le_of_lt Hab in let Hac := le.trans Hab' Hbc in (iff.mpr !lt_iff_le_and_ne) (and.intro Hac (assume Heq, not_le_of_gt (Heq ▸ Hab) Hbc)) theorem lt_of_le_of_lt (Hab : a ≤ b) (Hbc : b < c) : a < c := let Hbc' := le_of_lt Hbc in let Hac := le.trans Hab Hbc' in (iff.mpr !lt_iff_le_and_ne) (and.intro Hac (assume Heq, not_le_of_gt (Heq⁻¹ ▸ Hbc) Hab)) theorem zero_lt_one : (0 : ℚ) < 1 := trivial theorem add_lt_add_left (H : a < b) (c : ℚ) : c + a < c + b := let H' := le_of_lt H in (iff.mpr (lt_iff_le_and_ne _ _)) (and.intro (add_le_add_left H' _) (take Heq, let Heq' := add_left_cancel Heq in !lt_irrefl (Heq' ▸ H))) section migrate_algebra open [classes] algebra protected definition discrete_linear_ordered_field [reducible] : algebra.discrete_linear_ordered_field rat := ⦃algebra.discrete_linear_ordered_field, rat.discrete_field, le_refl := le.refl, le_trans := @le.trans, le_antisymm := @le.antisymm, le_total := @le.total, le_of_lt := @le_of_lt, lt_irrefl := lt_irrefl, lt_of_lt_of_le := @lt_of_lt_of_le, lt_of_le_of_lt := @lt_of_le_of_lt, le_iff_lt_or_eq := @le_iff_lt_or_eq, add_le_add_left := @add_le_add_left, mul_nonneg := @mul_nonneg, mul_pos := @mul_pos, decidable_lt := @decidable_lt, zero_lt_one := zero_lt_one, add_lt_add_left := @add_lt_add_left⦄ local attribute rat.discrete_linear_ordered_field [trans-instance] local attribute rat.discrete_field [instance] definition min : ℚ → ℚ → ℚ := algebra.min definition max : ℚ → ℚ → ℚ := algebra.max definition abs : ℚ → ℚ := algebra.abs definition sign : ℚ → ℚ := algebra.sign migrate from algebra with rat replacing sub → sub, dvd → dvd, has_le.ge → ge, has_lt.gt → gt, divide → divide, max → max, min → min, abs → abs, sign → sign, nmul → nmul, imul → imul attribute le.trans lt.trans lt_of_lt_of_le lt_of_le_of_lt ge.trans gt.trans gt_of_gt_of_ge gt_of_ge_of_gt [trans] end migrate_algebra theorem rat_of_nat_abs (a : ℤ) : abs (of_int a) = of_nat (int.nat_abs a) := assert ∀ n : ℕ, of_int (int.neg_succ_of_nat n) = - of_nat (nat.succ n), from λ n, rfl, int.induction_on a (take b, abs_of_nonneg (!of_nat_nonneg)) (take b, by rewrite [this, abs_neg, abs_of_nonneg (!of_nat_nonneg)]) section open int set_option pp.coercions true theorem num_nonneg_of_nonneg {q : ℚ} (H : q ≥ 0) : num q ≥ 0 := have of_int (num q) ≥ of_int 0, begin rewrite [-mul_denom], apply mul_nonneg H, rewrite [of_int_le_of_int], exact int.le_of_lt !denom_pos end, show num q ≥ 0, from iff.mp !of_int_le_of_int this theorem num_pos_of_pos {q : ℚ} (H : q > 0) : num q > 0 := have of_int (num q) > of_int 0, begin rewrite [-mul_denom], apply mul_pos H, rewrite [of_int_lt_of_int], exact !denom_pos end, show num q > 0, from iff.mp !of_int_lt_of_int this theorem num_neg_of_neg {q : ℚ} (H : q < 0) : num q < 0 := have of_int (num q) < of_int 0, begin rewrite [-mul_denom], apply mul_neg_of_neg_of_pos H, rewrite [of_int_lt_of_int], exact !denom_pos end, show num q < 0, from iff.mp !of_int_lt_of_int this theorem num_nonpos_of_nonpos {q : ℚ} (H : q ≤ 0) : num q ≤ 0 := have of_int (num q) ≤ of_int 0, begin rewrite [-mul_denom], apply mul_nonpos_of_nonpos_of_nonneg H, rewrite [of_int_le_of_int], exact int.le_of_lt !denom_pos end, show num q ≤ 0, from iff.mp !of_int_le_of_int this end definition ubound : ℚ → ℕ := λ a : ℚ, nat.succ (int.nat_abs (num a)) theorem ubound_ge (a : ℚ) : of_nat (ubound a) ≥ a := have h : abs a * abs (of_int (denom a)) = abs (of_int (num a)), from !abs_mul ▸ !mul_denom ▸ rfl, assert of_int (denom a) > 0, from (iff.mpr !of_int_pos) !denom_pos, have 1 ≤ abs (of_int (denom a)), begin rewrite (abs_of_pos this), apply iff.mpr !of_int_le_of_int, apply denom_pos end, have abs a ≤ abs (of_int (num a)), from le_of_mul_le_of_ge_one (h ▸ !le.refl) !abs_nonneg this, calc a ≤ abs a : le_abs_self ... ≤ abs (of_int (num a)) : this ... ≤ abs (of_int (num a)) + 1 : rat.le_add_of_nonneg_right trivial ... = of_nat (int.nat_abs (num a)) + 1 : rat_of_nat_abs ... = of_nat (nat.succ (int.nat_abs (num a))) : of_nat_add theorem ubound_pos (a : ℚ) : nat.gt (ubound a) nat.zero := !nat.succ_pos end rat
15711e114f40f258bf858bc3a59444c3466ac82b
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Compiler/InitAttr.lean
6bdd5d1611681db1899810e116c4390eeef2ca95
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
5,969
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.Elab.InfoTree.Main namespace Lean private def getIOTypeArg : Expr → Option Expr | Expr.app (Expr.const `IO _) arg => some arg | _ => none private def isUnitType : Expr → Bool | Expr.const `Unit _ => true | _ => false private def isIOUnit (type : Expr) : Bool := match getIOTypeArg type with | some type => isUnitType type | _ => false /-- Run the initializer of the given module (without `builtin_initialize` commands). Return `false` if the initializer is not available as native code. Initializers do not have corresponding Lean definitions, so they cannot be interpreted in this case. -/ @[extern "lean_run_mod_init"] unsafe opaque runModInit (mod : Name) : IO Bool /-- Run the initializer for `decl` and store its value for global access. Should only be used while importing. -/ @[extern "lean_run_init"] unsafe opaque runInit (env : @& Environment) (opts : @& Options) (decl initDecl : @& Name) : IO Unit unsafe def registerInitAttrUnsafe (attrName : Name) (runAfterImport : Bool) (ref : Name) : IO (ParametricAttribute Name) := registerParametricAttribute { ref := ref name := attrName descr := "initialization procedure for global references" getParam := fun declName stx => do let decl ← getConstInfo declName match (← Attribute.Builtin.getIdent? stx) with | some initFnName => let initFnName ← Elab.resolveGlobalConstNoOverloadWithInfo initFnName let initDecl ← getConstInfo initFnName match getIOTypeArg initDecl.type with | none => throwError "initialization function '{initFnName}' must have type of the form `IO <type>`" | some initTypeArg => if decl.type == initTypeArg then pure initFnName else throwError "initialization function '{initFnName}' type mismatch" | none => if isIOUnit decl.type then pure Name.anonymous else throwError "initialization function must have type `IO Unit`" afterImport := fun entries => do let ctx ← read if runAfterImport && (← isInitializerExecutionEnabled) then for mod in ctx.env.header.moduleNames, modEntries in entries do -- any native Lean code reachable by the interpreter (i.e. from shared -- libraries with their corresponding module in the Environment) must -- first be initialized if !(← runModInit mod) then -- If no native code for the module is available, run `[init]` decls manually. -- All other constants (nullary functions) are lazily initialized by the interpreter. for (decl, initDecl) in modEntries do if initDecl.isAnonymous then let initFn ← IO.ofExcept <| ctx.env.evalConst (IO Unit) ctx.opts decl initFn else runInit ctx.env ctx.opts decl initDecl } @[implemented_by registerInitAttrUnsafe] private opaque registerInitAttrInner (attrName : Name) (runAfterImport : Bool) (ref : Name) : IO (ParametricAttribute Name) @[inline] def registerInitAttr (attrName : Name) (runAfterImport : Bool) (ref : Name := by exact decl_name%) : IO (ParametricAttribute Name) := registerInitAttrInner attrName runAfterImport ref builtin_initialize regularInitAttr : ParametricAttribute Name ← registerInitAttr `init true builtin_initialize builtinInitAttr : ParametricAttribute Name ← registerInitAttr `builtin_init false def getInitFnNameForCore? (env : Environment) (attr : ParametricAttribute Name) (fn : Name) : Option Name := match attr.getParam? env fn with | some Name.anonymous => none | some n => some n | _ => none @[export lean_get_builtin_init_fn_name_for] def getBuiltinInitFnNameFor? (env : Environment) (fn : Name) : Option Name := getInitFnNameForCore? env builtinInitAttr fn @[export lean_get_regular_init_fn_name_for] def getRegularInitFnNameFor? (env : Environment) (fn : Name) : Option Name := getInitFnNameForCore? env regularInitAttr fn @[export lean_get_init_fn_name_for] def getInitFnNameFor? (env : Environment) (fn : Name) : Option Name := getBuiltinInitFnNameFor? env fn <|> getRegularInitFnNameFor? env fn def isIOUnitInitFnCore (env : Environment) (attr : ParametricAttribute Name) (fn : Name) : Bool := match attr.getParam? env fn with | some Name.anonymous => true | _ => false @[export lean_is_io_unit_regular_init_fn] def isIOUnitRegularInitFn (env : Environment) (fn : Name) : Bool := isIOUnitInitFnCore env regularInitAttr fn @[export lean_is_io_unit_builtin_init_fn] def isIOUnitBuiltinInitFn (env : Environment) (fn : Name) : Bool := isIOUnitInitFnCore env builtinInitAttr fn def isIOUnitInitFn (env : Environment) (fn : Name) : Bool := isIOUnitBuiltinInitFn env fn || isIOUnitRegularInitFn env fn def hasInitAttr (env : Environment) (fn : Name) : Bool := (getInitFnNameFor? env fn).isSome def setBuiltinInitAttr (env : Environment) (declName : Name) (initFnName : Name := Name.anonymous) : Except String Environment := builtinInitAttr.setParam env declName initFnName def declareBuiltin (forDecl : Name) (value : Expr) : CoreM Unit := do let name := `_regBuiltin ++ forDecl let type := mkApp (mkConst `IO) (mkConst `Unit) let decl := Declaration.defnDecl { name, levelParams := [], type, value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } match (← getEnv).addAndCompile {} decl with -- TODO: pretty print error | Except.error e => do let msg ← (e.toMessageData {}).toString throwError "failed to emit registration code for builtin '{forDecl}': {msg}" | Except.ok env => IO.ofExcept (setBuiltinInitAttr env name) >>= setEnv end Lean
1d192e65b94fc6fcc48ff38232ce73388dfe9761
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/algebra/char_zero.lean
1f642f2a7a0d6e3cb155ca45c833f0572f75029b
[ "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
3,329
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import algebra.field import data.nat.cast import tactic.wlog /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) -/ class char_zero (α : Type*) [add_monoid α] [has_one α] : Prop := (cast_injective : function.injective (coe : ℕ → α)) theorem char_zero_of_inj_zero {α : Type*} [add_monoid α] [has_one α] (add_left_cancel : ∀ a b c : α, a + b = a + c → b = c) (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := ⟨λ m n, begin assume h, wlog hle : m ≤ n, cases nat.le.dest hle with k e, suffices : k = 0, by rw [← e, this, add_zero], apply H, apply add_left_cancel n, rw [← h, ← nat.cast_add, e, add_zero, h] end⟩ -- We have no `left_cancel_add_monoid`, so we restate it for `add_group` -- and `ordered_cancel_comm_monoid`. theorem add_group.char_zero_of_inj_zero {α : Type*} [add_group α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H theorem ordered_cancel_comm_monoid.char_zero_of_inj_zero {α : Type*} [ordered_cancel_add_comm_monoid α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_char_zero {α : Type*} [linear_ordered_semiring α] : char_zero α := ordered_cancel_comm_monoid.char_zero_of_inj_zero $ λ n h, nat.eq_zero_of_le_zero $ (@nat.cast_le α _ _ _).1 (le_of_eq h) namespace nat variables {α : Type*} [add_monoid α] [has_one α] [char_zero α] theorem cast_injective : function.injective (coe : ℕ → α) := char_zero.cast_injective @[simp, norm_cast] theorem cast_inj {m n : ℕ} : (m : α) = n ↔ m = n := cast_injective.eq_iff @[simp, norm_cast] theorem cast_eq_zero {n : ℕ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[norm_cast] theorem cast_ne_zero {n : ℕ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero lemma cast_add_one_ne_zero (n : ℕ) : (n + 1 : α) ≠ 0 := by exact_mod_cast n.succ_ne_zero end nat @[field_simps] lemma two_ne_zero' {α : Type*} [add_monoid α] [has_one α] [char_zero α] : (2:α) ≠ 0 := have ((2:ℕ):α) ≠ 0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_succ, nat.cast_one] at this section variables {α : Type*} [semiring α] [no_zero_divisors α] [char_zero α] lemma add_self_eq_zero {a : α} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] lemma bit0_eq_zero {a : α} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero end section variables {α : Type*} [division_ring α] [char_zero α] @[simp] lemma half_add_self (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : α) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : α) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : α) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end
632eacb34e1701e5e2303bbcf3102d12e6f74ba8
4727251e0cd73359b15b664c3170e5d754078599
/src/data/real/basic.lean
67fcb79ca3e817a98c4c0631baf84b81acb65655
[ "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
24,163
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import algebra.module.basic import algebra.bounds import algebra.order.archimedean import algebra.star.basic import data.real.cau_seq_completion import order.conditionally_complete_lattice /-! # Real numbers from Cauchy sequences This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers. This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply lifting everything to `ℚ`. -/ open_locale pointwise /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ lemma of_cauchy_zero : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma of_cauchy_one : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma of_cauchy_add (a b) : (⟨a + b⟩ : ℝ) = ⟨a⟩ + ⟨b⟩ := show _ = add _ _, by rw add lemma of_cauchy_neg (a) : (⟨-a⟩ : ℝ) = -⟨a⟩ := show _ = neg _, by rw neg lemma of_cauchy_mul (a b) : (⟨a * b⟩ : ℝ) = ⟨a⟩ * ⟨b⟩ := show _ = mul _ _, by rw mul lemma cauchy_zero : (0 : ℝ).cauchy = 0 := show zero.cauchy = 0, by rw zero lemma cauchy_one : (1 : ℝ).cauchy = 1 := show one.cauchy = 1, by rw one lemma cauchy_add : ∀ a b, (a + b : ℝ).cauchy = a.cauchy + b.cauchy | ⟨a⟩ ⟨b⟩ := show (add _ _).cauchy = _, by rw add lemma cauchy_neg : ∀ a, (-a : ℝ).cauchy = -a.cauchy | ⟨a⟩ := show (neg _).cauchy = _, by rw neg lemma cauchy_mul : ∀ a b, (a * b : ℝ).cauchy = a.cauchy * b.cauchy | ⟨a⟩ ⟨b⟩ := show (mul _ _).cauchy = _, by rw mul instance : comm_ring ℝ := begin refine_struct { zero := (0 : ℝ), one := (1 : ℝ), mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := λ a b, a + (-b), npow := @npow_rec ℝ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec ℝ ⟨0⟩ ⟨(+)⟩, zsmul := @zsmul_rec ℝ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩ }; repeat { rintro ⟨_⟩, }; try { refl }; simp [← of_cauchy_zero, ← of_cauchy_one, ←of_cauchy_add, ←of_cauchy_neg, ←of_cauchy_mul]; apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip end /-! Extra instances to short-circuit type class resolution. These short-circuits have an additional property of ensuring that a computable path is found; if `field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable` version of them. -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : comm_monoid_with_zero ℝ := by apply_instance instance : monoid_with_zero ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : has_sub ℝ := by apply_instance instance : module ℝ ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : star_ring ℝ := star_ring_of_comm instance : has_trivial_star ℝ := ⟨λ _, rfl⟩ /-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this is `cau_seq.completion.of_rat`, not `rat.cast`. -/ def of_rat : ℚ →+* ℝ := by refine_struct { to_fun := of_cauchy ∘ of_rat }; simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add, of_cauchy_one, of_cauchy_zero, ← of_cauchy_mul, ← of_cauchy_add] lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨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))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← of_cauchy_zero; refl lemma mk_one : mk 1 = 1 := by rw ← of_cauchy_one; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, ←of_cauchy_add] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, ←of_cauchy_mul] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, ←of_cauchy_neg] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert of_rat_lt.2 zero_lt_one; simp protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : ordered_comm_ring ℝ := { add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : ordered_ring ℝ := by apply_instance instance : ordered_semiring ℝ := by apply_instance instance : ordered_add_comm_group ℝ := by apply_instance instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance instance : ordered_add_comm_monoid ℝ := by apply_instance instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩ open_locale classical noncomputable instance : linear_order ℝ := { le_total := begin intros a b, induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa using le_total a b, end, decidable_le := by apply_instance, .. real.partial_order } noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : is_domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.is_domain } @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma of_cauchy_inv {f} : (⟨f⁻¹⟩ : ℝ) = ⟨f⟩⁻¹ := show _ = inv' _, by rw inv' lemma cauchy_inv : ∀ f, (f⁻¹ : ℝ).cauchy = f.cauchy⁻¹ | ⟨f⟩ := show (inv' _).cauchy = _, by rw inv' noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [←of_cauchy_inv, ←of_cauchy_mul, ← of_cauchy_one, ← of_cauchy_zero, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← of_cauchy_zero, ←of_cauchy_inv], ..real.linear_ordered_comm_ring, } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : distrib_lattice ℝ := by apply_instance noncomputable instance : lattice ℝ := by apply_instance noncomputable instance : semilattice_inf ℝ := by apply_instance noncomputable instance : semilattice_sup ℝ := by apply_instance noncomputable instance : has_inf ℝ := by apply_instance noncomputable instance : has_sup ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := of_rat.eq_rat_cast theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ le_rfl).1, rw ← of_rat_eq_cast, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ le_rfl).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 : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| ≤ ε) : |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, real.ind_mk 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, |(f j : ℝ) - x| < ε) : ∃ h', real.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_is_lub (S : set ℝ) (hne : S.nonempty) (hbdd : bdd_above S) : ∃ x, is_lub S x := begin rcases ⟨hne, hbdd⟩ with ⟨⟨L, hL⟩, ⟨U, hU⟩⟩, have : ∀ d : ℕ, bdd_above {m : ℤ | ∃ y ∈ S, (m : ℝ) ≤ y * d}, { cases exists_int_gt U with k hk, refine λ d, ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (hy.trans _), push_cast, exact mul_le_mul_of_nonneg_right ((hU yS).trans hk.le) d.cast_nonneg }, choose f hf using λ d : ℕ, int.exists_greatest_of_bdd (this d) ⟨⌊L * d⌋, L, hL, int.floor_le _⟩, 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 := (int.sub_one_lt_floor _).trans_le (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, int.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) }, have hg : is_cau_seq abs (λ n, f n / n : ℕ → ℚ), { intros ε ε0, suffices : ∀ j k ≥ ⌈ε⁻¹⌉₊, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ ij _ le_rfl⟩⟩, rw [neg_lt, neg_sub], exact this _ le_rfl _ ij }, intros j ij k ik, replace ij := le_trans (nat.le_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (nat.le_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 ((inv_pos.2 ε0).trans_le ij), have k0 := nat.cast_pos.1 ((inv_pos.2 ε0).trans_le 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) }, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, ⟨λ x xS, _, λ y 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 := hK.le.trans (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 ((inv_pos.2 xz).trans_le hK), refine le_trans _ (hf₂ _ n0 _ xS).le, 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)⟩ } end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : S.nonempty ∧ bdd_above S then classical.some (exists_is_lub S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : S.nonempty ∧ bdd_above S then classical.some (exists_is_lub S h.1 h.2) else 0 := rfl protected theorem is_lub_Sup (S : set ℝ) (h₁ : S.nonempty) (h₂ : bdd_above S) : is_lub S (Sup S) := by { simp only [Sup_def, dif_pos (and.intro h₁ h₂)], apply classical.some_spec } noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup (-S)⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup (-S) := rfl protected theorem is_glb_Inf (S : set ℝ) (h₁ : S.nonempty) (h₂ : bdd_below S) : is_glb S (Inf S) := begin rw [Inf_def, ← is_lub_neg', neg_neg], exact real.is_lub_Sup _ h₁.neg h₂.neg end noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := λ s a hs ha, (real.is_lub_Sup s ⟨a, ha⟩ hs).1 ha, cSup_le := λ s a hs ha, (real.is_lub_Sup s hs ⟨a, ha⟩).2 ha, cInf_le := λ s a hs ha, (real.is_glb_Inf s ⟨a, ha⟩ hs).1 ha, le_cInf := λ s a hs ha, (real.is_glb_Inf s hs ⟨a, ha⟩).2 ha, ..real.linear_order, ..real.lattice} lemma lt_Inf_add_pos {s : set ℝ} (h : s.nonempty) {ε : ℝ} (hε : 0 < ε) : ∃ a ∈ s, a < Inf s + ε := exists_lt_of_cInf_lt h $ lt_add_of_pos_right _ hε lemma add_neg_lt_Sup {s : set ℝ} (h : s.nonempty) {ε : ℝ} (hε : ε < 0) : ∃ a ∈ s, Sup s + ε < a := exists_lt_of_lt_cSup h $ add_lt_iff_neg_left.2 hε lemma Inf_le_iff {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {a : ℝ} : Inf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε := begin rw le_iff_forall_pos_lt_add, split; intros H ε ε_pos, { exact exists_lt_of_cInf_lt h' (H ε ε_pos) }, { rcases H ε ε_pos with ⟨x, x_in, hx⟩, exact cInf_lt_of_lt h x_in hx } end lemma le_Sup_iff {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {a : ℝ} : a ≤ Sup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x := begin rw le_iff_forall_pos_lt_add, refine ⟨λ H ε ε_neg, _, λ H ε ε_pos, _⟩, { exact exists_lt_of_lt_cSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) }, { rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩, exact sub_lt_iff_lt_add.mp (lt_cSup_of_lt h x_in hx) } end @[simp] theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp lemma csupr_empty {α : Sort*} [is_empty α] (f : α → ℝ) : (⨆ i, f i) = 0 := begin dsimp [supr], convert real.Sup_empty, rw set.range_eq_empty_iff, apply_instance end @[simp] lemma csupr_const_zero {α : Sort*} : (⨆ i : α, (0:ℝ)) = 0 := begin casesI is_empty_or_nonempty α, { exact real.csupr_empty _ }, { exact csupr_const }, end theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) @[simp] theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] lemma cinfi_empty {α : Sort*} [is_empty α] (f : α → ℝ) : (⨅ i, f i) = 0 := begin dsimp [infi], convert real.Inf_empty, rw set.range_eq_empty_iff, apply_instance end @[simp] lemma cinfi_const_zero {α : Sort*} : (⨅ i : α, (0:ℝ)) = 0 := begin casesI is_empty_or_nonempty α, { exact real.cinfi_empty _ }, { exact cinfi_const }, end theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := neg_eq_zero.2 $ Sup_of_not_bdd_above $ mt bdd_above_neg.1 hs /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { exact Sup_empty.ge }, { apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) } end /-- As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is bounded above by `0` to show that `Sup S ≤ 0`. -/ lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, exacts [Sup_empty.le, cSup_le hS₂ hS], end /-- As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, exacts [Inf_empty.ge, le_cInf hS₂ hS] end /-- As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`. -/ lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { exact Inf_empty.le }, { apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) } end lemma Inf_le_Sup (s : set ℝ) (h₁ : bdd_below s) (h₂ : bdd_above s) : Inf s ≤ Sup s := begin rcases s.eq_empty_or_nonempty with rfl | hne, { rw [Inf_empty, Sup_empty] }, { exact cInf_le_cSup h₁ h₂ hne } end 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 (cSup_le lb (ub' _ _)).not_lt (sub_lt_self _ (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 (le_cSup ub _).not_lt ((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 instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real
750c61d623cf6db075a97d0e6c16f95eb0d640c8
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/nat/dist.lean
7f65f03e9e077a6991de44c81bb3ce7f863dbd71
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
3,964
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad Distance function on the natural numbers. -/ import data.nat.basic namespace nat /- distance -/ /-- Distance (absolute value of difference) between natural numbers. -/ def dist (n m : ℕ) := (n - m) + (m - n) theorem dist.def (n m : ℕ) : dist n m = (n - m) + (m - n) := rfl @[simp] theorem dist_comm (n m : ℕ) : dist n m = dist m n := by simp [dist.def] @[simp] theorem dist_self (n : ℕ) : dist n n = 0 := by simp [dist.def, nat.sub_self] theorem eq_of_dist_eq_zero {n m : ℕ} (h : dist n m = 0) : n = m := have n - m = 0, from eq_zero_of_add_eq_zero_right h, have n ≤ m, from nat.le_of_sub_eq_zero this, have m - n = 0, from eq_zero_of_add_eq_zero_left h, have m ≤ n, from nat.le_of_sub_eq_zero this, le_antisymm ‹n ≤ m› ‹m ≤ n› theorem dist_eq_zero {n m : ℕ} (h : n = m) : dist n m = 0 := begin rw [h, dist_self] end theorem dist_eq_sub_of_le {n m : ℕ} (h : n ≤ m) : dist n m = m - n := begin rw [dist.def, sub_eq_zero_of_le h, zero_add] end theorem dist_eq_sub_of_ge {n m : ℕ} (h : n ≥ m) : dist n m = n - m := begin rw [dist_comm], apply dist_eq_sub_of_le h end theorem dist_zero_right (n : ℕ) : dist n 0 = n := eq.trans (dist_eq_sub_of_ge (zero_le n)) (nat.sub_zero n) theorem dist_zero_left (n : ℕ) : dist 0 n = n := eq.trans (dist_eq_sub_of_le (zero_le n)) (nat.sub_zero n) theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n + k) - (m + k)) + ((m + k)-(n + k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : by rw nat.add_sub_add_right ... = (n - m) + (m - n) : by rw nat.add_sub_add_right theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := begin rw [add_comm k n, add_comm k m], apply dist_add_add_right end theorem dist_eq_intro {n m k l : ℕ} (h : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : by rw dist_add_add_right ... = dist (k + l) (k + m) : by rw h ... = dist l m : by rw dist_add_add_left protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := or.elim (le_total k m) (assume : k ≤ m, begin rw ←nat.add_sub_assoc this, apply nat.sub_le_sub_right, apply nat.le_sub_add end) (assume : k ≥ m, begin rw [sub_eq_zero_of_le this, add_zero], apply nat.sub_le_sub_left, exact this end) theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have dist n m + dist m k = (n - m) + (m - k) + ((k - m) + (m - n)), by simp [dist.def], begin rw [this, dist.def], apply add_le_add, repeat { apply nat.sub_lt_sub_add_sub } end theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := by rw [dist.def, dist.def, right_distrib, nat.mul_sub_right_distrib, nat.mul_sub_right_distrib] theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm] -- TODO(Jeremy): do when we have max and minx --theorem dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j := --sorry /- or.elim (lt_or_ge i j) (assume : i < j, by rw [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this]) (assume : i ≥ j, by rw [max_eq_left this , min_eq_right this, dist_eq_sub_of_ge this]) -/ theorem dist_succ_succ {i j : nat} : dist (succ i) (succ j) = dist i j := by simp [dist.def, succ_sub_succ] theorem dist_pos_of_ne {i j : nat} : i ≠ j → dist i j > 0 := assume hne, nat.lt_by_cases (assume : i < j, begin rw [dist_eq_sub_of_le (le_of_lt this)], apply nat.sub_pos_of_lt this end) (assume : i = j, by contradiction) (assume : i > j, begin rw [dist_eq_sub_of_ge (le_of_lt this)], apply nat.sub_pos_of_lt this end) end nat
65a49e079d7b8d46e9a367e8b8846283f3dfb288
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/well_founded_set.lean
4fa757296032f6e57405d79dc570d2f94996fe55
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
29,860
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.antichain import order.order_iso_nat import order.well_founded import tactic.tfae /-! # Well-founded sets A well-founded subset of an ordered type is one on which the relation `<` is well-founded. ## Main Definitions * `set.well_founded_on s r` indicates that the relation `r` is well-founded when restricted to the set `s`. * `set.is_wf s` indicates that `<` is well-founded when restricted to `s`. * `set.partially_well_ordered_on s r` indicates that the relation `r` is partially well-ordered (also known as well quasi-ordered) when restricted to the set `s`. * `set.is_pwo s` indicates that any infinite sequence of elements in `s` contains an infinite monotone subsequence. Note that this is equivalent to containing only two comparable elements. ## Main Results * Higman's Lemma, `set.partially_well_ordered_on.partially_well_ordered_on_sublist_forall₂`, shows that if `r` is partially well-ordered on `s`, then `list.sublist_forall₂` is partially well-ordered on the set of lists of elements of `s`. The result was originally published by Higman, but this proof more closely follows Nash-Williams. * `set.well_founded_on_iff` relates `well_founded_on` to the well-foundedness of a relation on the original type, to avoid dealing with subtypes. * `set.is_wf.mono` shows that a subset of a well-founded subset is well-founded. * `set.is_wf.union` shows that the union of two well-founded subsets is well-founded. * `finset.is_wf` shows that all `finset`s are well-founded. ## TODO Prove that `s` is partial well ordered iff it has no infinite descending chain or antichain. ## References * [Higman, *Ordering by Divisibility in Abstract Algebras*][Higman52] * [Nash-Williams, *On Well-Quasi-Ordering Finite Trees*][Nash-Williams63] -/ variables {ι α β : Type*} namespace set /-! ### Relations well-founded on sets -/ /-- `s.well_founded_on r` indicates that the relation `r` is well-founded when restricted to `s`. -/ def well_founded_on (s : set α) (r : α → α → Prop) : Prop := well_founded $ λ a b : s, r a b @[simp] lemma well_founded_on_empty (r : α → α → Prop) : well_founded_on ∅ r := well_founded_of_empty _ section well_founded_on variables {r r' : α → α → Prop} section any_rel variables {s t : set α} {x y : α} lemma well_founded_on_iff : s.well_founded_on r ↔ well_founded (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := begin have f : rel_embedding (λ (a : s) (b : s), r a b) (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := ⟨⟨coe, subtype.coe_injective⟩, λ a b, by simp⟩, refine ⟨λ h, _, f.well_founded⟩, rw well_founded.well_founded_iff_has_min, intros t ht, by_cases hst : (s ∩ t).nonempty, { rw ← subtype.preimage_coe_nonempty at hst, rcases h.has_min (coe ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hm ⟨x, xs⟩ xt xm⟩ }, { rcases ht with ⟨m, mt⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hst ⟨m, ⟨ms, mt⟩⟩⟩ } end namespace well_founded_on protected lemma induction (hs : s.well_founded_on r) (hx : x ∈ s) {P : α → Prop} (hP : ∀ y ∈ s, (∀ z ∈ s, r z y → P z) → P y) : P x := begin let Q : s → Prop := λ y, P y, change Q ⟨x, hx⟩, refine well_founded.induction hs ⟨x, hx⟩ _, simpa only [subtype.forall] end protected lemma mono (h : t.well_founded_on r') (hle : r ≤ r') (hst : s ⊆ t) : s.well_founded_on r := begin rw well_founded_on_iff at *, refine subrelation.wf (λ x y xy, _) h, exact ⟨hle _ _ xy.1, hst xy.2.1, hst xy.2.2⟩ end lemma subset (h : t.well_founded_on r) (hst : s ⊆ t) : s.well_founded_on r := h.mono le_rfl hst open relation /-- `a` is accessible under the relation `r` iff `r` is well-founded on the downward transitive closure of `a` under `r` (including `a` or not). -/ lemma acc_iff_well_founded_on {α} {r : α → α → Prop} {a : α} : [ acc r a, {b | refl_trans_gen r b a}.well_founded_on r, {b | trans_gen r b a}.well_founded_on r ].tfae := begin tfae_have : 1 → 2, { refine λ h, ⟨λ b, _⟩, apply inv_image.accessible, rw ← acc_trans_gen_iff at h ⊢, obtain h'|h' := refl_trans_gen_iff_eq_or_trans_gen.1 b.2, { rwa h' at h }, { exact h.inv h' } }, tfae_have : 2 → 3, { exact λ h, h.subset (λ _, trans_gen.to_refl) }, tfae_have : 3 → 1, { refine λ h, acc.intro _ (λ b hb, (h.apply ⟨b, trans_gen.single hb⟩).of_fibration subtype.val _), exact λ ⟨c, hc⟩ d h, ⟨⟨d, trans_gen.head h hc⟩, h, rfl⟩ }, tfae_finish, end end well_founded_on end any_rel section is_strict_order variables [is_strict_order α r] {s t : set α} instance is_strict_order.subset : is_strict_order α (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ a con, irrefl_of r a con.1 ⟩, to_is_trans := ⟨λ a b c ab bc, ⟨trans_of r ab.1 bc.1, ab.2.1, bc.2.2⟩ ⟩ } lemma well_founded_on_iff_no_descending_seq : s.well_founded_on r ↔ ∀ (f : ((>) : ℕ → ℕ → Prop) ↪r r), ¬∀ n, f n ∈ s := begin simp only [well_founded_on_iff, rel_embedding.well_founded_iff_no_descending_seq, ← not_exists, ← not_nonempty_iff, not_iff_not], split, { rintro ⟨⟨f, hf⟩⟩, have H : ∀ n, f n ∈ s, from λ n, (hf.2 n.lt_succ_self).2.2, refine ⟨⟨f, _⟩, H⟩, simpa only [H, and_true] using @hf }, { rintro ⟨⟨f, hf⟩, hfs : ∀ n, f n ∈ s⟩, refine ⟨⟨f, _⟩⟩, simpa only [hfs, and_true] using @hf } end lemma well_founded_on.union (hs : s.well_founded_on r) (ht : t.well_founded_on r) : (s ∪ t).well_founded_on r := begin rw well_founded_on_iff_no_descending_seq at *, rintro f hf, rcases nat.exists_subseq_of_forall_mem_union f hf with ⟨g, hg|hg⟩, exacts [hs (g.dual.lt_embedding.trans f) hg, ht (g.dual.lt_embedding.trans f) hg] end @[simp] lemma well_founded_on_union : (s ∪ t).well_founded_on r ↔ s.well_founded_on r ∧ t.well_founded_on r := ⟨λ h, ⟨h.subset $ subset_union_left _ _, h.subset $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩ end is_strict_order end well_founded_on /-! ### Sets well-founded w.r.t. the strict inequality -/ section has_lt variables [has_lt α] {s t : set α} /-- `s.is_wf` indicates that `<` is well-founded when restricted to `s`. -/ def is_wf (s : set α) : Prop := well_founded_on s (<) @[simp] lemma is_wf_empty : is_wf (∅ : set α) := well_founded_of_empty _ lemma is_wf_univ_iff : is_wf (univ : set α) ↔ well_founded ((<) : α → α → Prop) := by simp [is_wf, well_founded_on_iff] theorem is_wf.mono (h : is_wf t) (st : s ⊆ t) : is_wf s := h.subset st end has_lt section preorder variables [preorder α] {s t : set α} {a : α} protected lemma is_wf.union (hs : is_wf s) (ht : is_wf t) : is_wf (s ∪ t) := hs.union ht @[simp] lemma is_wf_union : is_wf (s ∪ t) ↔ is_wf s ∧ is_wf t := well_founded_on_union end preorder section preorder variables [preorder α] {s t : set α} {a : α} theorem is_wf_iff_no_descending_seq : is_wf s ↔ ∀ f : ℕ → α, strict_anti f → ¬(∀ n, f (order_dual.to_dual n) ∈ s) := well_founded_on_iff_no_descending_seq.trans ⟨λ H f hf, H ⟨⟨f, hf.injective⟩, λ a b, hf.lt_iff_lt⟩, λ H f, H f (λ _ _, f.map_rel_iff.2)⟩ end preorder /-! ### Partially well-ordered sets A set is partially well-ordered by a relation `r` when any infinite sequence contains two elements where the first is related to the second by `r`. Equivalently, any antichain (see `is_antichain`) is finite, see `set.partially_well_ordered_on_iff_finite_antichains`. -/ /-- A subset is partially well-ordered by a relation `r` when any infinite sequence contains two elements where the first is related to the second by `r`. -/ def partially_well_ordered_on (s : set α) (r : α → α → Prop) : Prop := ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ m n : ℕ, m < n ∧ r (f m) (f n) section partially_well_ordered_on variables {r : α → α → Prop} {r' : β → β → Prop} {f : α → β} {s : set α} {t : set α} {a : α} lemma partially_well_ordered_on.mono (ht : t.partially_well_ordered_on r) (h : s ⊆ t) : s.partially_well_ordered_on r := λ f hf, ht f $ λ n, h $ hf n @[simp] lemma partially_well_ordered_on_empty (r : α → α → Prop) : partially_well_ordered_on ∅ r := λ f hf, (hf 0).elim lemma partially_well_ordered_on.union (hs : s.partially_well_ordered_on r) (ht : t.partially_well_ordered_on r) : (s ∪ t).partially_well_ordered_on r := begin rintro f hf, rcases nat.exists_subseq_of_forall_mem_union f hf with ⟨g, hgs|hgt⟩, { rcases hs _ hgs with ⟨m, n, hlt, hr⟩, exact ⟨g m, g n, g.strict_mono hlt, hr⟩ }, { rcases ht _ hgt with ⟨m, n, hlt, hr⟩, exact ⟨g m, g n, g.strict_mono hlt, hr⟩ } end @[simp] lemma partially_well_ordered_on_union : (s ∪ t).partially_well_ordered_on r ↔ s.partially_well_ordered_on r ∧ t.partially_well_ordered_on r := ⟨λ h, ⟨h.mono $ subset_union_left _ _, h.mono $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩ lemma partially_well_ordered_on.image_of_monotone_on (hs : s.partially_well_ordered_on r) (hf : ∀ (a₁ ∈ s) (a₂ ∈ s), r a₁ a₂ → r' (f a₁) (f a₂)) : (f '' s).partially_well_ordered_on r' := begin intros g' hg', choose g hgs heq using hg', obtain rfl : f ∘ g = g', from funext heq, obtain ⟨m, n, hlt, hmn⟩ := hs g hgs, exact ⟨m, n, hlt, hf _ (hgs m) _ (hgs n) hmn⟩ end lemma _root_.is_antichain.finite_of_partially_well_ordered_on (ha : is_antichain r s) (hp : s.partially_well_ordered_on r) : s.finite := begin refine finite_or_infinite.resolve_right (λ hi, _), obtain ⟨m, n, hmn, h⟩ := hp (λ n, hi.nat_embedding _ n) (λ n, (hi.nat_embedding _ n).2), exact hmn.ne ((hi.nat_embedding _).injective $ subtype.val_injective $ ha.eq (hi.nat_embedding _ m).2 (hi.nat_embedding _ n).2 h), end section is_refl variables [is_refl α r] protected lemma finite.partially_well_ordered_on (hs : s.finite) : s.partially_well_ordered_on r := begin intros f hf, obtain ⟨m, n, hmn, h⟩ := hs.exists_lt_map_eq_of_forall_mem hf, exact ⟨m, n, hmn, h.subst $ refl (f m)⟩, end lemma _root_.is_antichain.partially_well_ordered_on_iff (hs : is_antichain r s) : s.partially_well_ordered_on r ↔ s.finite := ⟨hs.finite_of_partially_well_ordered_on, finite.partially_well_ordered_on⟩ @[simp] lemma partially_well_ordered_on_singleton (a : α) : partially_well_ordered_on {a} r := (finite_singleton a).partially_well_ordered_on @[simp] lemma partially_well_ordered_on_insert : partially_well_ordered_on (insert a s) r ↔ partially_well_ordered_on s r := by simp only [← singleton_union, partially_well_ordered_on_union, partially_well_ordered_on_singleton, true_and] protected lemma partially_well_ordered_on.insert (h : partially_well_ordered_on s r) (a : α) : partially_well_ordered_on (insert a s) r := partially_well_ordered_on_insert.2 h lemma partially_well_ordered_on_iff_finite_antichains [is_symm α r] : s.partially_well_ordered_on r ↔ ∀ t ⊆ s, is_antichain r t → t.finite := begin refine ⟨λ h t ht hrt, hrt.finite_of_partially_well_ordered_on (h.mono ht), _⟩, rintro hs f hf, by_contra' H, refine infinite_range_of_injective (λ m n hmn, _) (hs _ (range_subset_iff.2 hf) _), { obtain h | h | h := lt_trichotomy m n, { refine (H _ _ h _).elim, rw hmn, exact refl _ }, { exact h }, { refine (H _ _ h _).elim, rw hmn, exact refl _ } }, rintro _ ⟨m, hm, rfl⟩ _ ⟨n, hn, rfl⟩ hmn, obtain h | h := (ne_of_apply_ne _ hmn).lt_or_lt, { exact H _ _ h }, { exact mt symm (H _ _ h) } end variables [is_trans α r] lemma partially_well_ordered_on.exists_monotone_subseq (h : s.partially_well_ordered_on r) (f : ℕ → α) (hf : ∀ n, f n ∈ s) : ∃ g : ℕ ↪o ℕ, ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq r f, { refine ⟨g, λ m n hle, _⟩, obtain hlt | rfl := hle.lt_or_eq, exacts [h1 m n hlt, refl_of r _] }, { exfalso, obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) (λ n, hf _), exact h2 m n hlt hle } end lemma partially_well_ordered_on_iff_exists_monotone_subseq : s.partially_well_ordered_on r ↔ ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin classical, split; intros h f hf, { exact h.exists_monotone_subseq f hf }, { obtain ⟨g, gmon⟩ := h f hf, exact ⟨g 0, g 1, g.lt_iff_lt.2 zero_lt_one, gmon _ _ zero_le_one⟩ } end protected lemma partially_well_ordered_on.prod {t : set β} (hs : partially_well_ordered_on s r) (ht : partially_well_ordered_on t r') : partially_well_ordered_on (s ×ˢ t) (λ x y : α × β, r x.1 y.1 ∧ r' x.2 y.2) := begin intros f hf, obtain ⟨g₁, h₁⟩ := hs.exists_monotone_subseq (prod.fst ∘ f) (λ n, (hf n).1), obtain ⟨m, n, hlt, hle⟩ := ht (prod.snd ∘ f ∘ g₁) (λ n, (hf _).2), exact ⟨g₁ m, g₁ n, g₁.strict_mono hlt, h₁ _ _ hlt.le, hle⟩ end end is_refl lemma partially_well_ordered_on.well_founded_on [is_preorder α r] (h : s.partially_well_ordered_on r) : s.well_founded_on (λ a b, r a b ∧ ¬r b a) := begin letI : preorder α := { le := r, le_refl := refl_of r, le_trans := λ _ _ _, trans_of r }, change s.well_founded_on (<), change s.partially_well_ordered_on (≤) at h, rw well_founded_on_iff_no_descending_seq, intros f hf, obtain ⟨m, n, hlt, hle⟩ := h f hf, exact (f.map_rel_iff.2 hlt).not_le hle, end end partially_well_ordered_on section is_pwo variables [preorder α] [preorder β] {s t : set α} /-- A subset of a preorder is partially well-ordered when any infinite sequence contains a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/ def is_pwo (s : set α) : Prop := partially_well_ordered_on s (≤) lemma is_pwo.mono (ht : t.is_pwo) : s ⊆ t → s.is_pwo := ht.mono theorem is_pwo.exists_monotone_subseq (h : s.is_pwo) (f : ℕ → α) (hf : ∀ n, f n ∈ s) : ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := h.exists_monotone_subseq f hf theorem is_pwo_iff_exists_monotone_subseq : s.is_pwo ↔ ∀ f : ℕ → α, (∀ n, f n ∈ s) → ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := partially_well_ordered_on_iff_exists_monotone_subseq protected lemma is_pwo.is_wf (h : s.is_pwo) : s.is_wf := by simpa only [← lt_iff_le_not_le] using h.well_founded_on lemma is_pwo.prod {t : set β} (hs : s.is_pwo) (ht : t.is_pwo) : is_pwo (s ×ˢ t) := hs.prod ht lemma is_pwo.image_of_monotone_on (hs : s.is_pwo) {f : α → β} (hf : monotone_on f s) : is_pwo (f '' s) := hs.image_of_monotone_on hf lemma is_pwo.image_of_monotone (hs : s.is_pwo) {f : α → β} (hf : monotone f) : is_pwo (f '' s) := hs.image_of_monotone_on (hf.monotone_on _) protected lemma is_pwo.union (hs : is_pwo s) (ht : is_pwo t) : is_pwo (s ∪ t) := hs.union ht @[simp] lemma is_pwo_union : is_pwo (s ∪ t) ↔ is_pwo s ∧ is_pwo t := partially_well_ordered_on_union protected lemma finite.is_pwo (hs : s.finite) : is_pwo s := hs.partially_well_ordered_on @[simp] lemma is_pwo_of_finite [finite α] : s.is_pwo := s.to_finite.is_pwo @[simp] lemma is_pwo_singleton (a : α) : is_pwo ({a} : set α) := (finite_singleton a).is_pwo @[simp] lemma is_pwo_empty : is_pwo (∅ : set α) := finite_empty.is_pwo protected lemma subsingleton.is_pwo (hs : s.subsingleton) : is_pwo s := hs.finite.is_pwo @[simp] lemma is_pwo_insert {a} : is_pwo (insert a s) ↔ is_pwo s := by simp only [←singleton_union, is_pwo_union, is_pwo_singleton, true_and] protected lemma is_pwo.insert (h : is_pwo s) (a : α) : is_pwo (insert a s) := is_pwo_insert.2 h protected lemma finite.is_wf (hs : s.finite) : is_wf s := hs.is_pwo.is_wf @[simp] lemma is_wf_singleton {a : α} : is_wf ({a} : set α) := (finite_singleton a).is_wf protected lemma subsingleton.is_wf (hs : s.subsingleton) : is_wf s := hs.is_pwo.is_wf @[simp] lemma is_wf_insert {a} : is_wf (insert a s) ↔ is_wf s := by simp only [←singleton_union, is_wf_union, is_wf_singleton, true_and] lemma is_wf.insert (h : is_wf s) (a : α) : is_wf (insert a s) := is_wf_insert.2 h end is_pwo section well_founded_on variables {r : α → α → Prop} [is_strict_order α r] {s : set α} {a : α} protected lemma finite.well_founded_on (hs : s.finite) : s.well_founded_on r := by { letI := partial_order_of_SO r, exact hs.is_wf } @[simp] lemma well_founded_on_singleton : well_founded_on ({a} : set α) r := (finite_singleton a).well_founded_on protected lemma subsingleton.well_founded_on (hs : s.subsingleton) : s.well_founded_on r := hs.finite.well_founded_on @[simp] lemma well_founded_on_insert : well_founded_on (insert a s) r ↔ well_founded_on s r := by simp only [←singleton_union, well_founded_on_union, well_founded_on_singleton, true_and] lemma well_founded_on.insert (h : well_founded_on s r) (a : α) : well_founded_on (insert a s) r := well_founded_on_insert.2 h end well_founded_on section linear_order variables [linear_order α] {s : set α} protected lemma is_wf.is_pwo (hs : s.is_wf) : s.is_pwo := begin intros f hf, lift f to ℕ → s using hf, have hrange : (range f).nonempty := range_nonempty _, rcases hs.has_min (range f) (range_nonempty _) with ⟨_, ⟨m, rfl⟩, hm⟩, simp only [forall_range_iff, not_lt] at hm, exact ⟨m, m + 1, lt_add_one m, hm _⟩, end /-- In a linear order, the predicates `set.is_wf` and `set.is_pwo` are equivalent. -/ lemma is_wf_iff_is_pwo : s.is_wf ↔ s.is_pwo := ⟨is_wf.is_pwo, is_pwo.is_wf⟩ end linear_order end set namespace finset variables {r : α → α → Prop} @[simp] protected lemma partially_well_ordered_on [is_refl α r] (s : finset α) : (s : set α).partially_well_ordered_on r := s.finite_to_set.partially_well_ordered_on @[simp] protected lemma is_pwo [preorder α] (s : finset α) : set.is_pwo (↑s : set α) := s.partially_well_ordered_on @[simp] protected lemma is_wf [preorder α] (s : finset α) : set.is_wf (↑s : set α) := s.finite_to_set.is_wf @[simp] protected lemma well_founded_on [is_strict_order α r] (s : finset α) : set.well_founded_on (↑s : set α) r := by { letI := partial_order_of_SO r, exact s.is_wf } lemma well_founded_on_sup [is_strict_order α r] (s : finset ι) {f : ι → set α} : (s.sup f).well_founded_on r ↔ ∀ i ∈ s, (f i).well_founded_on r := finset.cons_induction_on s (by simp) $ λ a s ha hs, by simp [-sup_set_eq_bUnion, hs] lemma partially_well_ordered_on_sup (s : finset ι) {f : ι → set α} : (s.sup f).partially_well_ordered_on r ↔ ∀ i ∈ s, (f i).partially_well_ordered_on r := finset.cons_induction_on s (by simp) $ λ a s ha hs, by simp [-sup_set_eq_bUnion, hs] lemma is_wf_sup [preorder α] (s : finset ι) {f : ι → set α} : (s.sup f).is_wf ↔ ∀ i ∈ s, (f i).is_wf := s.well_founded_on_sup lemma is_pwo_sup [preorder α] (s : finset ι) {f : ι → set α} : (s.sup f).is_pwo ↔ ∀ i ∈ s, (f i).is_pwo := s.partially_well_ordered_on_sup @[simp] lemma well_founded_on_bUnion [is_strict_order α r] (s : finset ι) {f : ι → set α} : (⋃ i ∈ s, f i).well_founded_on r ↔ ∀ i ∈ s, (f i).well_founded_on r := by simpa only [finset.sup_eq_supr] using s.well_founded_on_sup @[simp] lemma partially_well_ordered_on_bUnion (s : finset ι) {f : ι → set α} : (⋃ i ∈ s, f i).partially_well_ordered_on r ↔ ∀ i ∈ s, (f i).partially_well_ordered_on r := by simpa only [finset.sup_eq_supr] using s.partially_well_ordered_on_sup @[simp] lemma is_wf_bUnion [preorder α] (s : finset ι) {f : ι → set α} : (⋃ i ∈ s, f i).is_wf ↔ ∀ i ∈ s, (f i).is_wf := s.well_founded_on_bUnion @[simp] lemma is_pwo_bUnion [preorder α] (s : finset ι) {f : ι → set α} : (⋃ i ∈ s, f i).is_pwo ↔ ∀ i ∈ s, (f i).is_pwo := s.partially_well_ordered_on_bUnion end finset namespace set section preorder variables [preorder α] {s : set α} {a : α} /-- `is_wf.min` returns a minimal element of a nonempty well-founded set. -/ noncomputable def is_wf.min (hs : is_wf s) (hn : s.nonempty) : α := hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) lemma is_wf.min_mem (hs : is_wf s) (hn : s.nonempty) : hs.min hn ∈ s := (well_founded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2 lemma is_wf.not_lt_min (hs : is_wf s) (hn : s.nonempty) (ha : a ∈ s) : ¬ a < hs.min hn := hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s)) @[simp] lemma is_wf_min_singleton (a) {hs : is_wf ({a} : set α)} {hn : ({a} : set α).nonempty} : hs.min hn = a := eq_of_mem_singleton (is_wf.min_mem hs hn) end preorder section linear_order variables [linear_order α] {s t : set α} {a : α} lemma is_wf.min_le (hs : s.is_wf) (hn : s.nonempty) (ha : a ∈ s) : hs.min hn ≤ a := le_of_not_lt (hs.not_lt_min hn ha) lemma is_wf.le_min_iff (hs : s.is_wf) (hn : s.nonempty) : a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b := ⟨λ ha b hb, le_trans ha (hs.min_le hn hb), λ h, h _ (hs.min_mem _)⟩ lemma is_wf.min_le_min_of_subset {hs : s.is_wf} {hsn : s.nonempty} {ht : t.is_wf} {htn : t.nonempty} (hst : s ⊆ t) : ht.min htn ≤ hs.min hsn := (is_wf.le_min_iff _ _).2 (λ b hb, ht.min_le htn (hst hb)) lemma is_wf.min_union (hs : s.is_wf) (hsn : s.nonempty) (ht : t.is_wf) (htn : t.nonempty) : (hs.union ht).min (union_nonempty.2 (or.intro_left _ hsn)) = min (hs.min hsn) (ht.min htn) := begin refine le_antisymm (le_min (is_wf.min_le_min_of_subset (subset_union_left _ _)) (is_wf.min_le_min_of_subset (subset_union_right _ _))) _, rw min_le_iff, exact ((mem_union _ _ _).1 ((hs.union ht).min_mem (union_nonempty.2 (or.intro_left _ hsn)))).imp (hs.min_le _) (ht.min_le _), end end linear_order end set open set namespace set.partially_well_ordered_on variables {r : α → α → Prop} /-- In the context of partial well-orderings, a bad sequence is a nonincreasing sequence whose range is contained in a particular set `s`. One exists if and only if `s` is not partially well-ordered. -/ def is_bad_seq (r : α → α → Prop) (s : set α) (f : ℕ → α) : Prop := (∀ n, f n ∈ s) ∧ ∀ m n : ℕ, m < n → ¬ r (f m) (f n) lemma iff_forall_not_is_bad_seq (r : α → α → Prop) (s : set α) : s.partially_well_ordered_on r ↔ ∀ f, ¬ is_bad_seq r s f := forall_congr $ λ f, by simp [is_bad_seq] /-- This indicates that every bad sequence `g` that agrees with `f` on the first `n` terms has `rk (f n) ≤ rk (g n)`. -/ def is_min_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) : Prop := ∀ g : ℕ → α, (∀ (m : ℕ), m < n → f m = g m) → rk (g n) < rk (f n) → ¬ is_bad_seq r s g /-- Given a bad sequence `f`, this constructs a bad sequence that agrees with `f` on the first `n` terms and is minimal at `n`. -/ noncomputable def min_bad_seq_of_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) (hf : is_bad_seq r s f) : { g : ℕ → α // (∀ (m : ℕ), m < n → f m = g m) ∧ is_bad_seq r s g ∧ is_min_bad_seq r rk s n g } := begin classical, have h : ∃ (k : ℕ) (g : ℕ → α), (∀ m, m < n → f m = g m) ∧ is_bad_seq r s g ∧ rk (g n) = k := ⟨_, f, λ _ _, rfl, hf, rfl⟩, obtain ⟨h1, h2, h3⟩ := classical.some_spec (nat.find_spec h), refine ⟨classical.some (nat.find_spec h), h1, by convert h2, λ g hg1 hg2 con, _⟩, refine nat.find_min h _ ⟨g, λ m mn, (h1 m mn).trans (hg1 m mn), by convert con, rfl⟩, rwa ← h3, end lemma exists_min_bad_of_exists_bad (r : α → α → Prop) (rk : α → ℕ) (s : set α) : (∃ f, is_bad_seq r s f) → ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rintro ⟨f0, (hf0 : is_bad_seq r s f0)⟩, let fs : Π (n : ℕ), { f : ℕ → α // is_bad_seq r s f ∧ is_min_bad_seq r rk s n f }, { refine nat.rec _ _, { exact ⟨(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).1, (min_bad_seq_of_bad_seq r rk s 0 f0 hf0).2.2⟩, }, { exact λ n fn, ⟨(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).1, (min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).2.2⟩ } }, have h : ∀ m n, m ≤ n → (fs m).1 m = (fs n).1 m, { intros m n mn, obtain ⟨k, rfl⟩ := exists_add_of_le mn, clear mn, induction k with k ih, { refl }, rw [ih, ((min_bad_seq_of_bad_seq r rk s (m + k).succ (fs (m + k)).1 (fs (m + k)).2.1).2.1 m (nat.lt_succ_iff.2 (nat.add_le_add_left k.zero_le m)))], refl }, refine ⟨λ n, (fs n).1 n, ⟨(λ n, ((fs n).2).1.1 n), λ m n mn, _⟩, λ n g hg1 hg2, _⟩, { dsimp, rw [← subtype.val_eq_coe, h m n (le_of_lt mn)], convert (fs n).2.1.2 m n mn }, { convert (fs n).2.2 g (λ m mn, eq.trans _ (hg1 m mn)) (lt_of_lt_of_le hg2 le_rfl), rw ← h m n (le_of_lt mn) }, end lemma iff_not_exists_is_min_bad_seq (rk : α → ℕ) {s : set α} : s.partially_well_ordered_on r ↔ ¬ ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rw [iff_forall_not_is_bad_seq, ← not_exists, not_congr], split, { apply exists_min_bad_of_exists_bad }, rintro ⟨f, hf1, hf2⟩, exact ⟨f, hf1⟩, end /-- Higman's Lemma, which states that for any reflexive, transitive relation `r` which is partially well-ordered on a set `s`, the relation `list.sublist_forall₂ r` is partially well-ordered on the set of lists of elements of `s`. That relation is defined so that `list.sublist_forall₂ r l₁ l₂` whenever `l₁` related pointwise by `r` to a sublist of `l₂`. -/ lemma partially_well_ordered_on_sublist_forall₂ (r : α → α → Prop) [is_refl α r] [is_trans α r] {s : set α} (h : s.partially_well_ordered_on r) : { l : list α | ∀ x, x ∈ l → x ∈ s }.partially_well_ordered_on (list.sublist_forall₂ r) := begin rcases s.eq_empty_or_nonempty with rfl | ⟨as, has⟩, { apply partially_well_ordered_on.mono (finset.partially_well_ordered_on {list.nil}), { intros l hl, rw [finset.mem_coe, finset.mem_singleton, list.eq_nil_iff_forall_not_mem], exact hl, }, apply_instance }, haveI : inhabited α := ⟨as⟩, rw [iff_not_exists_is_min_bad_seq (list.length)], rintro ⟨f, hf1, hf2⟩, have hnil : ∀ n, f n ≠ list.nil := λ n con, (hf1).2 n n.succ n.lt_succ_self (con.symm ▸ list.sublist_forall₂.nil), obtain ⟨g, hg⟩ := h.exists_monotone_subseq (list.head ∘ f) _, swap, { simp only [set.range_subset_iff, function.comp_apply], exact λ n, hf1.1 n _ (list.head_mem_self (hnil n)) }, have hf' := hf2 (g 0) (λ n, if n < g 0 then f n else list.tail (f (g (n - g 0)))) (λ m hm, (if_pos hm).symm) _, swap, { simp only [if_neg (lt_irrefl (g 0)), tsub_self], rw [list.length_tail, ← nat.pred_eq_sub_one], exact nat.pred_lt (λ con, hnil _ (list.length_eq_zero.1 con)) }, rw [is_bad_seq] at hf', push_neg at hf', obtain ⟨m, n, mn, hmn⟩ := hf' _, swap, { rintro n x hx, split_ifs at hx with hn hn, { exact hf1.1 _ _ hx }, { refine hf1.1 _ _ (list.tail_subset _ hx), } }, by_cases hn : n < g 0, { apply hf1.2 m n mn, rwa [if_pos hn, if_pos (mn.trans hn)] at hmn }, { obtain ⟨n', rfl⟩ := exists_add_of_le (not_lt.1 hn), rw [if_neg hn, add_comm (g 0) n', add_tsub_cancel_right] at hmn, split_ifs at hmn with hm hm, { apply hf1.2 m (g n') (lt_of_lt_of_le hm (g.monotone n'.zero_le)), exact trans hmn (list.tail_sublist_forall₂_self _) }, { rw [← (tsub_lt_iff_left (le_of_not_lt hm))] at mn, apply hf1.2 _ _ (g.lt_iff_lt.2 mn), rw [← list.cons_head_tail (hnil (g (m - g 0))), ← list.cons_head_tail (hnil (g n'))], exact list.sublist_forall₂.cons (hg _ _ (le_of_lt mn)) hmn, } } end end set.partially_well_ordered_on lemma well_founded.is_wf [has_lt α] (h : well_founded ((<) : α → α → Prop)) (s : set α) : s.is_wf := (set.is_wf_univ_iff.2 h).mono s.subset_univ /-- A version of **Dickson's lemma** any subset of functions `Π s : σ, α s` is partially well ordered, when `σ` is a `fintype` and each `α s` is a linear well order. This includes the classical case of Dickson's lemma that `ℕ ^ n` is a well partial order. Some generalizations would be possible based on this proof, to include cases where the target is partially well ordered, and also to consider the case of `set.partially_well_ordered_on` instead of `set.is_pwo`. -/ lemma pi.is_pwo {α : ι → Type*} [Π i, linear_order (α i)] [∀ i, is_well_order (α i) (<)] [finite ι] (s : set (Π i, α i)) : s.is_pwo := begin casesI nonempty_fintype ι, suffices : ∀ s : finset ι, ∀ (f : ℕ → Π s, α s), ∃ g : ℕ ↪o ℕ, ∀ ⦃a b : ℕ⦄, a ≤ b → ∀ (x : ι) (hs : x ∈ s), (f ∘ g) a x ≤ (f ∘ g) b x, { refine is_pwo_iff_exists_monotone_subseq.2 (λ f hf, _), simpa only [finset.mem_univ, true_implies_iff] using this finset.univ f }, refine finset.cons_induction _ _, { intros f, existsi rel_embedding.refl (≤), simp only [is_empty.forall_iff, implies_true_iff, forall_const, finset.not_mem_empty], }, { intros x s hx ih f, obtain ⟨g, hg⟩ := (is_well_founded.wf.is_wf univ).is_pwo.exists_monotone_subseq (λ n, f n x) mem_univ, obtain ⟨g', hg'⟩ := ih (f ∘ g), refine ⟨g'.trans g, λ a b hab, (finset.forall_mem_cons _ _).2 _⟩, exact ⟨hg (order_hom_class.mono g' hab), hg' hab⟩ } end
692796e92b75e8682fcd997d1cc0f9c5348ad031
618003631150032a5676f229d13a079ac875ff77
/src/ring_theory/free_ring.lean
2392ade46f28ac3d9bfe251c6a55fdc65cbf1b7b
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
3,932
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import data.polynomial universes u v def free_ring (α : Type u) : Type u := free_abelian_group $ free_monoid α namespace free_ring variables (α : Type u) instance : ring (free_ring α) := free_abelian_group.ring _ instance : inhabited (free_ring α) := ⟨0⟩ variables {α} def of (x : α) : free_ring α := free_abelian_group.of [x] @[elab_as_eliminator] protected lemma induction_on {C : free_ring α → Prop} (z : free_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_ring α) ▸ ha _ _ hn1 h1) (λ m, list.rec_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {β : Type v} [ring β] (f : α → β) def lift : free_ring α → β := free_abelian_group.lift $ λ L, (list.map f L).prod @[simp] lemma lift_zero : lift f 0 = 0 := rfl @[simp] lemma lift_one : lift f 1 = 1 := free_abelian_group.lift.of _ _ @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ one_mul _ @[simp] lemma lift_add (x y) : lift f (x + y) = lift f x + lift f y := free_abelian_group.lift.add _ _ _ @[simp] lemma lift_neg (x) : lift f (-x) = -lift f x := free_abelian_group.lift.neg _ _ @[simp] lemma lift_sub (x y) : lift f (x - y) = lift f x - lift f y := free_abelian_group.lift.sub _ _ _ @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros L2, conv { to_lhs, dsimp only [(*), mul_zero_class.mul, semiring.mul, ring.mul, semigroup.mul] }, rw [free_abelian_group.lift.of, lift, free_abelian_group.lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros L1, iterate 3 { rw free_abelian_group.lift.of }, show list.prod (list.map f (_ ++ _)) = _, rw [list.map_append, list.prod_append] }, { intros L1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros L2 ih, rw [mul_neg_eq_neg_mul_symm, lift_neg, lift_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, lift_add, lift_add, mul_add, ih1, ih2] }, end instance : is_ring_hom (lift f) := { map_one := lift_one f, map_mul := lift_mul f, map_add := lift_add f } @[simp] lemma lift_pow (x) (n : ℕ) : lift f (x ^ n) = lift f x ^ n := is_semiring_hom.map_pow _ x n @[simp] lemma lift_comp_of (f : free_ring α → β) [is_ring_hom f] : lift (f ∘ of) = f := funext $ λ x, free_ring.induction_on x (by rw [lift_neg, lift_one, is_ring_hom.map_neg f, is_ring_hom.map_one f]) (lift_of _) (λ x y ihx ihy, by rw [lift_add, is_ring_hom.map_add f, ihx, ihy]) (λ x y ihx ihy, by rw [lift_mul, is_ring_hom.map_mul f, ihx, ihy]) end lift variables {β : Type v} (f : α → β) def map : free_ring α → free_ring β := lift $ of ∘ f @[simp] lemma map_zero : map f 0 = 0 := rfl @[simp] lemma map_one : map f 1 = 1 := rfl @[simp] lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ @[simp] lemma map_add (x y) : map f (x + y) = map f x + map f y := lift_add _ _ _ @[simp] lemma map_neg (x) : map f (-x) = -map f x := lift_neg _ _ @[simp] lemma map_sub (x y) : map f (x - y) = map f x - map f y := lift_sub _ _ _ @[simp] lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ @[simp] lemma map_pow (x) (n : ℕ) : map f (x ^ n) = (map f x) ^ n := lift_pow _ _ _ end free_ring
d923a844331e96781c31aa2aef7420fed5be1a54
6e41ee3ac9b96e8980a16295cc21f131e731884f
/library/logic/eq.lean
3359865ed65c6952a8c63b9bb1d3e1d22a2ea4d0
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,459
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: logic.eq Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn Additional declarations/theorems about equality. See also init.datatypes and init.logic. -/ open eq.ops namespace eq variables {A B : Type} {a a' a₁ a₂ a₃ a₄ : A} theorem irrel (H₁ H₂ : a = a') : H₁ = H₂ := !proof_irrel theorem id_refl (H₁ : a = a) : H₁ = (eq.refl a) := rfl definition drec_on {B : Πa' : A, a = a' → Type} (H₁ : a = a') (H₂ : B a (refl a)) : B a' H₁ := eq.rec (λH₁ : a = a, show B a H₁, from H₂) H₁ H₁ theorem rec_on_id {B : A → Type} (H : a = a) (b : B a) : rec_on H b = b := rfl theorem rec_on_constant (H : a = a') {B : Type} (b : B) : rec_on H b = b := drec_on H rfl theorem rec_on_constant2 (H₁ : a₁ = a₂) (H₂ : a₃ = a₄) (b : B) : rec_on H₁ b = rec_on H₂ b := rec_on_constant H₁ b ⬝ rec_on_constant H₂ b⁻¹ theorem rec_on_irrel_arg {f : A → B} {D : B → Type} (H : a = a') (H' : f a = f a') (b : D (f a)) : rec_on H b = rec_on H' b := drec_on H (λ(H' : f a = f a), !rec_on_id⁻¹) H' theorem rec_on_irrel {a a' : A} {D : A → Type} (H H' : a = a') (b : D a) : drec_on H b = drec_on H' b := proof_irrel H H' ▸ rfl theorem rec_on_compose {a b c : A} {P : A → Type} (H₁ : a = b) (H₂ : b = c) (u : P a) : rec_on H₂ (rec_on H₁ u) = rec_on (trans H₁ H₂) u := (show ∀ H₂ : b = c, rec_on H₂ (rec_on H₁ u) = rec_on (trans H₁ H₂) u, from drec_on H₂ (take (H₂ : b = b), rec_on_id H₂ _)) H₂ end eq open eq section variables {A B C D E F : Type} variables {a a' : A} {b b' : B} {c c' : C} {d d' : D} {e e' : E} theorem congr_fun {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a := H ▸ rfl theorem congr_arg (f : A → B) (H : a = a') : f a = f a' := H ▸ rfl theorem congr {f g : A → B} (H₁ : f = g) (H₂ : a = a') : f a = g a' := H₁ ▸ H₂ ▸ rfl theorem congr_arg2 (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := congr (congr_arg f Ha) Hb theorem congr_arg3 (f : A → B → C → D) (Ha : a = a') (Hb : b = b') (Hc : c = c') : f a b c = f a' b' c' := congr (congr_arg2 f Ha Hb) Hc theorem congr_arg4 (f : A → B → C → D → E) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') : f a b c d = f a' b' c' d' := congr (congr_arg3 f Ha Hb Hc) Hd theorem congr_arg5 (f : A → B → C → D → E → F) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e') : f a b c d e = f a' b' c' d' e' := congr (congr_arg4 f Ha Hb Hc Hd) He theorem congr2 (f f' : A → B → C) (Hf : f = f') (Ha : a = a') (Hb : b = b') : f a b = f' a' b' := Hf ▸ congr_arg2 f Ha Hb theorem congr3 (f f' : A → B → C → D) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') : f a b c = f' a' b' c' := Hf ▸ congr_arg3 f Ha Hb Hc theorem congr4 (f f' : A → B → C → D → E) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') : f a b c d = f' a' b' c' d' := Hf ▸ congr_arg4 f Ha Hb Hc Hd theorem congr5 (f f' : A → B → C → D → E → F) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e') : f a b c d e = f' a' b' c' d' e' := Hf ▸ congr_arg5 f Ha Hb Hc Hd He end theorem equal_f {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) : ∀x, f x = g x := take x, congr_fun H x section variables {a b c : Prop} theorem eqmp (H₁ : a = b) (H₂ : a) : b := H₁ ▸ H₂ theorem eqmpr (H₁ : a = b) (H₂ : b) : a := H₁⁻¹ ▸ H₂ theorem imp_trans (H₁ : a → b) (H₂ : b → c) : a → c := assume Ha, H₂ (H₁ Ha) theorem imp_eq_trans (H₁ : a → b) (H₂ : b = c) : a → c := assume Ha, H₂ ▸ (H₁ Ha) theorem eq_imp_trans (H₁ : a = b) (H₂ : b → c) : a → c := assume Ha, H₂ (H₁ ▸ Ha) end section variables {p : Prop} theorem p_ne_false : p → p ≠ false := assume (Hp : p) (Heq : p = false), Heq ▸ Hp theorem p_ne_true : ¬p → p ≠ true := assume (Hnp : ¬p) (Heq : p = true), absurd trivial (Heq ▸ Hnp) end theorem true_ne_false : ¬true = false := assume H : true = false, H ▸ trivial
a7e312a6ac602933420b40db0d12e931a855bec7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/control/monad/basic.lean
480462e348c820c84325ee582d390d1a5b4076e7
[]
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
2,599
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.basic import Mathlib.data.equiv.basic import Mathlib.PostPort universes u v u₀ u₁ v₀ v₁ namespace Mathlib /-! # Monad ## Attributes * ext * functor_norm * monad_norm ## Implementation Details Set of rewrite rules and automation for monads in general and `reader_t`, `state_t`, `except_t` and `option_t` in particular. The rewrite rules for monads are carefully chosen so that `simp with functor_norm` will not introduce monadic vocabulary in a context where applicatives would do just fine but will handle monadic notation already present in an expression. In a context where monadic reasoning is desired `simp with monad_norm` will translate functor and applicative notation into monad notation and use regular `functor_norm` rules as well. ## Tags functor, applicative, monad, simp -/ theorem map_eq_bind_pure_comp (m : Type u → Type v) [Monad m] [is_lawful_monad m] {α : Type u} {β : Type u} (f : α → β) (x : m α) : f <$> x = x >>= pure ∘ f := eq.mpr (id (Eq._oldrec (Eq.refl (f <$> x = x >>= pure ∘ f)) (bind_pure_comp_eq_map f x))) (Eq.refl (f <$> x)) /-- run a `state_t` program and discard the final state -/ def state_t.eval {m : Type u → Type v} [Functor m] {σ : Type u} {α : Type u} (cmd : state_t σ m α) (s : σ) : m α := prod.fst <$> state_t.run cmd s /-- reduce the equivalence between two state monads to the equivalence between their respective function spaces -/ def state_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ : Type u₀} {σ₁ : Type u₀} {α₂ : Type u₁} {σ₂ : Type u₁} (F : (σ₁ → m₁ (α₁ × σ₁)) ≃ (σ₂ → m₂ (α₂ × σ₂))) : state_t σ₁ m₁ α₁ ≃ state_t σ₂ m₂ α₂ := equiv.mk (fun (_x : state_t σ₁ m₁ α₁) => sorry) (fun (_x : state_t σ₂ m₂ α₂) => sorry) sorry sorry /-- reduce the equivalence between two reader monads to the equivalence between their respective function spaces -/ def reader_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ : Type u₀} {ρ₁ : Type u₀} {α₂ : Type u₁} {ρ₂ : Type u₁} (F : (ρ₁ → m₁ α₁) ≃ (ρ₂ → m₂ α₂)) : reader_t ρ₁ m₁ α₁ ≃ reader_t ρ₂ m₂ α₂ := equiv.mk (fun (_x : reader_t ρ₁ m₁ α₁) => sorry) (fun (_x : reader_t ρ₂ m₂ α₂) => sorry) sorry sorry
0ae6cf35b9d46bb6aafeb12fc4744026252cb070
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/perm/cycles.lean
bfe3bb1ab39b57fef72d127ecde1a1f16f599e5e
[ "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
59,110
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.finset.noncomm_prod import group_theory.perm.sign import logic.equiv.fintype /-! # Cyclic permutations ## Main definitions In the following, `f : equiv.perm β`. * `equiv.perm.is_cycle`: `f.is_cycle` when two nonfixed points of `β` are related by repeated application of `f`. * `equiv.perm.same_cycle`: `f.same_cycle x y` when `x` and `y` are in the same cycle of `f`. The following two definitions require that `β` is a `fintype`: * `equiv.perm.cycle_of`: `f.cycle_of x` is the cycle of `f` that `x` belongs to. * `equiv.perm.cycle_factors`: `f.cycle_factors` is a list of disjoint cyclic permutations that multiply to `f`. ## Main results * This file contains several closure results: - `closure_is_cycle` : The symmetric group is generated by cycles - `closure_cycle_adjacent_swap` : The symmetric group is generated by a cycle and an adjacent transposition - `closure_cycle_coprime_swap` : The symmetric group is generated by a cycle and a coprime transposition - `closure_prime_cycle_swap` : The symmetric group is generated by a prime cycle and a transposition -/ namespace equiv.perm open equiv function finset variables {α : Type*} {β : Type*} [decidable_eq α] section sign_cycle /-! ### `is_cycle` -/ variables [fintype α] /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle (f : perm β) : Prop := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle.ne_one {f : perm β} (h : is_cycle f) : f ≠ 1 := λ hf, by simpa [hf, is_cycle] using h @[simp] lemma not_is_cycle_one : ¬ (1 : perm β).is_cycle := λ H, H.ne_one rfl lemma is_cycle.two_le_card_support {f : perm α} (h : is_cycle f) : 2 ≤ f.support.card := two_le_card_support_of_ne_one h.ne_one lemma is_cycle_swap {α : Type*} [decidable_eq α] {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by { rw [zpow_one, swap_apply_def], split_ifs at *; cc }⟩⟩ lemma is_swap.is_cycle {α : Type*} [decidable_eq α] {f : perm α} (hf : is_swap f) : is_cycle f := begin obtain ⟨x, y, hxy, rfl⟩ := hf, exact is_cycle_swap hxy, end lemma is_cycle.inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc }, λ y hy, let ⟨i, hi⟩ := hx.2 y (by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc }) in ⟨-i, by rwa [zpow_neg, inv_zpow, inv_inv]⟩⟩ lemma is_cycle.is_cycle_conj {f g : perm β} (hf : is_cycle f) : is_cycle (g * f * g⁻¹) := begin obtain ⟨a, ha1, ha2⟩ := hf, refine ⟨g a, by simp [ha1], λ b hb, _⟩, obtain ⟨i, hi⟩ := ha2 (g⁻¹ b) _, { refine ⟨i, _⟩, rw conj_zpow, simp [hi] }, { contrapose! hb, rw [perm.mul_apply, perm.mul_apply, hb, apply_inv_self] } end lemma is_cycle.exists_zpow_eq {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← zpow_add, sub_add_cancel, hb]⟩ lemma is_cycle.exists_pow_eq [fintype β] {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℕ, (f ^ i) x = y := let ⟨n, hn⟩ := hf.exists_zpow_eq hx hy in by classical; exact ⟨(n % order_of f).to_nat, by { have := n.mod_nonneg (int.coe_nat_ne_zero.mpr (ne_of_gt (order_of_pos f))), rwa [← zpow_coe_nat, int.to_nat_of_nonneg this, ← zpow_eq_mod_order_of] }⟩ lemma is_cycle.exists_pow_eq_one [fintype β] {f : perm β} (hf : is_cycle f) : ∃ (k : ℕ) (hk : 1 < k), f ^ k = 1 := begin classical, have : is_of_fin_order f := exists_pow_eq_one f, rw is_of_fin_order_iff_pow_eq_one at this, obtain ⟨x, hx, hx'⟩ := hf, obtain ⟨_ | _ | k, hk, hk'⟩ := this, { exact absurd hk (lt_asymm hk) }, { rw pow_one at hk', simpa [hk'] using hx }, { exact ⟨k + 2, by simp, hk'⟩ } end /-- The subgroup generated by a cycle is in bijection with its support -/ noncomputable def is_cycle.zpowers_equiv_support {σ : perm α} (hσ : is_cycle σ) : (↑(subgroup.zpowers σ) : set (perm α)) ≃ (↑(σ.support) : set α) := equiv.of_bijective (λ τ, ⟨τ (classical.some hσ), begin obtain ⟨τ, n, rfl⟩ := τ, rw [finset.mem_coe, coe_fn_coe_base', subtype.coe_mk, zpow_apply_mem_support, mem_support], exact (classical.some_spec hσ).1, end⟩) begin split, { rintros ⟨a, m, rfl⟩ ⟨b, n, rfl⟩ h, ext y, by_cases hy : σ y = y, { simp_rw [subtype.coe_mk, zpow_apply_eq_self_of_apply_eq_self hy] }, { obtain ⟨i, rfl⟩ := (classical.some_spec hσ).2 y hy, rw [subtype.coe_mk, subtype.coe_mk, zpow_apply_comm σ m i, zpow_apply_comm σ n i], exact congr_arg _ (subtype.ext_iff.mp h) } }, by { rintros ⟨y, hy⟩, rw [finset.mem_coe, mem_support] at hy, obtain ⟨n, rfl⟩ := (classical.some_spec hσ).2 y hy, exact ⟨⟨σ ^ n, n, rfl⟩, rfl⟩ }, end @[simp] lemma is_cycle.zpowers_equiv_support_apply {σ : perm α} (hσ : is_cycle σ) {n : ℕ} : hσ.zpowers_equiv_support ⟨σ ^ n, n, rfl⟩ = ⟨(σ ^ n) (classical.some hσ), pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ := rfl @[simp] lemma is_cycle.zpowers_equiv_support_symm_apply {σ : perm α} (hσ : is_cycle σ) (n : ℕ) : hσ.zpowers_equiv_support.symm ⟨(σ ^ n) (classical.some hσ), pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ = ⟨σ ^ n, n, rfl⟩ := (equiv.symm_apply_eq _).2 hσ.zpowers_equiv_support_apply lemma order_of_is_cycle {σ : perm α} (hσ : is_cycle σ) : order_of σ = σ.support.card := begin rw [order_eq_card_zpowers, ←fintype.card_coe], convert fintype.card_congr (is_cycle.zpowers_equiv_support hσ), end lemma is_cycle_swap_mul_aux₁ {α : Type*} [decidable_eq α] : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by { rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← f.injective.eq_iff, apply_inv_self], exact this.1 }, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by { rw [apply_inv_self], rwa [pow_succ, mul_apply] at h }) in ⟨i + 1, by rw [add_comm, zpow_add, mul_apply, hi, zpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ {α : Type*} [decidable_eq α] : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by { rw [mul_apply, swap_apply_def], split_ifs; simp only [inv_eq_iff_eq, perm.mul_apply, zpow_neg_succ_of_nat, ne.def, perm.apply_inv_self] at *; cc }, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← zpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, zpow_neg_succ_of_nat, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, zpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, zpow_add, zpow_one, zpow_neg, ← inv_zpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, zpow_add, zpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma is_cycle.eq_swap_of_apply_apply_eq_self {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, zpow_add, mul_apply, hi] at hj, cases zpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle.swap_mul {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by { simp [swap_apply_def, mul_apply, if_neg hffx, f.injective.eq_iff, if_neg hx, hx], }, λ y hy, let ⟨i, hi⟩ := hf.exists_zpow_eq hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [zpow_one, mul_apply] ... = y : by rwa [← zpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ lemma is_cycle.sign : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1) ^ f.support.card | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1) ^ f.support.card : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, begin rw hf.eq_swap_of_apply_apply_eq_self hx.1 h1, simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap] end, by { rw [sign_mul, sign_swap hx.1.symm, h, sign_one, hf.eq_swap_of_apply_apply_eq_self hx.1 h1, card_support_swap hx.1.symm], refl } else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq _ _ h1, card_insert_of_not_mem (not_mem_erase _ _), sdiff_singleton_eq_erase], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by { rw [sign_mul, sign_swap hx.1.symm, (hf.swap_mul hx.1 h1).sign, ← h], simp only [pow_add, mul_one, neg_neg, one_mul, mul_neg, eq_self_iff_true, pow_one, neg_mul_neg] } using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} lemma is_cycle_of_is_cycle_pow {σ : perm α} {n : ℕ} (h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ := begin have key : ∀ x : α, (σ ^ n) x ≠ x ↔ σ x ≠ x, { simp_rw [←mem_support], exact finset.ext_iff.mp (le_antisymm (support_pow_le σ n) h2) }, obtain ⟨x, hx1, hx2⟩ := h1, refine ⟨x, (key x).mp hx1, λ y hy, _⟩, cases (hx2 y ((key y).mpr hy)) with i _, exact ⟨n * i, by rwa zpow_mul⟩ end -- The lemma `support_zpow_le` is relevant. It means that `h2` is equivalent to -- `σ.support = (σ ^ n).support`, as well as to `σ.support.card ≤ (σ ^ n).support.card`. lemma is_cycle_of_is_cycle_zpow {σ : perm α} {n : ℤ} (h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ := begin cases n, { exact is_cycle_of_is_cycle_pow h1 h2 }, { simp only [le_eq_subset, zpow_neg_succ_of_nat, perm.support_inv] at h1 h2, simpa using is_cycle_of_is_cycle_pow h1.inv h2 } end lemma is_cycle.extend_domain {α : Type*} {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} (h : is_cycle g) : is_cycle (g.extend_domain f) := begin obtain ⟨a, ha, ha'⟩ := h, refine ⟨f a, _, λ b hb, _⟩, { rw extend_domain_apply_image, exact λ con, ha (f.injective (subtype.coe_injective con)) }, by_cases pb : p b, { obtain ⟨i, hi⟩ := ha' (f.symm ⟨b, pb⟩) (λ con, hb _), { refine ⟨i, _⟩, have hnat : ∀ (k : ℕ) (a : α), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a), { intros k a, induction k with k ih, { refl }, rw [pow_succ, perm.mul_apply, ih, extend_domain_apply_image, pow_succ, perm.mul_apply] }, have hint : ∀ (k : ℤ) (a : α), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a), { intros k a, induction k with k k, { rw [zpow_of_nat, zpow_of_nat, hnat] }, rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, inv_eq_iff_eq, hnat, apply_inv_self] }, rw [hint, hi, apply_symm_apply, subtype.coe_mk] }, { rw [extend_domain_apply_subtype _ _ pb, con, apply_symm_apply, subtype.coe_mk] } }, { exact (hb (extend_domain_apply_not_subtype _ _ pb)).elim } end lemma nodup_of_pairwise_disjoint_cycles {l : list (perm β)} (h1 : ∀ f ∈ l, is_cycle f) (h2 : l.pairwise disjoint) : l.nodup := nodup_of_pairwise_disjoint (λ h, (h1 1 h).ne_one rfl) h2 end sign_cycle /-! ### `same_cycle` -/ /-- The equivalence relation indicating that two points are in the same cycle of a permutation. -/ def same_cycle (f : perm β) (x y : β) : Prop := ∃ i : ℤ, (f ^ i) x = y @[refl] lemma same_cycle.refl (f : perm β) (x : β) : same_cycle f x x := ⟨0, rfl⟩ @[symm] lemma same_cycle.symm {f : perm β} {x y : β} : same_cycle f x y → same_cycle f y x := λ ⟨i, hi⟩, ⟨-i, by rw [zpow_neg, ← hi, inv_apply_self]⟩ @[trans] lemma same_cycle.trans {f : perm β} {x y z : β} : same_cycle f x y → same_cycle f y z → same_cycle f x z := λ ⟨i, hi⟩ ⟨j, hj⟩, ⟨j + i, by rw [zpow_add, mul_apply, hi, hj]⟩ lemma same_cycle.apply_eq_self_iff {f : perm β} {x y : β} : same_cycle f x y → (f x = x ↔ f y = y) := λ ⟨i, hi⟩, by rw [← hi, ← mul_apply, ← zpow_one_add, add_comm, zpow_add_one, mul_apply, (f ^ i).injective.eq_iff] lemma is_cycle.same_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : same_cycle f x y := hf.exists_zpow_eq hx hy lemma same_cycle.nat' [fintype β] {f : perm β} {x y : β} (h : same_cycle f x y) : ∃ (i : ℕ) (h : i < order_of f), (f ^ i) x = y := begin classical, obtain ⟨k, rfl⟩ := h, use ((k % order_of f).nat_abs), have h₀ := int.coe_nat_pos.mpr (order_of_pos f), have h₁ := int.mod_nonneg k h₀.ne', rw [←zpow_coe_nat, int.nat_abs_of_nonneg h₁, ←zpow_eq_mod_order_of], refine ⟨_, rfl⟩, rw [←int.coe_nat_lt, int.nat_abs_of_nonneg h₁], exact int.mod_lt_of_pos _ h₀, end lemma same_cycle.nat'' [fintype β] {f : perm β} {x y : β} (h : same_cycle f x y) : ∃ (i : ℕ) (hpos : 0 < i) (h : i ≤ order_of f), (f ^ i) x = y := begin classical, obtain ⟨_|i, hi, rfl⟩ := h.nat', { refine ⟨order_of f, order_of_pos f, le_rfl, _⟩, rw [pow_order_of_eq_one, pow_zero] }, { exact ⟨i.succ, i.zero_lt_succ, hi.le, rfl⟩ } end instance [fintype α] (f : perm α) : decidable_rel (same_cycle f) := λ x y, decidable_of_iff (∃ n ∈ list.range (fintype.card (perm α)), (f ^ n) x = y) ⟨λ ⟨n, _, hn⟩, ⟨n, hn⟩, λ ⟨i, hi⟩, ⟨(i % order_of f).nat_abs, list.mem_range.2 (int.coe_nat_lt.1 $ by { rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), { apply lt_of_lt_of_le (int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), { simp [order_of_le_card_univ] }, exact fintype_perm }, exact fintype_perm, }), by { rw [← zpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← zpow_eq_mod_order_of, hi], exact fintype_perm }⟩⟩ lemma same_cycle_apply {f : perm β} {x y : β} : same_cycle f x (f y) ↔ same_cycle f x y := ⟨λ ⟨i, hi⟩, ⟨-1 + i, by rw [zpow_add, mul_apply, hi, zpow_neg_one, inv_apply_self]⟩, λ ⟨i, hi⟩, ⟨1 + i, by rw [zpow_add, mul_apply, hi, zpow_one]⟩⟩ lemma same_cycle_cycle {f : perm β} {x : β} (hx : f x ≠ x) : is_cycle f ↔ (∀ {y}, same_cycle f x y ↔ f y ≠ y) := ⟨λ hf y, ⟨λ ⟨i, hi⟩ hy, hx $ by { rw [← zpow_apply_eq_self_of_apply_eq_self hy i, (f ^ i).injective.eq_iff] at hi, rw [hi, hy] }, hf.exists_zpow_eq hx⟩, λ h, ⟨x, hx, λ y hy, h.2 hy⟩⟩ lemma same_cycle_inv (f : perm β) {x y : β} : same_cycle f⁻¹ x y ↔ same_cycle f x y := ⟨λ ⟨i, hi⟩, ⟨-i, by rw [zpow_neg, ← inv_zpow, hi]⟩, λ ⟨i, hi⟩, ⟨-i, by rw [zpow_neg, ← inv_zpow, inv_inv, hi]⟩ ⟩ lemma same_cycle_inv_apply {f : perm β} {x y : β} : same_cycle f x (f⁻¹ y) ↔ same_cycle f x y := by rw [← same_cycle_inv, same_cycle_apply, same_cycle_inv] @[simp] lemma same_cycle_pow_left_iff {f : perm β} {x y : β} {n : ℕ} : same_cycle f ((f ^ n) x) y ↔ same_cycle f x y := begin split, { rintro ⟨k, rfl⟩, use (k + n), simp [zpow_add] }, { rintro ⟨k, rfl⟩, use (k - n), rw [←zpow_coe_nat, ←mul_apply, ←zpow_add, int.sub_add_cancel] } end @[simp] lemma same_cycle_zpow_left_iff {f : perm β} {x y : β} {n : ℤ} : same_cycle f ((f ^ n) x) y ↔ same_cycle f x y := begin cases n, { exact same_cycle_pow_left_iff }, { rw [zpow_neg_succ_of_nat, ←inv_pow, ←same_cycle_inv, same_cycle_pow_left_iff, same_cycle_inv] } end /-- Unlike `support_congr`, which assumes that `∀ (x ∈ g.support), f x = g x)`, here we have the weaker assumption that `∀ (x ∈ f.support), f x = g x`. -/ lemma is_cycle.support_congr [fintype α] {f g : perm α} (hf : is_cycle f) (hg : is_cycle g) (h : f.support ⊆ g.support) (h' : ∀ (x ∈ f.support), f x = g x) : f = g := begin have : f.support = g.support, { refine le_antisymm h _, intros z hz, obtain ⟨x, hx, hf'⟩ := id hf, have hx' : g x ≠ x, { rwa [←h' x (mem_support.mpr hx)] }, obtain ⟨m, hm⟩ := hg.exists_pow_eq hx' (mem_support.mp hz), have h'' : ∀ (x ∈ f.support ∩ g.support), f x = g x, { intros x hx, exact h' x (mem_of_mem_inter_left hx) }, rwa [←hm, ←pow_eq_on_of_mem_support h'' _ x (mem_inter_of_mem (mem_support.mpr hx) (mem_support.mpr hx')), pow_apply_mem_support, mem_support] }, refine support_congr h _, simpa [←this] using h' end /-- If two cyclic permutations agree on all terms in their intersection, and that intersection is not empty, then the two cyclic permutations must be equal. -/ lemma is_cycle.eq_on_support_inter_nonempty_congr [fintype α] {f g : perm α} (hf : is_cycle f) (hg : is_cycle g) (h : ∀ (x ∈ f.support ∩ g.support), f x = g x) {x : α} (hx : f x = g x) (hx' : x ∈ f.support) : f = g := begin have hx'' : x ∈ g.support, { rwa [mem_support, ←hx, ←mem_support] }, have : f.support ⊆ g.support, { intros y hy, obtain ⟨k, rfl⟩ := hf.exists_pow_eq (mem_support.mp hx') (mem_support.mp hy), rwa [pow_eq_on_of_mem_support h _ _ (mem_inter_of_mem hx' hx''), pow_apply_mem_support] }, rw (inter_eq_left_iff_subset _ _).mpr this at h, exact hf.support_congr hg this h end lemma is_cycle.support_pow_eq_iff [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} : support (f ^ n) = support f ↔ ¬ order_of f ∣ n := begin rw order_of_dvd_iff_pow_eq_one, split, { intros h H, refine hf.ne_one _, rw [←support_eq_empty_iff, ←h, H, support_one] }, { intro H, apply le_antisymm (support_pow_le _ n) _, intros x hx, contrapose! H, ext z, by_cases hz : f z = z, { rw [pow_apply_eq_self_of_apply_eq_self hz, one_apply] }, { obtain ⟨k, rfl⟩ := hf.exists_pow_eq hz (mem_support.mp hx), apply (f ^ k).injective, rw [←mul_apply, (commute.pow_pow_self _ _ _).eq, mul_apply], simpa using H } } end lemma is_cycle.pow_iff [fintype β] {f : perm β} (hf : is_cycle f) {n : ℕ} : is_cycle (f ^ n) ↔ n.coprime (order_of f) := begin classical, split, { intro h, have hr : support (f ^ n) = support f, { rw hf.support_pow_eq_iff, rintro ⟨k, rfl⟩, refine h.ne_one _, simp [pow_mul, pow_order_of_eq_one] }, have : order_of (f ^ n) = order_of f, { rw [order_of_is_cycle h, hr, order_of_is_cycle hf] }, rw [order_of_pow, nat.div_eq_self] at this, cases this, { exact absurd this (order_of_pos _).ne' }, { rwa [nat.coprime_iff_gcd_eq_one, nat.gcd_comm] } }, { intro h, obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h, have hf' : is_cycle ((f ^ n) ^ m) := by rwa hm, refine is_cycle_of_is_cycle_pow hf' _, intros x hx, rw [hm], exact support_pow_le _ n hx } end lemma is_cycle.pow_eq_one_iff [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} : f ^ n = 1 ↔ ∃ (x ∈ f.support), (f ^ n) x = x := begin split, { intro h, obtain ⟨x, hx, -⟩ := id hf, exact ⟨x, mem_support.mpr hx, by simp [h]⟩ }, { rintro ⟨x, hx, hx'⟩, by_cases h : support (f ^ n) = support f, { rw [←h, mem_support] at hx, contradiction }, { rw [hf.support_pow_eq_iff, not_not] at h, obtain ⟨k, rfl⟩ := h, rw [pow_mul, pow_order_of_eq_one, one_pow] } } end lemma is_cycle.mem_support_pos_pow_iff_of_lt_order_of [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} (npos : 0 < n) (hn : n < order_of f) {x : α} : x ∈ (f ^ n).support ↔ x ∈ f.support := begin have : ¬ order_of f ∣ n := nat.not_dvd_of_pos_of_lt npos hn, rw ←hf.support_pow_eq_iff at this, rw this end lemma is_cycle.is_cycle_pow_pos_of_lt_prime_order [fintype β] {f : perm β} (hf : is_cycle f) (hf' : (order_of f).prime) (n : ℕ) (hn : 0 < n) (hn' : n < order_of f) : is_cycle (f ^ n) := begin classical, have : n.coprime (order_of f), { refine nat.coprime.symm _, rw nat.prime.coprime_iff_not_dvd hf', exact nat.not_dvd_of_pos_of_lt hn hn' }, obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime this, have hf'' := hf, rw ←hm at hf'', refine is_cycle_of_is_cycle_pow hf'' _, rw [hm], exact support_pow_le f n end /-! ### `cycle_of` -/ /-- `f.cycle_of x` is the cycle of the permutation `f` to which `x` belongs. -/ def cycle_of [fintype α] (f : perm α) (x : α) : perm α := of_subtype (@subtype_perm _ f (same_cycle f x) (λ _, same_cycle_apply.symm)) lemma cycle_of_apply [fintype α] (f : perm α) (x y : α) : cycle_of f x y = if same_cycle f x y then f y else y := rfl lemma cycle_of_inv [fintype α] (f : perm α) (x : α) : (cycle_of f x)⁻¹ = cycle_of f⁻¹ x := equiv.ext $ λ y, begin rw [inv_eq_iff_eq, cycle_of_apply, cycle_of_apply], split_ifs; simp [*, same_cycle_inv, same_cycle_inv_apply] at * end @[simp] lemma cycle_of_pow_apply_self [fintype α] (f : perm α) (x : α) : ∀ n : ℕ, (cycle_of f x ^ n) x = (f ^ n) x | 0 := rfl | (n+1) := by { rw [pow_succ, mul_apply, cycle_of_apply, cycle_of_pow_apply_self, if_pos, pow_succ, mul_apply], exact ⟨n, rfl⟩ } @[simp] lemma cycle_of_zpow_apply_self [fintype α] (f : perm α) (x : α) : ∀ n : ℤ, (cycle_of f x ^ n) x = (f ^ n) x | (n : ℕ) := cycle_of_pow_apply_self f x n | -[1+ n] := by rw [zpow_neg_succ_of_nat, ← inv_pow, cycle_of_inv, zpow_neg_succ_of_nat, ← inv_pow, cycle_of_pow_apply_self] lemma same_cycle.cycle_of_apply [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : cycle_of f x y = f y := dif_pos h lemma cycle_of_apply_of_not_same_cycle [fintype α] {f : perm α} {x y : α} (h : ¬same_cycle f x y) : cycle_of f x y = y := dif_neg h lemma same_cycle.cycle_of_eq [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : cycle_of f x = cycle_of f y := begin ext z, rw cycle_of_apply, split_ifs with hz hz, { exact (h.symm.trans hz).cycle_of_apply.symm }, { exact (cycle_of_apply_of_not_same_cycle (mt h.trans hz)).symm } end @[simp] lemma cycle_of_apply_apply_zpow_self [fintype α] (f : perm α) (x : α) (k : ℤ) : cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x := begin rw same_cycle.cycle_of_apply, { rw [add_comm, zpow_add, zpow_one, mul_apply] }, { exact ⟨k, rfl⟩ } end @[simp] lemma cycle_of_apply_apply_pow_self [fintype α] (f : perm α) (x : α) (k : ℕ) : cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x := by convert cycle_of_apply_apply_zpow_self f x k using 1 @[simp] lemma cycle_of_apply_apply_self [fintype α] (f : perm α) (x : α) : cycle_of f x (f x) = f (f x) := by convert cycle_of_apply_apply_pow_self f x 1 using 1 @[simp] lemma cycle_of_apply_self [fintype α] (f : perm α) (x : α) : cycle_of f x x = f x := (same_cycle.refl _ _).cycle_of_apply lemma is_cycle.cycle_of_eq [fintype α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) : cycle_of f x = f := equiv.ext $ λ y, if h : same_cycle f x y then by rw [h.cycle_of_apply] else by rw [cycle_of_apply_of_not_same_cycle h, not_not.1 (mt ((same_cycle_cycle hx).1 hf).2 h)] @[simp] lemma cycle_of_eq_one_iff [fintype α] (f : perm α) {x : α} : cycle_of f x = 1 ↔ f x = x := begin simp_rw [ext_iff, cycle_of_apply, one_apply], refine ⟨λ h, (if_pos (same_cycle.refl f x)).symm.trans (h x), λ h y, _⟩, by_cases hy : f y = y, { rw [hy, if_t_t] }, { exact if_neg (mt same_cycle.apply_eq_self_iff (by tauto)) }, end @[simp] lemma cycle_of_self_apply [fintype α] (f : perm α) (x : α) : cycle_of f (f x) = cycle_of f x := (same_cycle_apply.mpr (same_cycle.refl _ _)).symm.cycle_of_eq @[simp] lemma cycle_of_self_apply_pow [fintype α] (f : perm α) (n : ℕ) (x : α) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_pow_left_iff.mpr (same_cycle.refl _ _)).cycle_of_eq @[simp] lemma cycle_of_self_apply_zpow [fintype α] (f : perm α) (n : ℤ) (x : α) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_zpow_left_iff.mpr (same_cycle.refl _ _)).cycle_of_eq lemma is_cycle.cycle_of [fintype α] {f : perm α} (hf : is_cycle f) {x : α} : cycle_of f x = if f x = x then 1 else f := begin by_cases hx : f x = x, { rwa [if_pos hx, cycle_of_eq_one_iff] }, { rwa [if_neg hx, hf.cycle_of_eq] }, end lemma cycle_of_one [fintype α] (x : α) : cycle_of 1 x = 1 := (cycle_of_eq_one_iff 1).mpr rfl lemma is_cycle_cycle_of [fintype α] (f : perm α) {x : α} (hx : f x ≠ x) : is_cycle (cycle_of f x) := have cycle_of f x x ≠ x, by rwa [(same_cycle.refl _ _).cycle_of_apply], (same_cycle_cycle this).2 $ λ y, ⟨λ h, mt h.apply_eq_self_iff.2 this, λ h, if hxy : same_cycle f x y then let ⟨i, hi⟩ := hxy in ⟨i, by rw [cycle_of_zpow_apply_self, hi]⟩ else by { rw [cycle_of_apply_of_not_same_cycle hxy] at h, exact (h rfl).elim }⟩ @[simp] lemma two_le_card_support_cycle_of_iff [fintype α] {f : perm α} {x : α} : 2 ≤ card (cycle_of f x).support ↔ f x ≠ x := begin refine ⟨λ h, _, λ h, by simpa using (is_cycle_cycle_of _ h).two_le_card_support⟩, contrapose! h, rw ←cycle_of_eq_one_iff at h, simp [h] end @[simp] lemma card_support_cycle_of_pos_iff [fintype α] {f : perm α} {x : α} : 0 < card (cycle_of f x).support ↔ f x ≠ x := begin rw [←two_le_card_support_cycle_of_iff, ←nat.succ_le_iff], exact ⟨λ h, or.resolve_left h.eq_or_lt (card_support_ne_one _).symm, zero_lt_two.trans_le⟩ end lemma pow_apply_eq_pow_mod_order_of_cycle_of_apply [fintype α] (f : perm α) (n : ℕ) (x : α) : (f ^ n) x = (f ^ (n % order_of (cycle_of f x))) x := by rw [←cycle_of_pow_apply_self f, ←cycle_of_pow_apply_self f, pow_eq_mod_order_of] lemma cycle_of_mul_of_apply_right_eq_self [fintype α] {f g : perm α} (h : _root_.commute f g) (x : α) (hx : g x = x) : (f * g).cycle_of x = f.cycle_of x := begin ext y, by_cases hxy : (f * g).same_cycle x y, { obtain ⟨z, rfl⟩ := hxy, rw cycle_of_apply_apply_zpow_self, simp [h.mul_zpow, zpow_apply_eq_self_of_apply_eq_self hx] }, { rw [cycle_of_apply_of_not_same_cycle hxy, cycle_of_apply_of_not_same_cycle], contrapose! hxy, obtain ⟨z, rfl⟩ := hxy, refine ⟨z, _⟩, simp [h.mul_zpow, zpow_apply_eq_self_of_apply_eq_self hx] } end lemma disjoint.cycle_of_mul_distrib [fintype α] {f g : perm α} (h : f.disjoint g) (x : α) : (f * g).cycle_of x = (f.cycle_of x * g.cycle_of x) := begin cases (disjoint_iff_eq_or_eq.mp h) x with hfx hgx, { simp [h.commute.eq, cycle_of_mul_of_apply_right_eq_self h.symm.commute, hfx] }, { simp [cycle_of_mul_of_apply_right_eq_self h.commute, hgx] } end lemma support_cycle_of_eq_nil_iff [fintype α] {f : perm α} {x : α} : (f.cycle_of x).support = ∅ ↔ x ∉ f.support := by simp lemma support_cycle_of_le [fintype α] (f : perm α) (x : α) : support (f.cycle_of x) ≤ support f := begin intros y hy, rw [mem_support, cycle_of_apply] at hy, split_ifs at hy, { exact mem_support.mpr hy }, { exact absurd rfl hy } end lemma mem_support_cycle_of_iff [fintype α] {f : perm α} {x y : α} : y ∈ support (f.cycle_of x) ↔ same_cycle f x y ∧ x ∈ support f := begin by_cases hx : f x = x, { rw (cycle_of_eq_one_iff _).mpr hx, simp [hx] }, { rw [mem_support, cycle_of_apply], split_ifs with hy, { simp only [hx, hy, iff_true, ne.def, not_false_iff, and_self, mem_support], rcases hy with ⟨k, rfl⟩, rw ←not_mem_support, simpa using hx }, { simpa [hx] using hy } } end lemma same_cycle.mem_support_iff [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : x ∈ support f ↔ y ∈ support f := ⟨λ hx, support_cycle_of_le f x (mem_support_cycle_of_iff.mpr ⟨h, hx⟩), λ hy, support_cycle_of_le f y (mem_support_cycle_of_iff.mpr ⟨h.symm, hy⟩)⟩ lemma pow_mod_card_support_cycle_of_self_apply [fintype α] (f : perm α) (n : ℕ) (x : α) : (f ^ (n % (f.cycle_of x).support.card)) x = (f ^ n) x := begin by_cases hx : f x = x, { rw [pow_apply_eq_self_of_apply_eq_self hx, pow_apply_eq_self_of_apply_eq_self hx] }, { rw [←cycle_of_pow_apply_self, ←cycle_of_pow_apply_self f, ←order_of_is_cycle (is_cycle_cycle_of f hx), ←pow_eq_mod_order_of] } end /-- x is in the support of f iff cycle_of f x is a cycle.-/ lemma is_cycle_cycle_of_iff [fintype α] (f : perm α) {x : α} : is_cycle (cycle_of f x) ↔ (f x ≠ x) := begin split, { intro hx, rw ne.def, rw ← cycle_of_eq_one_iff f, exact equiv.perm.is_cycle.ne_one hx, }, { intro hx, apply equiv.perm.is_cycle_cycle_of, exact hx } end /-! ### `cycle_factors` -/ /-- Given a list `l : list α` and a permutation `f : perm α` whose nonfixed points are all in `l`, recursively factors `f` into cycles. -/ def cycle_factors_aux [fintype α] : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} | [] f h := ⟨[], by { simp only [imp_false, list.pairwise.nil, list.not_mem_nil, forall_const, and_true, forall_prop_of_false, not_not, not_false_iff, list.prod_nil] at *, ext, simp * }⟩ | (x::l) f h := if hx : f x = x then cycle_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h, hy (by rwa h)) (h hy)) else let ⟨m, hm₁, hm₂, hm₃⟩ := cycle_factors_aux l ((cycle_of f x)⁻¹ * f) (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by { rw [h, mul_apply, ne.def, inv_eq_iff_eq, cycle_of_apply_self] at hy, exact hy rfl }) (h (λ h : f y = y, by { rw [mul_apply, h, ne.def, inv_eq_iff_eq, cycle_of_apply] at hy, split_ifs at hy; cc }))) in ⟨(cycle_of f x) :: m, by { rw [list.prod_cons, hm₁], simp }, λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ hg, hg.symm ▸ is_cycle_cycle_of _ hx) (hm₂ g), list.pairwise_cons.2 ⟨λ g hg y, or_iff_not_imp_left.2 (λ hfy, have hxy : same_cycle f x y := not_not.1 (mt cycle_of_apply_of_not_same_cycle hfy), have hgm : g :: m.erase g ~ m := list.cons_perm_iff_perm_erase.2 ⟨hg, list.perm.refl _⟩, have ∀ h ∈ m.erase g, disjoint g h, from (list.pairwise_cons.1 ((hgm.pairwise_iff (λ a b (h : disjoint a b), h.symm)).2 hm₃)).1, classical.by_cases id $ λ hgy : g y ≠ y, (disjoint_prod_right _ this y).resolve_right $ have hsc : same_cycle f⁻¹ x (f y), by rwa [same_cycle_inv, same_cycle_apply], by { rw [disjoint_prod_perm hm₃ hgm.symm, list.prod_cons, ← eq_inv_mul_iff_mul_eq] at hm₁, rwa [hm₁, mul_apply, mul_apply, cycle_of_inv, hsc.cycle_of_apply, inv_apply_self, inv_eq_iff_eq, eq_comm] }), hm₃⟩⟩ lemma mem_list_cycles_iff {α : Type*} [fintype α] {l : list (perm α)} (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) {σ : perm α} : σ ∈ l ↔ σ.is_cycle ∧ ∀ (a : α) (h4 : σ a ≠ a), σ a = l.prod a := begin suffices : σ.is_cycle → (σ ∈ l ↔ ∀ (a : α) (h4 : σ a ≠ a), σ a = l.prod a), { exact ⟨λ hσ, ⟨h1 σ hσ, (this (h1 σ hσ)).mp hσ⟩, λ hσ, (this hσ.1).mpr hσ.2⟩ }, intro h3, classical, split, { intros h a ha, exact eq_on_support_mem_disjoint h h2 _ (mem_support.mpr ha) }, { intros h, have hσl : σ.support ⊆ l.prod.support, { intros x hx, rw mem_support at hx, rwa [mem_support, ←h _ hx] }, obtain ⟨a, ha, -⟩ := id h3, rw ←mem_support at ha, obtain ⟨τ, hτ, hτa⟩ := exists_mem_support_of_mem_support_prod (hσl ha), have hτl : ∀ (x ∈ τ.support), τ x = l.prod x := eq_on_support_mem_disjoint hτ h2, have key : ∀ (x ∈ σ.support ∩ τ.support), σ x = τ x, { intros x hx, rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hτl x (mem_of_mem_inter_right hx)] }, convert hτ, refine h3.eq_on_support_inter_nonempty_congr (h1 _ hτ) key _ ha, exact key a (mem_inter_of_mem ha hτa) } end lemma list_cycles_perm_list_cycles {α : Type*} [fintype α] {l₁ l₂ : list (perm α)} (h₀ : l₁.prod = l₂.prod) (h₁l₁ : ∀ σ : perm α, σ ∈ l₁ → σ.is_cycle) (h₁l₂ : ∀ σ : perm α, σ ∈ l₂ → σ.is_cycle) (h₂l₁ : l₁.pairwise disjoint) (h₂l₂ : l₂.pairwise disjoint) : l₁ ~ l₂ := begin classical, refine (list.perm_ext (nodup_of_pairwise_disjoint_cycles h₁l₁ h₂l₁) (nodup_of_pairwise_disjoint_cycles h₁l₂ h₂l₂)).mpr (λ σ, _), by_cases hσ : σ.is_cycle, { obtain ⟨a, ha⟩ := not_forall.mp (mt ext hσ.ne_one), rw [mem_list_cycles_iff h₁l₁ h₂l₁, mem_list_cycles_iff h₁l₂ h₂l₂, h₀] }, { exact iff_of_false (mt (h₁l₁ σ) hσ) (mt (h₁l₂ σ) hσ) } end /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors [fintype α] [linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} := cycle_factors_aux (univ.sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`, without a linear order. -/ def trunc_cycle_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (cycle_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) section cycle_factors_finset variables [fintype α] (f : perm α) /-- Factors a permutation `f` into a `finset` of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors_finset : finset (perm α) := (trunc_cycle_factors f).lift (λ (l : {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint}), l.val.to_finset) (λ ⟨l, hl⟩ ⟨l', hl'⟩, list.to_finset_eq_of_perm _ _ (list_cycles_perm_list_cycles (hl'.left.symm ▸ hl.left) hl.right.left (hl'.right.left) hl.right.right hl'.right.right)) lemma cycle_factors_finset_eq_list_to_finset {σ : perm α} {l : list (perm α)} (hn : l.nodup) : σ.cycle_factors_finset = l.to_finset ↔ (∀ f : perm α, f ∈ l → f.is_cycle) ∧ l.pairwise disjoint ∧ l.prod = σ := begin obtain ⟨⟨l', hp', hc', hd'⟩, hl⟩ := trunc.exists_rep σ.trunc_cycle_factors, have ht : cycle_factors_finset σ = l'.to_finset, { rw [cycle_factors_finset, ←hl, trunc.lift_mk] }, rw ht, split, { intro h, have hn' : l'.nodup := nodup_of_pairwise_disjoint_cycles hc' hd', have hperm : l ~ l' := list.perm_of_nodup_nodup_to_finset_eq hn hn' h.symm, refine ⟨_, _, _⟩, { exact λ _ h, hc' _ (hperm.subset h)}, { rwa list.perm.pairwise_iff disjoint.symmetric hperm }, { rw [←hp', hperm.symm.prod_eq'], refine hd'.imp _, exact λ _ _, disjoint.commute } }, { rintro ⟨hc, hd, hp⟩, refine list.to_finset_eq_of_perm _ _ _, refine list_cycles_perm_list_cycles _ hc' hc hd' hd, rw [hp, hp'] } end lemma cycle_factors_finset_eq_finset {σ : perm α} {s : finset (perm α)} : σ.cycle_factors_finset = s ↔ (∀ f : perm α, f ∈ s → f.is_cycle) ∧ (∃ h : (∀ (a ∈ s) (b ∈ s), a ≠ b → disjoint a b), s.noncomm_prod id (λ a ha b hb, (em (a = b)).by_cases (λ h, h ▸ commute.refl a) (set.pairwise.mono' (λ _ _, disjoint.commute) h ha hb)) = σ) := begin obtain ⟨l, hl, rfl⟩ := s.exists_list_nodup_eq, rw cycle_factors_finset_eq_list_to_finset hl, simp only [noncomm_prod_to_finset, hl, exists_prop, list.mem_to_finset, and.congr_left_iff, and.congr_right_iff, list.map_id, ne.def], intros, exact ⟨list.pairwise.forall disjoint.symmetric, hl.pairwise_of_forall_ne⟩ end lemma cycle_factors_finset_pairwise_disjoint (p : perm α) (hp : p ∈ cycle_factors_finset f) (q : perm α) (hq : q ∈ cycle_factors_finset f) (h : p ≠ q) : disjoint p q := begin have : f.cycle_factors_finset = f.cycle_factors_finset := rfl, obtain ⟨-, hd, -⟩ := cycle_factors_finset_eq_finset.mp this, exact hd p hp q hq h end lemma cycle_factors_finset_mem_commute (p : perm α) (hp : p ∈ cycle_factors_finset f) (q : perm α) (hq : q ∈ cycle_factors_finset f) : _root_.commute p q := begin by_cases h : p = q, { exact h ▸ commute.refl _ }, { exact (cycle_factors_finset_pairwise_disjoint _ _ hp _ hq h).commute } end /-- The product of cycle factors is equal to the original `f : perm α`. -/ lemma cycle_factors_finset_noncomm_prod (comm : ∀ (g ∈ f.cycle_factors_finset) (h ∈ f.cycle_factors_finset), commute (id g) (id h) := cycle_factors_finset_mem_commute f) : f.cycle_factors_finset.noncomm_prod id (comm) = f := begin have : f.cycle_factors_finset = f.cycle_factors_finset := rfl, obtain ⟨-, hd, hp⟩ := cycle_factors_finset_eq_finset.mp this, exact hp end lemma mem_cycle_factors_finset_iff {f p : perm α} : p ∈ cycle_factors_finset f ↔ p.is_cycle ∧ ∀ (a ∈ p.support), p a = f a := begin obtain ⟨l, hl, hl'⟩ := f.cycle_factors_finset.exists_list_nodup_eq, rw ←hl', rw [eq_comm, cycle_factors_finset_eq_list_to_finset hl] at hl', simpa [list.mem_to_finset, ne.def, ←hl'.right.right] using mem_list_cycles_iff hl'.left hl'.right.left end lemma cycle_of_mem_cycle_factors_finset_iff {f : perm α} {x : α} : cycle_of f x ∈ cycle_factors_finset f ↔ x ∈ f.support := begin rw mem_cycle_factors_finset_iff, split, { rintro ⟨hc, h⟩, contrapose! hc, rw [not_mem_support, ←cycle_of_eq_one_iff] at hc, simp [hc] }, { intros hx, refine ⟨is_cycle_cycle_of _ (mem_support.mp hx), _⟩, intros y hy, rw mem_support at hy, rw cycle_of_apply, split_ifs with H, { refl }, { rw cycle_of_apply_of_not_same_cycle H at hy, contradiction } } end lemma mem_cycle_factors_finset_support_le {p f : perm α} (h : p ∈ cycle_factors_finset f) : p.support ≤ f.support := begin rw mem_cycle_factors_finset_iff at h, intros x hx, rwa [mem_support, ←h.right x hx, ←mem_support] end lemma cycle_factors_finset_eq_empty_iff {f : perm α} : cycle_factors_finset f = ∅ ↔ f = 1 := by simpa [cycle_factors_finset_eq_finset] using eq_comm @[simp] lemma cycle_factors_finset_one : cycle_factors_finset (1 : perm α) = ∅ := by simp [cycle_factors_finset_eq_empty_iff] @[simp] lemma cycle_factors_finset_eq_singleton_self_iff {f : perm α} : f.cycle_factors_finset = {f} ↔ f.is_cycle := by simp [cycle_factors_finset_eq_finset] lemma is_cycle.cycle_factors_finset_eq_singleton {f : perm α} (hf : is_cycle f) : f.cycle_factors_finset = {f} := cycle_factors_finset_eq_singleton_self_iff.mpr hf lemma cycle_factors_finset_eq_singleton_iff {f g : perm α} : f.cycle_factors_finset = {g} ↔ f.is_cycle ∧ f = g := begin suffices : f = g → (g.is_cycle ↔ f.is_cycle), { simpa [cycle_factors_finset_eq_finset, eq_comm] }, rintro rfl, exact iff.rfl end /-- Two permutations `f g : perm α` have the same cycle factors iff they are the same. -/ lemma cycle_factors_finset_injective : function.injective (@cycle_factors_finset α _ _) := begin intros f g h, rw ←cycle_factors_finset_noncomm_prod f, simpa [h] using cycle_factors_finset_noncomm_prod g end lemma disjoint.disjoint_cycle_factors_finset {f g : perm α} (h : disjoint f g) : _root_.disjoint (cycle_factors_finset f) (cycle_factors_finset g) := begin rw disjoint_iff_disjoint_support at h, intros x hx, simp only [mem_cycle_factors_finset_iff, inf_eq_inter, mem_inter, mem_support] at hx, obtain ⟨⟨⟨a, ha, -⟩, hf⟩, -, hg⟩ := hx, refine h (_ : a ∈ f.support ∩ g.support), simp [ha, ←hf a ha, ←hg a ha] end lemma disjoint.cycle_factors_finset_mul_eq_union {f g : perm α} (h : disjoint f g) : cycle_factors_finset (f * g) = cycle_factors_finset f ∪ cycle_factors_finset g := begin rw cycle_factors_finset_eq_finset, split, { simp only [mem_cycle_factors_finset_iff, mem_union], rintro _ (⟨h, -⟩ | ⟨h, -⟩); exact h }, { refine ⟨_, _⟩, { simp_rw mem_union, rintros x (hx | hx) y (hy | hy) hxy, { exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy }, { exact h.mono (mem_cycle_factors_finset_support_le hx) (mem_cycle_factors_finset_support_le hy) }, { exact h.symm.mono (mem_cycle_factors_finset_support_le hx) (mem_cycle_factors_finset_support_le hy) }, { exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy } }, { rw noncomm_prod_union_of_disjoint h.disjoint_cycle_factors_finset, rw [cycle_factors_finset_noncomm_prod, cycle_factors_finset_noncomm_prod] } } end lemma disjoint_mul_inv_of_mem_cycle_factors_finset {f g : perm α} (h : f ∈ cycle_factors_finset g) : disjoint (g * f⁻¹) f := begin rw mem_cycle_factors_finset_iff at h, intro x, by_cases hx : f x = x, { exact or.inr hx }, { refine or.inl _, rw [mul_apply, ←h.right, apply_inv_self], rwa [←support_inv, apply_mem_support, support_inv, mem_support] } end /-- If c is a cycle, a ∈ c.support and c is a cycle of f, then `c = f.cycle_of a` -/ lemma cycle_is_cycle_of {f c : equiv.perm α} {a : α} (ha : a ∈ c.support) (hc : c ∈ f.cycle_factors_finset) : c = f.cycle_of a := begin suffices : f.cycle_of a = c.cycle_of a, { rw this, apply symm, exact equiv.perm.is_cycle.cycle_of_eq ((equiv.perm.mem_cycle_factors_finset_iff.mp hc).left) (equiv.perm.mem_support.mp ha), }, let hfc := (equiv.perm.disjoint_mul_inv_of_mem_cycle_factors_finset hc).symm, let hfc2 := (perm.disjoint.commute hfc), rw ← equiv.perm.cycle_of_mul_of_apply_right_eq_self hfc2, simp only [hfc2.eq, inv_mul_cancel_right], -- a est dans le support de c, donc pas dans celui de g c⁻¹ exact equiv.perm.not_mem_support.mp (finset.disjoint_left.mp (equiv.perm.disjoint.disjoint_support hfc) ha), end end cycle_factors_finset @[elab_as_eliminator] lemma cycle_induction_on [fintype β] (P : perm β → Prop) (σ : perm β) (base_one : P 1) (base_cycles : ∀ σ : perm β, σ.is_cycle → P σ) (induction_disjoint : ∀ σ τ : perm β, disjoint σ τ → is_cycle σ → P σ → P τ → P (σ * τ)) : P σ := begin suffices : ∀ l : list (perm β), (∀ τ : perm β, τ ∈ l → τ.is_cycle) → l.pairwise disjoint → P l.prod, { classical, let x := σ.trunc_cycle_factors.out, exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2) }, intro l, induction l with σ l ih, { exact λ _ _, base_one }, { intros h1 h2, rw list.prod_cons, exact induction_disjoint σ l.prod (disjoint_prod_right _ (list.pairwise_cons.mp h2).1) (h1 _ (list.mem_cons_self _ _)) (base_cycles σ (h1 σ (l.mem_cons_self σ))) (ih (λ τ hτ, h1 τ (list.mem_cons_of_mem σ hτ)) h2.of_cons) } end lemma cycle_factors_finset_mul_inv_mem_eq_sdiff [fintype α] {f g : perm α} (h : f ∈ cycle_factors_finset g) : cycle_factors_finset (g * f⁻¹) = (cycle_factors_finset g) \ {f} := begin revert f, apply cycle_induction_on _ g, { simp }, { intros σ hσ f hf, simp only [cycle_factors_finset_eq_singleton_self_iff.mpr hσ, mem_singleton] at hf ⊢, simp [hf] }, { intros σ τ hd hc hσ hτ f, simp_rw [hd.cycle_factors_finset_mul_eq_union, mem_union], -- if only `wlog` could work here... rintro (hf | hf), { rw [hd.commute.eq, union_comm, union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hσ hf], { rw mem_cycle_factors_finset_iff at hf, intro x, cases hd.symm x with hx hx, { exact or.inl hx }, { refine or.inr _, by_cases hfx : f x = x, { rw ←hfx, simpa [hx] using hfx.symm }, { rw mul_apply, rw ←hf.right _ (mem_support.mpr hfx) at hx, contradiction } } }, { exact λ H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem hf H) } }, { rw [union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hτ hf], { rw mem_cycle_factors_finset_iff at hf, intro x, cases hd x with hx hx, { exact or.inl hx }, { refine or.inr _, by_cases hfx : f x = x, { rw ←hfx, simpa [hx] using hfx.symm }, { rw mul_apply, rw ←hf.right _ (mem_support.mpr hfx) at hx, contradiction } } }, { exact λ H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem H hf) } } } end lemma same_cycle.nat_of_mem_support [fintype α] (f : perm α) {x y : α} (h : same_cycle f x y) (hx : x ∈ f.support) : ∃ (i : ℕ) (hi' : i < (f.cycle_of x).support.card), (f ^ i) x = y := begin revert f, intro f, apply cycle_induction_on _ f, { simp }, { intros g hg H hx, rw mem_support at hx, rw [hg.cycle_of_eq hx, ←order_of_is_cycle hg], exact H.nat' }, { rintros g h hd hg IH IH' ⟨m, rfl⟩ hx, cases (disjoint_iff_eq_or_eq.mp hd) x with hgx hhx, { have hpow : ∀ (k : ℤ), ((g * h) ^ k) x = (h ^ k) x, { intro k, suffices : (g ^ k) x = x, { simpa [hd.commute.eq, hd.commute.symm.mul_zpow] }, rw zpow_apply_eq_self_of_apply_eq_self, simpa using hgx }, obtain ⟨k, hk, hk'⟩ := IH' _ _, { refine ⟨k, _, _⟩, { rw [←cycle_of_eq_one_iff] at hgx, rwa [hd.cycle_of_mul_distrib, hgx, one_mul] }, { simpa [←zpow_coe_nat, hpow] using hk' } }, { use m, simp [hpow] }, { rw [mem_support, hd.commute.eq] at hx, simpa [hgx] using hx } }, { have hpow : ∀ (k : ℤ), ((g * h) ^ k) x = (g ^ k) x, { intro k, suffices : (h ^ k) x = x, { simpa [hd.commute.mul_zpow] }, rw zpow_apply_eq_self_of_apply_eq_self, simpa using hhx }, obtain ⟨k, hk, hk'⟩ := IH _ _, { refine ⟨k, _, _⟩, { rw [←cycle_of_eq_one_iff] at hhx, rwa [hd.cycle_of_mul_distrib, hhx, mul_one] }, { simpa [←zpow_coe_nat, hpow] using hk' } }, { use m, simp [hpow] }, { simpa [hhx] using hx } } } end lemma same_cycle.nat [fintype α] (f : perm α) {x y : α} (h : same_cycle f x y) : ∃ (i : ℕ) (hi : 0 < i) (hi' : i ≤ (f.cycle_of x).support.card + 1), (f ^ i) x = y := begin by_cases hx : x ∈ f.support, { obtain ⟨k, hk, hk'⟩ := same_cycle.nat_of_mem_support f h hx, cases k, { refine ⟨(f.cycle_of x).support.card, _, self_le_add_right _ _, _⟩, { refine zero_lt_one.trans (one_lt_card_support_of_ne_one _), simpa using hx }, { simp only [perm.coe_one, id.def, pow_zero] at hk', subst hk', rw [←order_of_is_cycle (is_cycle_cycle_of _ (mem_support.mp hx)), ←cycle_of_pow_apply_self, pow_order_of_eq_one, one_apply] } }, { exact ⟨k + 1, by simp, nat.le_succ_of_le hk.le, hk'⟩ } }, { refine ⟨1, zero_lt_one, by simp, _⟩, obtain ⟨k, rfl⟩ := h, rw [not_mem_support] at hx, rw [pow_apply_eq_self_of_apply_eq_self hx, zpow_apply_eq_self_of_apply_eq_self hx] } end section generation variables [fintype α] [fintype β] open subgroup lemma closure_is_cycle : closure {σ : perm β | is_cycle σ} = ⊤ := begin classical, exact top_le_iff.mp (le_trans (ge_of_eq closure_is_swap) (closure_mono (λ _, is_swap.is_cycle))), end lemma closure_cycle_adjacent_swap {σ : perm α} (h1 : is_cycle σ) (h2 : σ.support = ⊤) (x : α) : closure ({σ, swap x (σ x)} : set (perm α)) = ⊤ := begin let H := closure ({σ, swap x (σ x)} : set (perm α)), have h3 : σ ∈ H := subset_closure (set.mem_insert σ _), have h4 : swap x (σ x) ∈ H := subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)), have step1 : ∀ (n : ℕ), swap ((σ ^ n) x) ((σ^(n+1)) x) ∈ H, { intro n, induction n with n ih, { exact subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)) }, { convert H.mul_mem (H.mul_mem h3 ih) (H.inv_mem h3), rw [mul_swap_eq_swap_mul, mul_inv_cancel_right], refl } }, have step2 : ∀ (n : ℕ), swap x ((σ ^ n) x) ∈ H, { intro n, induction n with n ih, { convert H.one_mem, exact swap_self x }, { by_cases h5 : x = (σ ^ n) x, { rw [pow_succ, mul_apply, ←h5], exact h4 }, by_cases h6 : x = (σ^(n+1)) x, { rw [←h6, swap_self], exact H.one_mem }, rw [swap_comm, ←swap_mul_swap_mul_swap h5 h6], exact H.mul_mem (H.mul_mem (step1 n) ih) (step1 n) } }, have step3 : ∀ (y : α), swap x y ∈ H, { intro y, have hx : x ∈ (⊤ : finset α) := finset.mem_univ x, rw [←h2, mem_support] at hx, have hy : y ∈ (⊤ : finset α) := finset.mem_univ y, rw [←h2, mem_support] at hy, cases is_cycle.exists_pow_eq h1 hx hy with n hn, rw ← hn, exact step2 n }, have step4 : ∀ (y z : α), swap y z ∈ H, { intros y z, by_cases h5 : z = x, { rw [h5, swap_comm], exact step3 y }, by_cases h6 : z = y, { rw [h6, swap_self], exact H.one_mem }, rw [←swap_mul_swap_mul_swap h5 h6, swap_comm z x], exact H.mul_mem (H.mul_mem (step3 y) (step3 z)) (step3 y) }, rw [eq_top_iff, ←closure_is_swap, closure_le], rintros τ ⟨y, z, h5, h6⟩, rw h6, exact step4 y z, end lemma closure_cycle_coprime_swap {n : ℕ} {σ : perm α} (h0 : nat.coprime n (fintype.card α)) (h1 : is_cycle σ) (h2 : σ.support = finset.univ) (x : α) : closure ({σ, swap x ((σ ^ n) x)} : set (perm α)) = ⊤ := begin rw [←finset.card_univ, ←h2, ←order_of_is_cycle h1] at h0, cases exists_pow_eq_self_of_coprime h0 with m hm, have h2' : (σ ^ n).support = ⊤ := eq.trans (support_pow_coprime h0) h2, have h1' : is_cycle ((σ ^ n) ^ (m : ℤ)) := by rwa ← hm at h1, replace h1' : is_cycle (σ ^ n) := is_cycle_of_is_cycle_pow h1' (le_trans (support_pow_le σ n) (ge_of_eq (congr_arg support hm))), rw [eq_top_iff, ←closure_cycle_adjacent_swap h1' h2' x, closure_le, set.insert_subset], exact ⟨subgroup.pow_mem (closure _) (subset_closure (set.mem_insert σ _)) n, set.singleton_subset_iff.mpr (subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)))⟩, end lemma closure_prime_cycle_swap {σ τ : perm α} (h0 : (fintype.card α).prime) (h1 : is_cycle σ) (h2 : σ.support = finset.univ) (h3 : is_swap τ) : closure ({σ, τ} : set (perm α)) = ⊤ := begin obtain ⟨x, y, h4, h5⟩ := h3, obtain ⟨i, hi⟩ := h1.exists_pow_eq (mem_support.mp ((finset.ext_iff.mp h2 x).mpr (finset.mem_univ x))) (mem_support.mp ((finset.ext_iff.mp h2 y).mpr (finset.mem_univ y))), rw [h5, ←hi], refine closure_cycle_coprime_swap (nat.coprime.symm (h0.coprime_iff_not_dvd.mpr (λ h, h4 _))) h1 h2 x, cases h with m hm, rwa [hm, pow_mul, ←finset.card_univ, ←h2, ←order_of_is_cycle h1, pow_order_of_eq_one, one_pow, one_apply] at hi, end end generation section variables [fintype α] {σ τ : perm α} noncomputable theory lemma is_conj_of_support_equiv (f : {x // x ∈ (σ.support : set α)} ≃ {x // x ∈ (τ.support : set α)}) (hf : ∀ (x : α) (hx : x ∈ (σ.support : set α)), (f ⟨σ x, apply_mem_support.2 hx⟩ : α) = τ ↑(f ⟨x,hx⟩)) : is_conj σ τ := begin refine is_conj_iff.2 ⟨equiv.extend_subtype f, _⟩, rw mul_inv_eq_iff_eq_mul, ext, simp only [perm.mul_apply], by_cases hx : x ∈ σ.support, { rw [equiv.extend_subtype_apply_of_mem, equiv.extend_subtype_apply_of_mem], { exact hf x (finset.mem_coe.2 hx) } }, { rwa [not_not.1 ((not_congr mem_support).1 (equiv.extend_subtype_not_mem f _ _)), not_not.1 ((not_congr mem_support).mp hx)] } end theorem is_cycle.is_conj (hσ : is_cycle σ) (hτ : is_cycle τ) (h : σ.support.card = τ.support.card) : is_conj σ τ := begin refine is_conj_of_support_equiv (hσ.zpowers_equiv_support.symm.trans ((zpowers_equiv_zpowers begin rw [order_of_is_cycle hσ, h, order_of_is_cycle hτ], end).trans hτ.zpowers_equiv_support)) _, intros x hx, simp only [perm.mul_apply, equiv.trans_apply, equiv.sum_congr_apply], obtain ⟨n, rfl⟩ := hσ.exists_pow_eq (classical.some_spec hσ).1 (mem_support.1 hx), apply eq.trans _ (congr rfl (congr rfl (congr rfl (congr rfl (hσ.zpowers_equiv_support_symm_apply n).symm)))), apply (congr rfl (congr rfl (congr rfl (hσ.zpowers_equiv_support_symm_apply (n + 1))))).trans _, simp only [ne.def, is_cycle.zpowers_equiv_support_apply, subtype.coe_mk, zpowers_equiv_zpowers_apply], rw [pow_succ, perm.mul_apply], end theorem is_cycle.is_conj_iff (hσ : is_cycle σ) (hτ : is_cycle τ) : is_conj σ τ ↔ σ.support.card = τ.support.card := ⟨begin intro h, obtain ⟨π, rfl⟩ := is_conj_iff.1 h, apply finset.card_congr (λ a ha, π a) (λ _ ha, _) (λ _ _ _ _ ab, π.injective ab) (λ b hb, _), { simp [mem_support.1 ha] }, { refine ⟨π⁻¹ b, ⟨_, π.apply_inv_self b⟩⟩, contrapose! hb, rw [mem_support, not_not] at hb, rw [mem_support, not_not, perm.mul_apply, perm.mul_apply, hb, perm.apply_inv_self] } end, hσ.is_conj hτ⟩ @[simp] lemma support_conj : (σ * τ * σ⁻¹).support = τ.support.map σ.to_embedding := begin ext, simp only [mem_map_equiv, perm.coe_mul, comp_app, ne.def, perm.mem_support, equiv.eq_symm_apply], refl, end lemma card_support_conj : (σ * τ * σ⁻¹).support.card = τ.support.card := by simp end theorem disjoint.is_conj_mul {α : Type*} [fintype α] {σ τ π ρ : perm α} (hc1 : is_conj σ π) (hc2 : is_conj τ ρ) (hd1 : disjoint σ τ) (hd2 : disjoint π ρ) : is_conj (σ * τ) (π * ρ) := begin classical, obtain ⟨f, rfl⟩ := is_conj_iff.1 hc1, obtain ⟨g, rfl⟩ := is_conj_iff.1 hc2, have hd1' := coe_inj.2 hd1.support_mul, have hd2' := coe_inj.2 hd2.support_mul, rw [coe_union] at *, have hd1'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd1), have hd2'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd2), refine is_conj_of_support_equiv _ _, { refine ((equiv.set.of_eq hd1').trans (equiv.set.union hd1'')).trans ((equiv.sum_congr (subtype_equiv f (λ a, _)) (subtype_equiv g (λ a, _))).trans ((equiv.set.of_eq hd2').trans (equiv.set.union hd2'')).symm); { simp only [set.mem_image, to_embedding_apply, exists_eq_right, support_conj, coe_map, apply_eq_iff_eq] } }, { intros x hx, simp only [trans_apply, symm_trans_apply, set.of_eq_apply, set.of_eq_symm_apply, equiv.sum_congr_apply], rw [hd1', set.mem_union] at hx, cases hx with hxσ hxτ, { rw [mem_coe, mem_support] at hxσ, rw [set.union_apply_left hd1'' _, set.union_apply_left hd1'' _], simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inl, comp_app, set.union_symm_apply_left, subtype.coe_mk, apply_eq_iff_eq], { have h := (hd2 (f x)).resolve_left _, { rw [mul_apply, mul_apply] at h, rw [h, inv_apply_self, (hd1 x).resolve_left hxσ] }, { rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } }, { rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, mem_support] }, { rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply, (hd1 x).resolve_left hxσ, mem_coe, apply_mem_support, mem_support] } }, { rw [mem_coe, ← apply_mem_support, mem_support] at hxτ, rw [set.union_apply_right hd1'' _, set.union_apply_right hd1'' _], simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inr, comp_app, set.union_symm_apply_right, subtype.coe_mk, apply_eq_iff_eq], { have h := (hd2 (g (τ x))).resolve_right _, { rw [mul_apply, mul_apply] at h, rw [inv_apply_self, h, (hd1 (τ x)).resolve_right hxτ] }, { rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } }, { rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, ← apply_mem_support, mem_support] }, { rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply, (hd1 (τ x)).resolve_right hxτ, mem_coe, mem_support] } } } end section fixed_points /-! ### Fixed points -/ lemma fixed_point_card_lt_of_ne_one [fintype α] {σ : perm α} (h : σ ≠ 1) : (filter (λ x, σ x = x) univ).card < fintype.card α - 1 := begin rw [lt_tsub_iff_left, ← lt_tsub_iff_right, ← finset.card_compl, finset.compl_filter], exact one_lt_card_support_of_ne_one h end end fixed_points end equiv.perm
eeb94e2d89bdbf0332cd3808d63d581d4271c200
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/factorial.lean
b9c78ce43a9a05da76dbf15a3ae5de683e5a75ba
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,955
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.basic import Mathlib.PostPort namespace Mathlib /-! # The factorial function -/ namespace nat /-- `nat.factorial n` is the factorial of `n`. -/ @[simp] def factorial : ℕ → ℕ := sorry @[simp] theorem factorial_zero : factorial 0 = factorial 1 := rfl @[simp] theorem factorial_succ (n : ℕ) : factorial (Nat.succ n) = Nat.succ n * factorial n := rfl @[simp] theorem factorial_one : factorial 1 = 1 := rfl theorem mul_factorial_pred {n : ℕ} (hn : 0 < n) : n * factorial (n - 1) = factorial n := nat.sub_add_cancel hn ▸ rfl theorem factorial_pos (n : ℕ) : 0 < factorial n := sorry theorem factorial_ne_zero (n : ℕ) : factorial n ≠ 0 := ne_of_gt (factorial_pos n) theorem factorial_dvd_factorial {m : ℕ} {n : ℕ} (h : m ≤ n) : factorial m ∣ factorial n := sorry theorem dvd_factorial {m : ℕ} {n : ℕ} : 0 < m → m ≤ n → m ∣ factorial n := sorry theorem factorial_le {m : ℕ} {n : ℕ} (h : m ≤ n) : factorial m ≤ factorial n := le_of_dvd (factorial_pos n) (factorial_dvd_factorial h) theorem factorial_mul_pow_le_factorial {m : ℕ} {n : ℕ} : factorial m * Nat.succ m ^ n ≤ factorial (m + n) := sorry theorem monotone_factorial : monotone factorial := fun (n m : ℕ) => factorial_le theorem factorial_lt {m : ℕ} {n : ℕ} (h0 : 0 < n) : factorial n < factorial m ↔ n < m := sorry theorem one_lt_factorial {n : ℕ} : 1 < factorial n ↔ 1 < n := sorry theorem factorial_eq_one {n : ℕ} : factorial n = 1 ↔ n ≤ 1 := sorry theorem factorial_inj {m : ℕ} {n : ℕ} (h0 : 1 < factorial n) : factorial n = factorial m ↔ n = m := sorry theorem self_le_factorial (n : ℕ) : n ≤ factorial n := sorry
9974cf2c9e692178056877f79bf7160e952f8452
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/constructions.lean
3f5cd153cf1a528137f916535f28f6f730c0bcd9
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
33,103
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_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ := eq_univ_of_forall $ λ x, begin rw mem_closure_iff, intros U U_op x_in_U, let V := quotient.mk ⁻¹' U, cases quotient.exists_rep x with y y_x, have y_in_V : y ∈ V, by simp only [mem_preimage, y_x, x_in_U], have V_op : is_open V := U_op, obtain ⟨w, w_in_V, w_in_range⟩ : (V ∩ s).nonempty := mem_closure_iff.1 (H y) V V_op y_in_V, exact ⟨_, w_in_V, mem_image_of_mem quotient.mk w_in_range⟩ end 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 δ] 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 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 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) 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 is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = filter.prod (𝓝 a) (𝓝 b) := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] 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_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := by rw [nhds_prod_eq]; exact prod_mem_prod 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_fst.continuous_at).prod (hg.comp continuous_snd.continuous_at) 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*} {β : 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 ▸ is_open_prod hs 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 [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end /-- 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 α β) := begin assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₁, refine ⟨o₁, _, o₁_open, yo₁⟩, assume z zs, rw mem_image_eq, exact ⟨(z, y₂), ho (by simp [zs, yo₂]), rfl⟩ end /-- 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 α β) := begin /- This lemma could be proved by composing the fact that the first projection is open, and exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/ assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₂, refine ⟨o₂, _, o₂_open, yo₂⟩, assume z zs, rw mem_image_eq, exact ⟨(y₁, z), ho (by simp [zs, yo₁]), rfl⟩ end /-- 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 [st.1.ne_empty, st.2.ne_empty] at H, exact is_open_prod H.1 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 filter.prod (𝓝 a) (𝓝 b) ⊓ 𝓟 (set.prod s t) = filter.prod (𝓝 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 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 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] 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 γ] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_sup_dom hf hg 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 open_embedding_inl : open_embedding (inl : α → α ⊕ β) := { open_range := begin rw is_open_sum_iff, convert and.intro is_open_univ is_open_empty; { ext, simp } end, .. embedding_inl } lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) := { open_range := begin rw is_open_sum_iff, convert and.intro is_open_empty is_open_univ; { ext, simp } end, .. 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 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 } 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_eq $ 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_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, embedding_is_closed embedding_subtype_coe (by simp [subtype.range_coe]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ 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 $ assume x y, subtype.eq 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⟩ lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng 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*} 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 lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom /-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is continuous. -/ lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} : continuous (λ x : π i, function.update f i x) := begin refine continuous_pi (λj, _), by_cases h : j = i, { rw h, simpa using continuous_id }, { simpa [h] using continuous_const } end 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 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, continuous_apply a _ $ 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} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in 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 end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] 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) := 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. -/ 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)) 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 ⟨⟨_⟩, sigma_map_injective function.injective_id (λ 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 lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom 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₂
64c87833322f3a67a38aa1e640803f75118c88f7
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/topology/uniform_space/cauchy.lean
288815801c424137e8edaa3cbf334a3aa874a6c0
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
25,084
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 Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets. -/ import topology.uniform_space.basic topology.bases data.set.intervals universes u v open filter topological_space set classical open_locale classical variables {α : Type u} {β : Type v} [uniform_space α] open_locale uniformity topological_space /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ (𝓤 α) /-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f` has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/ def is_complete (s : set α) := ∀f, cauchy f → f ≤ principal s → ∃x∈s, f ≤ 𝓝 x lemma filter.has_basis.cauchy_iff {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀ i, p i → ∃ t ∈ f, ∀ x y ∈ t, (x, y) ∈ s i)) := and_congr iff.rfl $ (f.basis_sets.prod_self.le_basis_iff h).trans $ by simp only [subset_def, prod.forall, mem_prod_eq, and_imp, id] lemma cauchy_iff' {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀ s ∈ 𝓤 α, ∃t∈f, ∀ x y ∈ t, (x, y) ∈ s)) := (𝓤 α).basis_sets.cauchy_iff lemma cauchy_iff {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀ s ∈ 𝓤 α, ∃t∈f, (set.prod t t) ⊆ s)) := (𝓤 α).basis_sets.cauchy_iff.trans $ by simp only [subset_def, prod.forall, mem_prod_eq, and_imp, id] lemma cauchy_map_iff {l : filter β} {f : β → α} : cauchy (l.map f) ↔ (l ≠ ⊥ ∧ tendsto (λp:β×β, (f p.1, f p.2)) (l.prod l) (𝓤 α)) := by rw [cauchy, (≠), map_eq_bot_iff, prod_map_map_eq]; refl lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (𝓝 a) := ⟨nhds_ne_bot, calc filter.prod (𝓝 a) (𝓝 a) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ (𝓤 α).lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ 𝓤 α : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds pure_ne_bot (pure_le_nhds a) /-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and `sequentially_complete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s` one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y` with `(x, y) ∈ s`, then `f` converges to `x`. -/ lemma le_nhds_of_cauchy_adhp_aux {f : filter α} {x : α} (adhs : ∀ s ∈ 𝓤 α, ∃ t ∈ f, (set.prod t t ⊆ s) ∧ ∃ y, (y ∈ t) ∧ (x, y) ∈ s) : f ≤ 𝓝 x := begin -- Consider a neighborhood `s` of `x` assume s hs, -- Take an entourage twice smaller than `s` rcases comp_mem_uniformity_sets (mem_nhds_uniformity_iff.1 hs) with ⟨U, U_mem, hU⟩, -- Take a set `t ∈ f`, `t × t ⊆ U`, and a point `y ∈ t` such that `(x, y) ∈ U` rcases adhs U U_mem with ⟨t, t_mem, ht, y, hy, hxy⟩, apply mem_sets_of_superset t_mem, -- Given a point `z ∈ t`, we have `(x, y) ∈ U` and `(y, z) ∈ t × t ⊆ U`, hence `z ∈ s` exact (λ z hz, hU (prod_mk_mem_comp_rel hxy (ht $ mk_mem_prod hy hz)) rfl) end /-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point for `f`. -/ lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ 𝓝 x ≠ ⊥) : f ≤ 𝓝 x := le_nhds_of_cauchy_adhp_aux begin assume s hs, -- Take `t ∈ f` such that `t × t ⊆ s`. rcases (cauchy_iff.1 hf).2 s hs with ⟨t, t_mem, ht⟩, use [t, t_mem, ht], exact (forall_sets_nonempty_iff_ne_bot.2 adhs _ (inter_mem_inf_sets t_mem (mem_nhds_left x hs))) end lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ 𝓝 x ↔ f ⊓ 𝓝 x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) (𝓤 α) : map_mono hf.right ... ≤ 𝓤 β : hm⟩ lemma cauchy_comap [uniform_space β] {f : filter β} {m : α → β} (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) (hf : cauchy f) (hb : comap m f ≠ ⊥) : cauchy (comap m f) := ⟨hb, calc filter.prod (comap m f) (comap m f) = comap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) : comap_mono hf.right ... ≤ 𝓤 α : hm⟩ /-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/ def cauchy_seq [semilattice_sup β] (u : β → α) := cauchy (at_top.map u) lemma cauchy_seq_of_tendsto_nhds [semilattice_sup β] [nonempty β] (f : β → α) {x} (hx : tendsto f at_top (𝓝 x)) : cauchy_seq f := cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hx lemma cauchy_seq_iff_tendsto [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (prod.map u u) at_top (𝓤 α) := cauchy_map_iff.trans $ (and_iff_right at_top_ne_bot).trans $ by simp only [prod_at_top_at_top_eq, prod.map_def] /-- If a Cauchy sequence has a convergent subsequence, then it converges. -/ lemma tendsto_nhds_of_cauchy_seq_of_subseq [semilattice_sup β] {u : β → α} (hu : cauchy_seq u) {ι : Type*} {f : ι → β} {p : filter ι} (hp : p ≠ ⊥) (hf : tendsto f p at_top) {a : α} (ha : tendsto (λ i, u (f i)) p (𝓝 a)) : tendsto u at_top (𝓝 a) := begin apply le_nhds_of_cauchy_adhp hu, rw ← bot_lt_iff_ne_bot, have : ⊥ < map (λ i, u (f i)) p ⊓ 𝓝 a, by { rw [bot_lt_iff_ne_bot, inf_of_le_left ha], exact map_ne_bot hp }, exact lt_of_lt_of_le this (inf_le_inf (map_mono hf) (le_refl _)) end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma filter.has_basis.cauchy_seq_iff {γ} [nonempty β] [semilattice_sup β] {u : β → α} {p : γ → Prop} {s : γ → set (α × α)} (h : (𝓤 α).has_basis p s) : cauchy_seq u ↔ ∀ i, p i → ∃N, ∀m n≥N, (u m, u n) ∈ s i := begin rw [cauchy_seq_iff_tendsto, ← prod_at_top_at_top_eq], refine (at_top_basis.prod_self.tendsto_iff h).trans _, simp only [exists_prop, true_and, maps_to, preimage, subset_def, prod.forall, mem_prod_eq, mem_set_of_eq, mem_Ici, and_imp, prod.map] end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma filter.has_basis.cauchy_seq_iff' {γ} [nonempty β] [semilattice_sup β] {u : β → α} {p : γ → Prop} {s : γ → set (α × α)} (H : (𝓤 α).has_basis p s) : cauchy_seq u ↔ ∀ i, p i → ∃N, ∀n≥N, (u n, u N) ∈ s i := begin refine H.cauchy_seq_iff.trans ⟨λ h i hi, _, λ h i hi, _⟩, { exact (h i hi).imp (λ N hN n hn, hN n N hn (le_refl N)) }, { rcases comp_symm_of_uniformity (H.mem_of_mem hi) with ⟨t, ht, ht', hts⟩, rcases H.mem_iff.1 ht with ⟨j, hj, hjt⟩, refine (h j hj).imp (λ N hN m n hm hn, hts ⟨u N, hjt _, ht' $ hjt _⟩), { exact hN m hm }, { exact hN n hn } } end lemma cauchy_seq_of_controlled [semilattice_sup β] [nonempty β] (U : β → set (α × α)) (hU : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) {f : β → α} (hf : ∀ {N m n : β}, N ≤ m → N ≤ n → (f m, f n) ∈ U N) : cauchy_seq f := cauchy_seq_iff_tendsto.2 begin assume s hs, rw [mem_map, mem_at_top_sets], cases hU s hs with N hN, refine ⟨(N, N), λ mn hmn, _⟩, cases mn with m n, exact hN (hf hmn.1 hmn.2) end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ 𝓝 x) lemma complete_univ {α : Type u} [uniform_space α] [complete_space α] : is_complete (univ : set α) := begin assume f hf _, rcases complete_space.complete hf with ⟨x, hx⟩, exact ⟨x, mem_univ x, hx⟩ end lemma cauchy_prod [uniform_space β] {f : filter α} {g : filter β} : cauchy f → cauchy g → cauchy (filter.prod f g) | ⟨f_proper, hf⟩ ⟨g_proper, hg⟩ := ⟨filter.prod_ne_bot.2 ⟨f_proper, g_proper⟩, let p_α := λp:(α×β)×(α×β), (p.1.1, p.2.1), p_β := λp:(α×β)×(α×β), (p.1.2, p.2.2) in suffices (f.prod f).comap p_α ⊓ (g.prod g).comap p_β ≤ (𝓤 α).comap p_α ⊓ (𝓤 β).comap p_β, by simpa [uniformity_prod, filter.prod, filter.comap_inf, filter.comap_comap_comp, (∘), inf_assoc, inf_comm, inf_left_comm], inf_le_inf (filter.comap_mono hf) (filter.comap_mono hg)⟩ instance complete_space.prod [uniform_space β] [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ cauchy_map uniform_continuous_fst hf in let ⟨x2, hx2⟩ := complete_space.complete $ cauchy_map uniform_continuous_snd hf in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem_sets H1 H2)⟩ } /--If `univ` is complete, the space is a complete space -/ lemma complete_space_of_is_complete_univ (h : is_complete (univ : set α)) : complete_space α := ⟨λ f hf, let ⟨x, _, hx⟩ := h f hf ((@principal_univ α).symm ▸ le_top) in ⟨x, hx⟩⟩ lemma complete_space_iff_is_complete_univ : complete_space α ↔ is_complete (univ : set α) := ⟨@complete_univ α _, complete_space_of_is_complete_univ⟩ lemma cauchy_iff_exists_le_nhds [complete_space α] {l : filter α} (hl : l ≠ ⊥) : cauchy l ↔ (∃x, l ≤ 𝓝 x) := ⟨complete_space.complete, assume ⟨x, hx⟩, cauchy_downwards cauchy_nhds hl hx⟩ lemma cauchy_map_iff_exists_tendsto [complete_space α] {l : filter β} {f : β → α} (hl : l ≠ ⊥) : cauchy (l.map f) ↔ (∃x, tendsto f l (𝓝 x)) := cauchy_iff_exists_le_nhds (map_ne_bot hl) /-- A Cauchy sequence in a complete space converges -/ theorem cauchy_seq_tendsto_of_complete [semilattice_sup β] [complete_space α] {u : β → α} (H : cauchy_seq u) : ∃x, tendsto u at_top (𝓝 x) := complete_space.complete H /-- If `K` is a complete subset, then any cauchy sequence in `K` converges to a point in `K` -/ lemma cauchy_seq_tendsto_of_is_complete [semilattice_sup β] {K : set α} (h₁ : is_complete K) {u : β → α} (h₂ : ∀ n, u n ∈ K) (h₃ : cauchy_seq u) : ∃ v ∈ K, tendsto u at_top (𝓝 v) := h₁ _ h₃ $ le_principal_iff.2 $ mem_map_sets_iff.2 ⟨univ, univ_mem_sets, by { simp only [image_univ], rintros _ ⟨n, rfl⟩, exact h₂ n }⟩ theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α] [nonempty α] {f : filter α} (hf : cauchy f) : f ≤ 𝓝 (lim f) := lim_spec (complete_space.complete hf) lemma is_complete_of_is_closed [complete_space α] {s : set α} (h : is_closed s) : is_complete s := λ f cf fs, let ⟨x, hx⟩ := complete_space.complete cf in ⟨x, is_closed_iff_nhds.mp h x (ne_bot_of_le_ne_bot cf.left (le_inf hx fs)), hx⟩ /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ 𝓤 α, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ 𝓤 α, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, let f : u → α := λ x, classical.some x.2.2, have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := finite_subset fk (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, have := ks xs, simp at this, rcases this with ⟨y, hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, exact mem_bUnion_iff.2 ⟨_, ⟨z, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_subset {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_empty : totally_bounded (∅ : set α) := λ d hd, ⟨∅, finite_empty, empty_subset _⟩ lemma totally_bounded_closure {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : closure_eq_of_is_closed $ is_closed_bUnion hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ lemma totally_bounded_image [uniform_space β] {f : α → β} {s : set α} (hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ 𝓤 α, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image f hfc, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp, exact hct x hx end⟩ lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : is_ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from mem_sets_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa using hs, let f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := (@ne_empty_iff_nonempty α s).1 (assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_ne_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_eq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := nonempty_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, is_ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_iff_totally_bounded_complete {s : set α} : compact s ↔ totally_bounded s ∧ is_complete s := ⟨λ hs, ⟨totally_bounded_iff_ultrafilter.2 (λ f hf1 hf2, let ⟨x, xs, fx⟩ := compact_iff_ultrafilter_le_nhds.1 hs f hf1 hf2 in cauchy_downwards (cauchy_nhds) (hf1.1) fx), λ f fc fs, let ⟨a, as, fa⟩ := hs f fc.1 fs in ⟨a, as, le_nhds_of_cauchy_adhp fc fa⟩⟩, λ ⟨ht, hc⟩, compact_iff_ultrafilter_le_nhds.2 (λf hf hfs, hc _ (totally_bounded_iff_ultrafilter.1 ht _ hf hfs) hfs)⟩ @[priority 100] -- see Note [lower instance priority] instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α := ⟨λf hf, by simpa [principal_univ] using (compact_iff_totally_bounded_complete.1 compact_univ).2 f hf⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := (@compact_iff_totally_bounded_complete α _ s).2 ⟨ht, is_complete_of_is_closed hc⟩ /-! ### Sequentially complete space In this section we prove that a uniform space is complete provided that it is sequentially complete (i.e., any Cauchy sequence converges) and its uniformity filter admits a countable generating set. In particular, this applies to (e)metric spaces, see the files `topology/metric_space/emetric_space` and `topology/metric_space/basic`. More precisely, we assume that there is a sequence of entourages `U_n` such that any other entourage includes one of `U_n`. Then any Cauchy filter `f` generates a decreasing sequence of sets `s_n ∈ f` such that `s_n × s_n ⊆ U_n`. Choose a sequence `x_n∈s_n`. It is easy to show that this is a Cauchy sequence. If this sequence converges to some `a`, then `f ≤ 𝓝 a`. -/ namespace sequentially_complete variables {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ n, U n ∈ 𝓤 α) (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) open set finset noncomputable theory /-- An auxiliary sequence of sets approximating a Cauchy filter. -/ def set_seq_aux (n : ℕ) : {s : set α // ∃ (_ : s ∈ f), s.prod s ⊆ U n } := indefinite_description _ $ (cauchy_iff.1 hf).2 (U n) (U_mem n) /-- Given a Cauchy filter `f` and a sequence `U` of entourages, `set_seq` provides a sequence of monotonically decreasing sets `s n ∈ f` such that `(s n).prod (s n) ⊆ U`. -/ def set_seq (n : ℕ) : set α := ⋂ m ∈ Iic n, (set_seq_aux hf U_mem m).val lemma set_seq_mem (n : ℕ) : set_seq hf U_mem n ∈ f := Inter_mem_sets (finite_le_nat n) (λ m _, (set_seq_aux hf U_mem m).2.fst) lemma set_seq_mono ⦃m n : ℕ⦄ (h : m ≤ n) : set_seq hf U_mem n ⊆ set_seq hf U_mem m := bInter_subset_bInter_left (λ k hk, le_trans hk h) lemma set_seq_sub_aux (n : ℕ) : set_seq hf U_mem n ⊆ set_seq_aux hf U_mem n := bInter_subset_of_mem right_mem_Iic lemma set_seq_prod_subset {N m n} (hm : N ≤ m) (hn : N ≤ n) : (set_seq hf U_mem m).prod (set_seq hf U_mem n) ⊆ U N := begin assume p hp, refine (set_seq_aux hf U_mem N).2.snd ⟨_, _⟩; apply set_seq_sub_aux, exact set_seq_mono hf U_mem hm hp.1, exact set_seq_mono hf U_mem hn hp.2 end /-- A sequence of points such that `seq n ∈ set_seq n`. Here `set_seq` is a monotonically decreasing sequence of sets `set_seq n ∈ f` with diameters controlled by a given sequence of entourages. -/ def seq (n : ℕ) : α := some $ nonempty_of_mem_sets hf.1 (set_seq_mem hf U_mem n) lemma seq_mem (n : ℕ) : seq hf U_mem n ∈ set_seq hf U_mem n := some_spec $ nonempty_of_mem_sets hf.1 (set_seq_mem hf U_mem n) lemma seq_pair_mem ⦃N m n : ℕ⦄ (hm : N ≤ m) (hn : N ≤ n) : (seq hf U_mem m, seq hf U_mem n) ∈ U N := set_seq_prod_subset hf U_mem hm hn ⟨seq_mem hf U_mem m, seq_mem hf U_mem n⟩ include U_le theorem seq_is_cauchy_seq : cauchy_seq $ seq hf U_mem := cauchy_seq_of_controlled U U_le $ seq_pair_mem hf U_mem /-- If the sequence `sequentially_complete.seq` converges to `a`, then `f ≤ 𝓝 a`. -/ theorem le_nhds_of_seq_tendsto_nhds ⦃a : α⦄ (ha : tendsto (seq hf U_mem) at_top (𝓝 a)) : f ≤ 𝓝 a := le_nhds_of_cauchy_adhp_aux begin assume s hs, rcases U_le s hs with ⟨m, hm⟩, rcases (tendsto_at_top' _ _).1 ha _ (mem_nhds_left a (U_mem m)) with ⟨n, hn⟩, refine ⟨set_seq hf U_mem (max m n), set_seq_mem hf U_mem _, _, seq hf U_mem (max m n), seq_mem hf U_mem _, _⟩, { have := le_max_left m n, exact set.subset.trans (set_seq_prod_subset hf U_mem this this) hm }, { exact hm (hn _ $ le_max_right m n) } end end sequentially_complete namespace uniform_space open sequentially_complete variables (H : has_countable_basis (𝓤 α)) include H /-- A uniform space is complete provided that (a) its uniformity filter has a countable basis; (b) any sequence satisfying a "controlled" version of the Cauchy condition converges. -/ theorem complete_of_convergent_controlled_sequences (U : ℕ → set (α × α)) (U_mem : ∀ n, U n ∈ 𝓤 α) (HU : ∀ u : ℕ → α, (∀ N m n, N ≤ m → N ≤ n → (u m, u n) ∈ U N) → ∃ a, tendsto u at_top (𝓝 a)) : complete_space α := begin rcases (𝓤 α).has_countable_basis_iff_mono_seq'.1 H with ⟨U', U'_mono, hU'⟩, have Hmem : ∀ n, U n ∩ U' n ∈ 𝓤 α, from λ n, inter_mem_sets (U_mem n) (hU'.2 ⟨n, subset.refl _⟩), refine ⟨λ f hf, (HU (seq hf Hmem) (λ N m n hm hn, _)).imp $ le_nhds_of_seq_tendsto_nhds _ _ (λ s hs, _)⟩, { rcases (hU'.1 hs) with ⟨N, hN⟩, exact ⟨N, subset.trans (inter_subset_right _ _) hN⟩ }, { exact inter_subset_left _ _ (seq_pair_mem hf Hmem hm hn) } end /-- A sequentially complete uniform space with a countable basis of the uniformity filter is complete. -/ theorem complete_of_cauchy_seq_tendsto (H' : ∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) : complete_space α := let ⟨U', U'_mono, hU'⟩ := (𝓤 α).has_countable_basis_iff_mono_seq'.1 H in complete_of_convergent_controlled_sequences H U' (λ n, hU'.2 ⟨n, subset.refl _⟩) (λ u hu, H' u $ cauchy_seq_of_controlled U' (λ s hs, hU'.1 hs) hu) protected lemma first_countable_topology : first_countable_topology α := ⟨λ a, by { rw nhds_eq_comap_uniformity, exact H.comap (prod.mk a) }⟩ end uniform_space
ad13f6499f355ccbffe8eb6f3abfd714512ea00d
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/BooleanGroup.lean
22d4e1c0637fec8e186dbffb59beb85b550d6b71
[]
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
7,222
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 BooleanGroup structure BooleanGroup (A : Type) : Type := (e : A) (op : (A → (A → A))) (lunit_e : (∀ {x : A} , (op e x) = x)) (runit_e : (∀ {x : A} , (op x e) = x)) (associative_op : (∀ {x y z : A} , (op (op x y) z) = (op x (op y z)))) (unipotence : (∀ {x : A} , (op x x) = e)) open BooleanGroup structure Sig (AS : Type) : Type := (eS : AS) (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (eP : (Prod A A)) (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (lunit_eP : (∀ {xP : (Prod A A)} , (opP eP xP) = xP)) (runit_eP : (∀ {xP : (Prod A A)} , (opP xP eP) = xP)) (associative_opP : (∀ {xP yP zP : (Prod A A)} , (opP (opP xP yP) zP) = (opP xP (opP yP zP)))) (unipotenceP : (∀ {xP : (Prod A A)} , (opP xP xP) = eP)) structure Hom {A1 : Type} {A2 : Type} (Bo1 : (BooleanGroup A1)) (Bo2 : (BooleanGroup A2)) : Type := (hom : (A1 → A2)) (pres_e : (hom (e Bo1)) = (e Bo2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Bo1) x1 x2)) = ((op Bo2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Bo1 : (BooleanGroup A1)) (Bo2 : (BooleanGroup A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_e : (interp (e Bo1) (e Bo2))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Bo1) x1 x2) ((op Bo2) y1 y2)))))) inductive BooleanGroupTerm : Type | eL : BooleanGroupTerm | opL : (BooleanGroupTerm → (BooleanGroupTerm → BooleanGroupTerm)) open BooleanGroupTerm inductive ClBooleanGroupTerm (A : Type) : Type | sing : (A → ClBooleanGroupTerm) | eCl : ClBooleanGroupTerm | opCl : (ClBooleanGroupTerm → (ClBooleanGroupTerm → ClBooleanGroupTerm)) open ClBooleanGroupTerm inductive OpBooleanGroupTerm (n : ℕ) : Type | v : ((fin n) → OpBooleanGroupTerm) | eOL : OpBooleanGroupTerm | opOL : (OpBooleanGroupTerm → (OpBooleanGroupTerm → OpBooleanGroupTerm)) open OpBooleanGroupTerm inductive OpBooleanGroupTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpBooleanGroupTerm2) | sing2 : (A → OpBooleanGroupTerm2) | eOL2 : OpBooleanGroupTerm2 | opOL2 : (OpBooleanGroupTerm2 → (OpBooleanGroupTerm2 → OpBooleanGroupTerm2)) open OpBooleanGroupTerm2 def simplifyCl {A : Type} : ((ClBooleanGroupTerm A) → (ClBooleanGroupTerm A)) | (opCl eCl x) := x | (opCl x eCl) := x | eCl := eCl | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpBooleanGroupTerm n) → (OpBooleanGroupTerm n)) | (opOL eOL x) := x | (opOL x eOL) := x | eOL := eOL | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpBooleanGroupTerm2 n A) → (OpBooleanGroupTerm2 n A)) | (opOL2 eOL2 x) := x | (opOL2 x eOL2) := x | eOL2 := eOL2 | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((BooleanGroup A) → (BooleanGroupTerm → A)) | Bo eL := (e Bo) | Bo (opL x1 x2) := ((op Bo) (evalB Bo x1) (evalB Bo x2)) def evalCl {A : Type} : ((BooleanGroup A) → ((ClBooleanGroupTerm A) → A)) | Bo (sing x1) := x1 | Bo eCl := (e Bo) | Bo (opCl x1 x2) := ((op Bo) (evalCl Bo x1) (evalCl Bo x2)) def evalOpB {A : Type} {n : ℕ} : ((BooleanGroup A) → ((vector A n) → ((OpBooleanGroupTerm n) → A))) | Bo vars (v x1) := (nth vars x1) | Bo vars eOL := (e Bo) | Bo vars (opOL x1 x2) := ((op Bo) (evalOpB Bo vars x1) (evalOpB Bo vars x2)) def evalOp {A : Type} {n : ℕ} : ((BooleanGroup A) → ((vector A n) → ((OpBooleanGroupTerm2 n A) → A))) | Bo vars (v2 x1) := (nth vars x1) | Bo vars (sing2 x1) := x1 | Bo vars eOL2 := (e Bo) | Bo vars (opOL2 x1 x2) := ((op Bo) (evalOp Bo vars x1) (evalOp Bo vars x2)) def inductionB {P : (BooleanGroupTerm → Type)} : ((P eL) → ((∀ (x1 x2 : BooleanGroupTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : BooleanGroupTerm) , (P x)))) | pel popl eL := pel | pel popl (opL x1 x2) := (popl _ _ (inductionB pel popl x1) (inductionB pel popl x2)) def inductionCl {A : Type} {P : ((ClBooleanGroupTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P eCl) → ((∀ (x1 x2 : (ClBooleanGroupTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClBooleanGroupTerm A)) , (P x))))) | psing pecl popcl (sing x1) := (psing x1) | psing pecl popcl eCl := pecl | psing pecl popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing pecl popcl x1) (inductionCl psing pecl popcl x2)) def inductionOpB {n : ℕ} {P : ((OpBooleanGroupTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P eOL) → ((∀ (x1 x2 : (OpBooleanGroupTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpBooleanGroupTerm n)) , (P x))))) | pv peol popol (v x1) := (pv x1) | pv peol popol eOL := peol | pv peol popol (opOL x1 x2) := (popol _ _ (inductionOpB pv peol popol x1) (inductionOpB pv peol popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpBooleanGroupTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P eOL2) → ((∀ (x1 x2 : (OpBooleanGroupTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpBooleanGroupTerm2 n A)) , (P x)))))) | pv2 psing2 peol2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 peol2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 peol2 popol2 eOL2 := peol2 | pv2 psing2 peol2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 peol2 popol2 x1) (inductionOp pv2 psing2 peol2 popol2 x2)) def stageB : (BooleanGroupTerm → (Staged BooleanGroupTerm)) | eL := (Now eL) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClBooleanGroupTerm A) → (Staged (ClBooleanGroupTerm A))) | (sing x1) := (Now (sing x1)) | eCl := (Now eCl) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpBooleanGroupTerm n) → (Staged (OpBooleanGroupTerm n))) | (v x1) := (const (code (v x1))) | eOL := (Now eOL) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpBooleanGroupTerm2 n A) → (Staged (OpBooleanGroupTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | eOL2 := (Now eOL2) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (eT : (Repr A)) (opT : ((Repr A) → ((Repr A) → (Repr A)))) end BooleanGroup
a0d0cb28296182fcd5739dbdf6fcacecfac33d87
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/data/fin/ops.lean
5fc2a724fc35439459f889927aefed67ce6d8059
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
3,341
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat init.data.fin.basic namespace fin open nat variable {n : nat} protected def succ : fin n → fin (succ n) | ⟨a, h⟩ := ⟨nat.succ a, succ_lt_succ h⟩ def of_nat {n : nat} (a : nat) : fin (succ n) := ⟨a % succ n, nat.mod_lt _ (nat.zero_lt_succ _)⟩ private lemma mlt {n b : nat} : ∀ {a}, n > a → b % n < n | 0 h := nat.mod_lt _ h | (a+1) h := have n > 0, from lt.trans (nat.zero_lt_succ _) h, nat.mod_lt _ this protected def add : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a + b) % n, mlt h⟩ protected def mul : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a * b) % n, mlt h⟩ private lemma sublt {a b n : nat} (h : a < n) : a - b < n := lt_of_le_of_lt (nat.sub_le a b) h protected def sub : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a - b, sublt h⟩ private lemma modlt {a b n : nat} (h₁ : a < n) (h₂ : b < n) : a % b < n := begin cases b with b, {simp [mod_zero], assumption}, {have h : a % (succ b) < succ b, apply nat.mod_lt _ (nat.zero_lt_succ _), exact lt.trans h h₂} end protected def mod : fin n → fin n → fin n | ⟨a, h₁⟩ ⟨b, h₂⟩ := ⟨a % b, modlt h₁ h₂⟩ private lemma divlt {a b n : nat} (h : a < n) : a / b < n := lt_of_le_of_lt (nat.div_le_self a b) h protected def div : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a / b, divlt h⟩ instance : has_zero (fin (succ n)) := ⟨⟨0, succ_pos n⟩⟩ instance : has_one (fin (succ n)) := ⟨of_nat 1⟩ instance : has_add (fin n) := ⟨fin.add⟩ instance : has_sub (fin n) := ⟨fin.sub⟩ instance : has_mul (fin n) := ⟨fin.mul⟩ instance : has_mod (fin n) := ⟨fin.mod⟩ instance : has_div (fin n) := ⟨fin.div⟩ lemma of_nat_zero : @of_nat n 0 = 0 := rfl lemma add_def (a b : fin n) : (a + b).val = (a.val + b.val) % n := show (fin.add a b).val = (a.val + b.val) % n, from by cases a; cases b; simp [fin.add] lemma mul_def (a b : fin n) : (a * b).val = (a.val * b.val) % n := show (fin.mul a b).val = (a.val * b.val) % n, from by cases a; cases b; simp [fin.mul] lemma sub_def (a b : fin n) : (a - b).val = a.val - b.val := show (fin.sub a b).val = a.val - b.val, from by cases a; cases b; simp [fin.sub] lemma mod_def (a b : fin n) : (a % b).val = a.val % b.val := show (fin.mod a b).val = a.val % b.val, from by cases a; cases b; simp [fin.mod] lemma div_def (a b : fin n) : (a / b).val = a.val / b.val := show (fin.div a b).val = a.val / b.val, from by cases a; cases b; simp [fin.div] lemma lt_def (a b : fin n) : (a < b) = (a.val < b.val) := show (fin.lt a b) = (a.val < b.val), from by cases a; cases b; simp [fin.lt] lemma le_def (a b : fin n) : (a ≤ b) = (a.val ≤ b.val) := show (fin.le a b) = (a.val ≤ b.val), from by cases a; cases b; simp [fin.le] lemma val_zero : (0 : fin (succ n)).val = 0 := rfl def pred {n : nat} : ∀ i : fin (succ n), i ≠ 0 → fin n | ⟨a, h₁⟩ h₂ := ⟨a.pred, begin have this : a ≠ 0, { have aux₁ := vne_of_ne h₂, dsimp at aux₁, rw val_zero at aux₁, exact aux₁ }, exact nat.pred_lt_pred this h₁ end⟩ end fin
38cbc3cf9eeabe3bcfaff3162206dc7974a5d64b
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/group_theory/solvable.lean
3451868f9a2b14a7ad55fdd9a27129c2c445a9b9
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,244
lean
/- Copyright (c) 2021 Jordan Brown, Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jordan Brown, Thomas Browning and Patrick Lutz -/ import group_theory.abelianization import data.bracket /-! # Solvable Groups In this file we introduce the notion of a solvable group. We define a solvable group as one whose derived series is eventually trivial. This requires defining the commutator of two subgroups and the derived series of a group. ## Main definitions * `general_commutator H₁ H₂` : the commutator of the subgroups `H₁` and `H₂` * `derived_series G n` : the `n`th term in the derived series of `G`, defined by iterating `general_commutator` starting with the top subgroup * `is_solvable G` : the group `G` is solvable -/ open subgroup variables {G : Type*} [group G] section general_commutator /-- The commutator of two subgroups `H₁` and `H₂`. -/ instance general_commutator : has_bracket (subgroup G) (subgroup G) := ⟨λ H₁ H₂, closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x}⟩ lemma general_commutator_def (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x} := rfl instance general_commutator_normal (H₁ H₂ : subgroup G) [h₁ : H₁.normal] [h₂ : H₂.normal] : normal ⁅H₁, H₂⁆ := begin let base : set G := {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x}, suffices h_base : base = group.conjugates_of_set base, { dsimp only [general_commutator_def, ←base], rw h_base, exact subgroup.normal_closure_normal }, apply set.subset.antisymm group.subset_conjugates_of_set, intros a h, rw group.mem_conjugates_of_set_iff at h, rcases h with ⟨b, ⟨c, hc, e, he, rfl⟩, d, rfl⟩, exact ⟨d * c * d⁻¹, h₁.conj_mem c hc d, d * e * d⁻¹, h₂.conj_mem e he d, by group⟩, end lemma general_commutator_mono {H₁ H₂ K₁ K₂ : subgroup G} (h₁ : H₁ ≤ K₁) (h₂ : H₂ ≤ K₂) : ⁅H₁, H₂⁆ ≤ ⁅K₁, K₂⁆ := begin apply closure_mono, rintros x ⟨p, hp, q, hq, rfl⟩, exact ⟨p, h₁ hp, q, h₂ hq, rfl⟩, end lemma general_commutator_def' (H₁ H₂ : subgroup G) [H₁.normal] [H₂.normal] : ⁅H₁, H₂⁆ = normal_closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x} := by rw [← normal_closure_eq_self ⁅H₁, H₂⁆, general_commutator_def, normal_closure_closure_eq_normal_closure] lemma general_commutator_le (H₁ H₂ : subgroup G) (K : subgroup G) : ⁅H₁, H₂⁆ ≤ K ↔ ∀ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ ∈ K := begin rw [general_commutator, closure_le], split, { intros h p hp q hq, exact h ⟨p, hp, q, hq, rfl⟩, }, { rintros h x ⟨p, hp, q, hq, rfl⟩, exact h p hp q hq, } end lemma general_commutator_comm (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = ⁅H₂, H₁⁆ := begin suffices : ∀ H₁ H₂ : subgroup G, ⁅H₁, H₂⁆ ≤ ⁅H₂, H₁⁆, { exact le_antisymm (this _ _) (this _ _) }, intros H₁ H₂, rw general_commutator_le, intros p hp q hq, have h : (p * q * p⁻¹ * q⁻¹)⁻¹ ∈ ⁅H₂, H₁⁆ := subset_closure ⟨q, hq, p, hp, by group⟩, convert inv_mem ⁅H₂, H₁⁆ h, group, end lemma general_commutator_le_right (H₁ H₂ : subgroup G) [h : normal H₂] : ⁅H₁, H₂⁆ ≤ H₂ := begin rw general_commutator_le, intros p hp q hq, exact mul_mem H₂ (h.conj_mem q hq p) (inv_mem H₂ hq), end lemma general_commutator_le_left (H₁ H₂ : subgroup G) [h : normal H₁] : ⁅H₁, H₂⁆ ≤ H₁ := begin rw general_commutator_comm, exact general_commutator_le_right H₂ H₁, end @[simp] lemma general_commutator_bot (H : subgroup G) : ⁅H, ⊥⁆ = (⊥ : subgroup G) := by { rw eq_bot_iff, exact general_commutator_le_right H ⊥ } @[simp] lemma bot_general_commutator (H : subgroup G) : ⁅(⊥ : subgroup G), H⁆ = (⊥ : subgroup G) := by { rw eq_bot_iff, exact general_commutator_le_left ⊥ H } lemma general_commutator_le_inf (H₁ H₂ : subgroup G) [normal H₁] [normal H₂] : ⁅H₁, H₂⁆ ≤ H₁ ⊓ H₂ := by simp only [general_commutator_le_left, general_commutator_le_right, le_inf_iff, and_self] end general_commutator section derived_series variables (G) /-- The derived series of the group `G`, obtained by starting from the subgroup `⊤` and repeatedly taking the commutator of the previous subgroup with itself for `n` times. -/ def derived_series : ℕ → subgroup G | 0 := ⊤ | (n + 1) := ⁅(derived_series n), (derived_series n)⁆ @[simp] lemma derived_series_zero : derived_series G 0 = ⊤ := rfl @[simp] lemma derived_series_succ (n : ℕ) : derived_series G (n + 1) = ⁅(derived_series G n), (derived_series G n)⁆ := rfl lemma derived_series_normal (n : ℕ) : (derived_series G n).normal := begin induction n with n ih, { exact subgroup.top_normal, }, { rw derived_series_succ, exactI general_commutator_normal (derived_series G n) (derived_series G n), } end @[simp] lemma general_commutator_eq_commutator : ⁅(⊤ : subgroup G), (⊤ : subgroup G)⁆ = commutator G := begin rw [commutator, general_commutator_def'], apply le_antisymm; apply normal_closure_mono, { exact λ x ⟨p, _, q, _, h⟩, ⟨p, q, h⟩, }, { exact λ x ⟨p, q, h⟩, ⟨p, mem_top p, q, mem_top q, h⟩, } end lemma commutator_def' : commutator G = subgroup.closure {x : G | ∃ p q, p * q * p⁻¹ * q⁻¹ = x} := begin rw [← general_commutator_eq_commutator, general_commutator], apply le_antisymm; apply closure_mono, { exact λ x ⟨p, _, q, _, h⟩, ⟨p, q, h⟩ }, { exact λ x ⟨p, q, h⟩, ⟨p, mem_top p, q, mem_top q, h⟩ } end @[simp] lemma derived_series_one : derived_series G 1 = commutator G := general_commutator_eq_commutator G end derived_series section commutator_map variables {G} {G' : Type*} [group G'] {f : G →* G'} lemma map_commutator_eq_commutator_map (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆.map f = ⁅H₁.map f, H₂.map f⁆ := begin rw [general_commutator, general_commutator, monoid_hom.map_closure], apply le_antisymm; apply closure_mono, { rintros _ ⟨x, ⟨p, hp, q, hq, rfl⟩, rfl⟩, refine ⟨f p, mem_map.mpr ⟨p, hp, rfl⟩, f q, mem_map.mpr ⟨q, hq, rfl⟩, by simp *⟩, }, { rintros x ⟨_, ⟨p, hp, rfl⟩, _, ⟨q, hq, rfl⟩, rfl⟩, refine ⟨p * q * p⁻¹ * q⁻¹, ⟨p, hp, q, hq, rfl⟩, by simp *⟩, }, end lemma commutator_le_map_commutator {H₁ H₂ : subgroup G} {K₁ K₂ : subgroup G'} (h₁ : K₁ ≤ H₁.map f) (h₂ : K₂ ≤ H₂.map f) : ⁅K₁, K₂⁆ ≤ ⁅H₁, H₂⁆.map f := by { rw map_commutator_eq_commutator_map, exact general_commutator_mono h₁ h₂ } section derived_series_map variables (f) lemma map_derived_series_le_derived_series (n : ℕ) : (derived_series G n).map f ≤ derived_series G' n := begin induction n with n ih, { simp only [derived_series_zero, le_top], }, { simp only [derived_series_succ, map_commutator_eq_commutator_map, general_commutator_mono, *], } end variables {f} lemma derived_series_le_map_derived_series (hf : function.surjective f) (n : ℕ) : derived_series G' n ≤ (derived_series G n).map f := begin induction n with n ih, { rwa [derived_series_zero, derived_series_zero, top_le_iff, ← monoid_hom.range_eq_map, ← monoid_hom.range_top_iff_surjective.mpr], }, { simp only [*, derived_series_succ, commutator_le_map_commutator], } end lemma map_derived_series_eq (hf : function.surjective f) (n : ℕ) : (derived_series G n).map f = derived_series G' n := le_antisymm (map_derived_series_le_derived_series f n) (derived_series_le_map_derived_series hf n) end derived_series_map end commutator_map section solvable variables (G) /-- A group `G` is solvable if its derived series is eventually trivial. We use this definition because it's the most convenient one to work with. -/ class is_solvable : Prop := (solvable : ∃ n : ℕ, derived_series G n = ⊥) lemma is_solvable_def : is_solvable G ↔ ∃ n : ℕ, derived_series G n = ⊥ := ⟨λ h, h.solvable, λ h, ⟨h⟩⟩ @[priority 100] instance comm_group.is_solvable {G : Type*} [comm_group G] : is_solvable G := begin use 1, rw [eq_bot_iff, derived_series_one], calc commutator G ≤ (monoid_hom.id G).ker : abelianization.commutator_subset_ker (monoid_hom.id G) ... = ⊥ : rfl, end lemma is_solvable_of_comm {G : Type*} [hG : group G] (h : ∀ a b : G, a * b = b * a) : is_solvable G := begin letI hG' : comm_group G := { mul_comm := h .. hG }, tactic.unfreeze_local_instances, cases hG, exact comm_group.is_solvable, end lemma is_solvable_of_top_eq_bot (h : (⊤ : subgroup G) = ⊥) : is_solvable G := ⟨⟨0, h⟩⟩ @[priority 100] instance is_solvable_of_subsingleton [subsingleton G] : is_solvable G := is_solvable_of_top_eq_bot G (by ext; simp at *) variables {G} {G' : Type*} [group G'] {f : G →* G'} lemma solvable_of_solvable_injective (hf : function.injective f) [h : is_solvable G'] : is_solvable G := begin rw is_solvable_def at *, cases h with n hn, use n, rw ← map_eq_bot_iff_of_injective _ hf, rw eq_bot_iff at *, calc map f (derived_series G n) ≤ derived_series G' n : map_derived_series_le_derived_series f n ... ≤ ⊥ : hn, end instance subgroup_solvable_of_solvable (H : subgroup G) [h : is_solvable G] : is_solvable H := solvable_of_solvable_injective (show function.injective (subtype H), from subtype.val_injective) lemma solvable_of_surjective (hf : function.surjective f) [h : is_solvable G] : is_solvable G' := begin rw is_solvable_def at *, cases h with n hn, use n, calc derived_series G' n = (derived_series G n).map f : eq.symm (map_derived_series_eq hf n) ... = (⊥ : subgroup G).map f : by rw hn ... = ⊥ : map_bot f, end instance solvable_quotient_of_solvable (H : subgroup G) [H.normal] [h : is_solvable G] : is_solvable (quotient_group.quotient H) := solvable_of_surjective (show function.surjective (quotient_group.mk' H), by tidy) lemma solvable_of_ker_le_range {G' G'' : Type*} [group G'] [group G''] (f : G' →* G) (g : G →* G'') (hfg : g.ker ≤ f.range) [hG' : is_solvable G'] [hG'' : is_solvable G''] : is_solvable G := begin tactic.unfreeze_local_instances, obtain ⟨n, hn⟩ := hG'', suffices : ∀ k : ℕ, derived_series G (n + k) ≤ (derived_series G' k).map f, { obtain ⟨m, hm⟩ := hG', use n + m, specialize this m, rwa [hm, map_bot, le_bot_iff] at this }, intro k, induction k with k hk, { rw [add_zero, derived_series_zero, ←monoid_hom.range_eq_map], refine le_trans _ hfg, rw [←map_eq_bot_iff, eq_bot_iff, ←hn], exact map_derived_series_le_derived_series g n }, { rw [nat.add_succ, derived_series_succ, derived_series_succ], exact commutator_le_map_commutator hk hk }, end instance solvable_prod {G' : Type*} [group G'] [h : is_solvable G] [h' : is_solvable G'] : is_solvable (G × G') := solvable_of_ker_le_range (monoid_hom.inl G G') (monoid_hom.snd G G') (λ x hx, ⟨x.1, prod.ext rfl hx.symm⟩) end solvable
899ad15a34c60538ae830f823a14b6b09e796a81
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tst14.lean
6f865e44945f3930a926e691a2bad26df7af9916
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
98
lean
import Int. print Int -> Int -> Int variable f : Int -> Int -> Int eval f 0 check f 0 check f 0 1
c05ff16f36389478c57c18761a06fc3d6dba6c88
798dd332c1ad790518589a09bc82459fb12e5156
/data/polynomial.lean
91479140e4f08a1d6c79ddfeadd7bac01bc03be9
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,793
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Jens Wagemaker Theory of univariate polynomials, represented as `ℕ →₀ α`, where α is a commutative semiring. -/ import data.finsupp algebra.euclidean_domain /-- `polynomial α` is the type of univariate polynomials over `α`. Polynomials should be seen as (semi-)rings with the additional the constructor `X`. `C` is the embedding from `α`. -/ def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α open finsupp finset lattice namespace polynomial universe u variables {α : Type u} {a b : α} {m n : ℕ} variables [decidable_eq α] section comm_semiring variables [comm_semiring α] {p q : polynomial α} instance : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun instance : has_zero (polynomial α) := finsupp.has_zero instance : has_one (polynomial α) := finsupp.has_one instance : has_add (polynomial α) := finsupp.has_add instance : has_mul (polynomial α) := finsupp.has_mul instance : comm_semiring (polynomial α) := finsupp.to_comm_semiring instance : decidable_eq (polynomial α) := finsupp.decidable_eq instance [has_repr α] : has_repr (polynomial α) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (p n) ++ ")" else if n = 1 then if (p n) = 1 then "X" else "C (" ++ repr (p n) ++ ") * X" else if (p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (p n) ++ ") * X ^ " ++ repr n) ""⟩ local attribute [instance] finsupp.to_comm_semiring @[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl /-- `C a` is the constant polynomial `a`. -/ def C (a : α) : polynomial α := single 0 a /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial α := single 1 1 /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial α) : with_bot ℕ := p.support.sup some def degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) /-- `nat_degree p` forces `degree p` to ℕ, by fixing the zero polnomial to the 0 degree. -/ def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0 lemma single_eq_C_mul_X : ∀{n}, single n a = C a * X^n | 0 := by simp; refl | (n+1) := calc single (n + 1) a = single n a * X : by rw [X, single_mul_single, mul_one] ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp [pow_add, mul_assoc] lemma sum_C_mul_X_eq (p : polynomial α) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) finsupp.sum_single @[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp [h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by simpa [C], h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by rwa [single_eq_C_mul_X], h_add _ _ this hp) @[simp] lemma zero_apply (n : ℕ) : (0 : polynomial α) n = 0 := rfl @[simp] lemma one_apply_zero (n : ℕ) : (1 : polynomial α) 0 = 1 := rfl @[simp] lemma add_apply (p q : polynomial α) (n : ℕ) : (p + q) n = p n + q n := finsupp.add_apply lemma C_apply : (C a : ℕ → α) n = ite (0 = n) a 0 := rfl @[simp] lemma C_apply_zero : (C a : ℕ → α) 0 = a := rfl @[simp] lemma X_apply_one : (X : polynomial α) 1 = 1 := rfl @[simp] lemma C_0 : C (0 : α) = 0 := by simp [C]; refl @[simp] lemma C_1 : C (1 : α) = 1 := rfl @[simp] lemma C_mul : C (a * b) = C a * C b := by simp [C, single_mul_single] @[simp] lemma C_add : C (a + b) = C a + C b := finsupp.single_add instance C.is_semiring_hom : is_semiring_hom (C : α → polynomial α) := ⟨C_0, C_1, λ _ _, C_add, λ _ _, C_mul⟩ @[simp] lemma C_mul_apply (p : polynomial α) : (C a * p) n = a * p n := begin conv in (a * _) { rw [← @sum_single _ _ _ _ _ p, sum_apply] }, rw [mul_def, C, sum_single_index], { simp [single_apply, finsupp.mul_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, simp end @[simp] lemma X_pow_apply (n i : ℕ) : (X ^ n : polynomial α) i = (if n = i then 1 else 0) := suffices (single n 1 : polynomial α) i = (if n = i then 1 else 0), by rw [single_eq_C_mul_X] at this; simpa, single_apply section eval₂ variables {β : Type*} [comm_semiring β] variables (f : α → β) [is_semiring_hom f] (x : β) open is_semiring_hom /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial α) : β := p.sum (λ e a, f a * x ^ e) @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := by simp [C, eval₂, sum_single_index, map_zero f] @[simp] lemma eval₂_X : X.eval₂ f x = x := by simp [X, eval₂, sum_single_index, map_zero f, map_one f] @[simp] lemma eval₂_zero : (0 : polynomial α).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (by simp [map_zero f]) (by simp [add_mul, map_add f]) @[simp] lemma eval₂_one : (1 : polynomial α).eval₂ f x = 1 := by rw [← C_1, eval₂_C, map_one f] @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin dunfold eval₂, rw [mul_def, finsupp.sum_mul _ p], simp [finsupp.mul_sum _ q, sum_sum_index, map_zero f, map_add f, add_mul, sum_single_index, map_mul f, pow_add], exact sum_congr rfl (assume i hi, sum_congr rfl $ assume j hj, by ac_refl) end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _ end eval₂ section eval variable {x : α} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : α → polynomial α → α := eval₂ id @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial α).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0 instance : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} : is_root q a → is_root (p * q) a := by simp [is_root.def, eval_mul] {contextual := tt} lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) : is_root p a → is_root (p * q) a := by simp [is_root.def, eval_mul] {contextual := tt} end eval section map variables {β : Type*} [comm_semiring β] [decidable_eq β] variables (f : α → β) [is_semiring_hom f] /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial α → polynomial β := eval₂ (C ∘ f) X @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_zero : (0 : polynomial α).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial α).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _ instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _ lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _ end map /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial α) : α := p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial α) := leading_coeff p = (1 : α) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial α) = 0 := by simp [nat_degree]; refl @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw [if_neg ha]; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; simp [h]; exact le_refl _ lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { simp [hp] }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup ((finsupp.mem_support_iff _ _).2 h) lemma le_nat_degree_of_ne_zero (h : p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma degree_le_degree (h : q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { simp [hp] }, { rw [degree_eq_nat_degree hp], exact le_degree_of_ne_zero h } end @[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { simp [ha] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by simp [h] else le_of_eq (degree_monomial n h) lemma eq_zero_of_degree_lt (h : degree p < n) : p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma apply_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : p (nat_degree q) = 0 := eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (p 0) := begin ext n, cases n, { refl }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [C_apply, if_neg (nat.succ_ne_zero _).symm, eq_zero_of_degree_lt this] } end lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt (mem_support_iff _ _).1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), by simp {contextual := tt}⟩ lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [add_apply, apply_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← add_apply], exact apply_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p := sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ λ h, not_mem_erase _ _ (mem_of_max h) lemma degree_sum_le {β : Type*} [decidable_eq β] (s : finset β) (f : β → polynomial α) : degree (s.sum f) ≤ s.sup (degree ∘ f) := finset.induction_on s (by simp [finsupp.support_zero]) $ assume a s has ih, calc degree (sum (insert a s) f) ≤ max (degree (f a)) (degree (s.sum f)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (p i * q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p) | 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp [ha] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact finsupp.single_eq_same } end @[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by simpa, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^1) = 1, by simpa, leading_coeff_monomial 1 1 @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^0) = 1, by simpa, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _ lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have p (nat_degree q) = 0, from apply_nat_degree_eq_zero_of_degree_lt h, by simp [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp [leading_coeff, this, nat_degree_eq_of_degree_eq h] @[simp] lemma mul_apply_degree_add_degree (p q : polynomial α) : (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := have ∀i, p i ≠ 0 → i ≠ nat_degree p → q.support.sum (λj, ite (i + j = nat_degree p + nat_degree q) (p i * q j) 0) = 0, begin assume i hpi hid, rw [finset.sum_eq_single (nat_degree q)]; simp [hid], assume j hqj hjd, have hi : j < nat_degree q, from lt_of_le_of_ne (le_nat_degree_of_ne_zero hqj) hjd, have hj : i < nat_degree p, from lt_of_le_of_ne (le_nat_degree_of_ne_zero hpi) hid, exact if_neg (ne_of_lt $ add_lt_add hj hi) end, begin rw [mul_def, sum_apply, finsupp.sum, finset.sum_eq_single (nat_degree p), sum_apply, finsupp.sum, finset.sum_eq_single (nat_degree q)]; simp [single_apply, leading_coeff] {contextual := tt}, assumption end lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; simp {contextual := tt}, have hq : q ≠ 0 := by refine mt _ h; by simp {contextual := tt}, le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa mul_apply_degree_add_degree end lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, by simpa [h₁] using h), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, by simpa [h₁] using h), have hpq : p * q ≠ 0 := λ hpq, by rw [← mul_apply_degree_add_degree, hpq, zero_apply] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul_eq' h, mul_apply_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, by simpa [h₁, pow_succ] using h, have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = add_monoid.smul n (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, add_monoid.zero_smul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, by simpa [h₁, pow_succ] using h, have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁] @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial α) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : α) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] end comm_semiring section comm_ring variables [comm_ring α] {p q : polynomial α} instance : comm_ring (polynomial α) := finsupp.to_comm_ring instance : has_scalar α (polynomial α) := finsupp.to_has_scalar instance : module α (polynomial α) := finsupp.to_module α instance C.is_ring_hom : is_ring_hom (@C α _ _) := by apply is_ring_hom.of_semiring instance eval₂.is_ring_hom {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : α} : is_ring_hom (eval x) := eval₂.is_ring_hom _ instance map.is_ring_hom {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : is_ring_hom (map f) := eval₂.is_ring_hom (C ∘ f) @[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma neg_apply (p : polynomial α) (n : ℕ) : (-p) n = -p n := neg_apply @[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ @[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩ lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 | h := begin rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α}, monic q → polynomial α × polynomial α | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, simp [mul_add, add_mul, mul_comm, hq, h, div_by_monic] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h], simp end using_well_founded {dec_tac := tactic.assumption} lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) : (∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) @[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, split_ifs; simp * at * end @[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, split_ifs; simp * at * end @[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else begin unfold mod_by_monic div_mod_by_monic_aux, split_ifs; simp * at * end @[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else begin unfold div_by_monic div_mod_by_monic_aux, split_ifs; simp * at * end lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; simp *⟩ lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; simp *⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial α), p = 0, from λ p, (@subsingleton_of_monic_zero α _ _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp [hp0] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp [dif_pos hq, h] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] {p q : polynomial α} instance : nonzero_comm_ring (polynomial α) := { zero_ne_one := λ (h : (0 : polynomial α) = 1), @zero_ne_one α _ $ calc (0 : α) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C, ..polynomial.comm_ring } @[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) := degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial α) = 1 := begin unfold X degree single finsupp.support, rw if_neg (zero_ne_one).symm, refl end @[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X α], by_cases ha : a = 0, { simp [ha] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial α) ^ n) = n | 0 := by simp; refl | (n+1) := have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : degree ((X : polynomial α) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial α) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial α) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : α) : (X : polynomial α) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial α) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn; exact dec_trivial) @[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) := by simp [monic, zero_ne_one] lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero α _ _ (h₁ ▸ h) lemma monic_X_sub_C (a : α) : monic (X - C a) := have degree (-C a) < degree (X : polynomial α) := if ha : a = 0 then by simp [ha]; exact dec_trivial else by simp [degree_C ha]; exact dec_trivial, by unfold monic; rw [sub_eq_add_neg, add_comm, leading_coeff_add_of_degree_lt this, leading_coeff_X] lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) := have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ end nonzero_comm_ring section integral_domain variables [integral_domain α] {p q : polynomial α} @[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp [hp0] else if hq0 : q = 0 then by simp [hq0] else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) : degree (p ^ n) = add_monoid.smul n (degree p) := by induction n; simp [*, pow_succ, succ_smul] @[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp [hp] }, { by_cases hq : q = 0, { simp [hq] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := by induction n; simp [*, pow_succ] instance : integral_domain (polynomial α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero_comm_ring } lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (ext (λ n, show p n = 0, from nat.cases_on n h (λ _, eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end lemma degree_le_mul_left (p : polynomial α) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp [hp] else by rw [degree_mul_eq, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0), ∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by have := mul_div_by_monic_eq_iff_is_root.2 hx; simp * at *, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add' (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by clear exists_finset_roots; finish⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial α) : finset α := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : (roots ((X : polynomial α) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial α) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial α) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ noncomputable def nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : finset α := by letI := classical.prop_decidable; exact roots ((X : polynomial α) ^ n - C a) @[simp] lemma mem_nth_roots {α : Type*} [integral_domain α] {n : ℕ} (hn : 0 < n) {a x : α} : x ∈ nth_roots n a ↔ x ^ n = a := by letI := classical.prop_decidable; rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : (nth_roots n a).card ≤ n := by letI := classical.prop_decidable; exact if hn : n = 0 then if h : (X : polynomial α) ^ n - C a = 0 then by simp [nat.zero_le, nth_roots, roots, h] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← @C_1 α _, ← is_ring_hom.map_sub (@C α _ _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) end integral_domain section field variables [field α] {p q : polynomial α} instance : vector_space α (polynomial α) := { ..finsupp.to_module α } lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (h : p ≠ 0) : degree (p * C (leading_coeff p)⁻¹) = degree p := have h₁ : (leading_coeff p)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq, degree_C h₁, add_zero] def div (p q : polynomial α) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) def mod (p q : polynomial α) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) : q * div p q + mod p q = p := if h : q = 0 then by simp [h, mod_by_monic, div, mod] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) : degree (mod p q) < degree q := degree_mul_leading_coeff_inv hq ▸ degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial α) := ⟨div⟩ instance : has_mod (polynomial α) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp [monic.def.1 hq] lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp [monic.def.1 hq] lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial α) := { quotient := (/), remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp [this] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul_eq]} end field section derivative variables [comm_semiring α] {β : Type*} /-- `derivative p` formal derivative of the polynomial `p` -/ def derivative (p : polynomial α) : polynomial α := p.sum (λn a, C (a * n) * X^(n - 1)) lemma derivative_apply (p : polynomial α) (n : ℕ) : (derivative p) n = p (n + 1) * (n + 1) := begin rw [derivative], simp [finsupp.sum], rw [finset.sum_eq_single (n + 1)]; simp {contextual := tt}, assume b, cases b; simp [nat.succ_eq_add_one] {contextual := tt}, end @[simp] lemma derivative_zero : derivative (0 : polynomial α) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : α) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X]; simp; refl @[simp] lemma derivative_C {a : α} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:α) * X ^ 0, by simpa, derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial α) = 1 := suffices derivative (C (1:α) * X^1) = C (1 * (1:ℕ)) * X ^ (1 - 1), by simpa, derivative_monomial 1 1 @[simp] lemma derivative_one : derivative (1 : polynomial α) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial α} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; simp [add_mul] @[simp] lemma derivative_sum {s : finset β} {f : β → polynomial α} : derivative (s.sum f) = s.sum (λb, derivative (f b)) := begin apply (finset.sum_hom derivative _ _).symm, exact derivative_zero, exact assume x y, derivative_add end @[simp] lemma derivative_mul {f g : polynomial α} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, dsimp, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C (b * m) * X^(m - 1)) * (C a * X^n))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by cases n; cases m; simp [mul_add, add_mul, mul_assoc, mul_comm, mul_left_comm, add_assoc, add_comm, add_left_comm, pow_add, pow_succ] ... = derivative f * g + f * derivative g : begin simp [finsupp.sum_add], conv { to_rhs, congr, { rw [← sum_C_mul_X_eq f, derivative] }, { rw [← sum_C_mul_X_eq g, derivative] }, }, simp [finsupp.mul_sum, finsupp.sum_mul], simp [finsupp.sum, mul_assoc, mul_comm, mul_left_comm] end end derivative section domain variables [integral_domain α] lemma mem_support_derivative [char_zero α] (p : polynomial α) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(p (n + 1) = 0 ∨ ((1 + n:ℕ) : α) = 0)) ↔ p (n + 1) ≠ 0, by simpa [derivative_apply], by rw [nat.cast_eq_zero]; simp @[simp] lemma degree_derivative_eq [char_zero α] (p : polynomial α) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa using hn }, { assume h, simpa [h] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain end polynomial
70114f4236f70bbcef61e375527c4c03756ffc9d
f57749ca63d6416f807b770f67559503fdb21001
/hott/types/default.hlean
1465d3c7941a30947ce21a146e7c9287ec4b287f
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
273
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import .bool .prod .sigma .pi .arrow .pointed .fiber import .nat .int .cubical import .eq .equiv .function .trunc
be6a60c8d3dac24207a9eed807dac19edad11edc
3446e92e64a5de7ed1f2109cfb024f83cd904c34
/src/game/world5/level3.lean
67501c67dcb735f43143279bd0f16f771a4b4c45
[]
no_license
kckennylau/natural_number_game
019f4a5f419c9681e65234ecd124c564f9a0a246
ad8c0adaa725975be8a9f978c8494a39311029be
refs/heads/master
1,598,784,137,722
1,571,905,156,000
1,571,905,156,000
218,354,686
0
0
null
1,572,373,319,000
1,572,373,318,000
null
UTF-8
Lean
false
false
281
lean
import game.world5.level2 -- hide namespace mynat -- hide /- # World 5 : Inequality world ## Level 3 : `zero_le` -/ /- Lemma For all naturals `a`, `0 ≤ a`. -/ lemma zero_le (a : mynat) : 0 ≤ a := begin [less_leaky] use a, rw zero_add, refl, end end mynat -- hide
2c0986bfdb3f0830a9ee88d3ba068ddaa2865627
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/fin/tuple/bubble_sort_induction.lean
8e7a0ca355e02d3e6cca6e8999df4338e945cfa4
[ "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
2,512
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import data.fin.tuple.sort import data.fintype.perm import order.well_founded /-! # "Bubble sort" induction > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We implement the following induction principle `tuple.bubble_sort_induction` on tuples with values in a linear order `α`. Let `f : fin n → α` and let `P` be a predicate on `fin n → α`. Then we can show that `f ∘ sort f` satisfies `P` if `f` satisfies `P`, and whenever some `g : fin n → α` satisfies `P` and `g i > g j` for some `i < j`, then `g ∘ swap i j` also satisfies `P`. We deduce it from a stronger variant `tuple.bubble_sort_induction'`, which requires the assumption only for `g` that are permutations of `f`. The latter is proved by well-founded induction via `well_founded.induction_bot'` with respect to the lexicographic ordering on the finite set of all permutations of `f`. -/ namespace tuple /-- *Bubble sort induction*: Prove that the sorted version of `f` has some property `P` if `f` satsifies `P` and `P` is preserved on permutations of `f` when swapping two antitone values. -/ lemma bubble_sort_induction' {n : ℕ} {α : Type*} [linear_order α] {f : fin n → α} {P : (fin n → α) → Prop} (hf : P f) (h : ∀ (σ : equiv.perm (fin n)) (i j : fin n), i < j → (f ∘ σ) j < (f ∘ σ) i → P (f ∘ σ) → P (f ∘ σ ∘ equiv.swap i j)) : P (f ∘ sort f) := begin letI := @preorder.lift _ (lex (fin n → α)) _ (λ σ : equiv.perm (fin n), to_lex (f ∘ σ)), refine @well_founded.induction_bot' _ _ _ (is_well_founded.wf : well_founded (<)) (equiv.refl _) (sort f) P (λ σ, f ∘ σ) (λ σ hσ hfσ, _) hf, obtain ⟨i, j, hij₁, hij₂⟩ := antitone_pair_of_not_sorted' hσ, exact ⟨σ * equiv.swap i j, pi.lex_desc hij₁ hij₂, h σ i j hij₁ hij₂ hfσ⟩, end /-- *Bubble sort induction*: Prove that the sorted version of `f` has some property `P` if `f` satsifies `P` and `P` is preserved when swapping two antitone values. -/ lemma bubble_sort_induction {n : ℕ} {α : Type*} [linear_order α] {f : fin n → α} {P : (fin n → α) → Prop} (hf : P f) (h : ∀ (g : fin n → α) (i j : fin n), i < j → g j < g i → P g → P (g ∘ equiv.swap i j)) : P (f ∘ sort f) := bubble_sort_induction' hf (λ σ, h _) end tuple
066c6d854eaadf7339c6a9471bcd23c21034433d
367134ba5a65885e863bdc4507601606690974c1
/scripts/lint_mathlib.lean
1353134421f2cacdb04d0efdaa42b0bab927bce2
[ "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,231
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint import system.io -- these are required import all -- then import everything, to parse the library for failing linters /-! # lint_mathlib Script that runs the linters listed in `mathlib_linters` on all of mathlib. As a side effect, the file `nolints.txt` is generated in the current directory. This script needs to be run in the root directory of mathlib. It assumes that files generated by `mk_all.sh` are present. This is used by the CI script for mathlib. Usage: `lean --run scripts/lint_mathlib.lean` -/ open native /-- Returns the contents of the `nolints.txt` file. -/ meta def mk_nolint_file (env : environment) (mathlib_path_len : ℕ) (results : list (name × linter × rb_map name string)) : format := do let failed_decls_by_file := rb_lmap.of_list (do (linter_name, _, decls) ← results, (decl_name, _) ← decls.to_list, let file_name := (env.decl_olean decl_name).get_or_else "", pure (file_name.popn mathlib_path_len, decl_name.to_string, linter_name.last)), format.intercalate format.line $ "import .all" :: "run_cmd tactic.skip" :: do (file_name, decls) ← failed_decls_by_file.to_list.reverse, "" :: ("-- " ++ file_name) :: do (decl, linters) ← (rb_lmap.of_list decls).to_list.reverse, pure $ "apply_nolint " ++ decl ++ " " ++ " ".intercalate linters /-- Parses the list of lines of the `nolints.txt` into an `rb_lmap` from linters to declarations. -/ meta def parse_nolints (lines : list string) : rb_lmap name name := rb_lmap.of_list $ do line ← lines, guard $ line.front = 'a', _ :: decl :: linters ← pure $ line.split (= ' ') | [], let decl := name.from_string decl, linter ← linters, pure (linter, decl) open io io.fs /-- Reads the `nolints.txt`, and returns it as an `rb_lmap` from linters to declarations. -/ meta def read_nolints_file (fn := "scripts/nolints.txt") : io (rb_lmap name name) := do cont ← io.fs.read_file fn, pure $ parse_nolints $ cont.to_string.split (= '\n') meta instance coe_tactic_to_io {α} : has_coe (tactic α) (io α) := ⟨run_tactic⟩ /-- Writes a file with the given contents. -/ meta def io.write_file (fn : string) (contents : string) : io unit := do h ← mk_file_handle fn mode.write, put_str h contents, close h /-- Runs when called with `lean --run` -/ meta def main : io unit := do env ← tactic.get_env, decls ← lint_mathlib_decls, linters ← get_linters mathlib_linters, mathlib_path_len ← string.length <$> tactic.get_mathlib_dir, let non_auto_decls := decls.filter (λ d, ¬ d.is_auto_or_internal env), results₀ ← lint_core decls non_auto_decls linters, nolint_file ← read_nolints_file, let results := (do (linter_name, linter, decls) ← results₀, [(linter_name, linter, (nolint_file.find linter_name).foldl rb_map.erase decls)]), io.print $ to_string $ format_linter_results env results decls non_auto_decls mathlib_path_len "in mathlib" tt lint_verbosity.medium, io.write_file "nolints.txt" $ to_string $ mk_nolint_file env mathlib_path_len results₀, if results.all (λ r, r.2.2.empty) then pure () else io.fail ""
c86c10bb26017c7bf06aeaf29a69023dee720fd7
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/complex.lean
e3a1c83e36778b5755a76dd22c8d9c5981a0a32e
[ "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
12,476
lean
/- Copyright (c) 2015 Jacob Gross. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jacob Gross, Jeremy Avigad The complex numbers. -/ import data.real open real eq.ops record complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex variables (u w z : ℂ) variable n : ℕ protected proposition eq {z w : ℂ} (H1 : complex.re z = complex.re w) (H2 : complex.im z = complex.im w) : z = w := begin induction z, induction w, rewrite [H1, H2] end protected proposition eta (z : ℂ) : complex.mk (complex.re z) (complex.im z) = z := by cases z; exact rfl -- definition of_real [coercion] (x : ℝ) : ℂ := complex.mk x 0 -- definition of_rat [coercion] (q : ℚ) : ℂ := q -- definition of_int [coercion] (i : ℤ) : ℂ := i -- definition of_nat [coercion] (n : ℕ) : ℂ := n -- definition of_num [coercion] [reducible] (n : num) : ℂ := n protected definition prio : num := num.pred real.prio attribute [instance, priority complex.prio] definition complex_has_zero : has_zero ℂ := has_zero.mk (of_nat 0) attribute [instance, priority complex.prio] definition complex_has_one : has_one ℂ := has_one.mk (of_nat 1) theorem re_of_real (x : ℝ) : re (of_real x) = x := rfl theorem im_of_real (x : ℝ) : im (of_real x) = 0 := rfl protected definition add (z w : ℂ) : ℂ := complex.mk (complex.re z + complex.re w) (complex.im z + complex.im w) protected definition neg (z : ℂ) : ℂ := complex.mk (-(re z)) (-(im z)) protected definition mul (z w : ℂ) : ℂ := complex.mk (complex.re w * complex.re z - complex.im w * complex.im z) (complex.re w * complex.im z + complex.im w * complex.re z) /- notation -/ attribute [instance, priority complex.prio] definition complex_has_add : has_add complex := has_add.mk complex.add attribute [instance, priority complex.prio] definition complex_has_neg : has_neg complex := has_neg.mk complex.neg attribute [instance, priority complex.prio] definition complex_has_mul : has_mul complex := has_mul.mk complex.mul protected theorem add_def (z w : ℂ) : z + w = complex.mk (complex.re z + complex.re w) (complex.im z + complex.im w) := rfl protected theorem neg_def (z : ℂ) : -z = complex.mk (-(re z)) (-(im z)) := rfl protected theorem mul_def (z w : ℂ) : z * w = complex.mk (complex.re w * complex.re z - complex.im w * complex.im z) (complex.re w * complex.im z + complex.im w * complex.re z) := rfl -- TODO: what notation should we use for i? definition ii := complex.mk 0 1 theorem i_mul_i : ii * ii = -1 := rfl /- basic properties -/ protected theorem add_comm (w z : ℂ) : w + z = z + w := complex.eq !add.comm !add.comm protected theorem add_assoc (w z u : ℂ) : (w + z) + u = w + (z + u) := complex.eq !add.assoc !add.assoc protected theorem add_zero (z : ℂ) : z + 0 = z := complex.eq !add_zero !add_zero protected theorem zero_add (z : ℂ) : 0 + z = z := !complex.add_comm ▸ !complex.add_zero definition smul (x : ℝ) (z : ℂ) : ℂ := complex.mk (x*re z) (x*im z) protected theorem add_right_inv : z + - z = 0 := complex.eq !add.right_inv !add.right_inv protected theorem add_left_inv : - z + z = 0 := !complex.add_comm ▸ !complex.add_right_inv protected theorem mul_comm : w * z = z * w := by rewrite [*complex.mul_def, *mul.comm (re w), *mul.comm (im w), add.comm] protected theorem one_mul : 1 * z = z := by krewrite [complex.mul_def, *mul_one, *mul_zero, sub_zero, zero_add, complex.eta] protected theorem mul_one : z * 1 = z := !complex.mul_comm ▸ !complex.one_mul protected theorem left_distrib : u * (w + z) = u * w + u * z := begin rewrite [*complex.mul_def, *complex.add_def, ▸*, *right_distrib, -sub_sub, *sub_eq_add_neg], rewrite [*add.assoc, add.left_comm (re z * im u), add.left_comm (-_)] end protected theorem right_distrib : (u + w) * z = u * z + w * z := by rewrite [*complex.mul_comm _ z, complex.left_distrib] protected theorem mul_assoc : (u * w) * z = u * (w * z) := begin rewrite [*complex.mul_def, ▸*, *sub_eq_add_neg, *left_distrib, *right_distrib, *neg_add], rewrite [-*neg_mul_eq_neg_mul, -*neg_mul_eq_mul_neg, *add.assoc, *mul.assoc], rewrite [add.comm (-(im z * (im w * _))), add.comm (-(im z * (im w * _))), *add.assoc] end theorem re_add (z w : ℂ) : re (z + w) = re z + re w := rfl theorem im_add (z w : ℂ) : im (z + w) = im z + im w := rfl /- coercions -/ theorem of_real_add (a b : ℝ) : of_real (a + b) = of_real a + of_real b := rfl theorem of_real_mul (a b : ℝ) : of_real (a * b) = (of_real a) * (of_real b) := by rewrite [complex.mul_def, *re_of_real, *im_of_real, *mul_zero, *zero_mul, sub_zero, add_zero, mul.comm] theorem of_real_neg (a : ℝ) : of_real (-a) = -(of_real a) := rfl theorem of_real.inj {a b : ℝ} (H : of_real a = of_real b) : a = b := show re (of_real a) = re (of_real b), from congr_arg re H theorem eq_of_of_real_eq_of_real {a b : ℝ} (H : of_real a = of_real b) : a = b := of_real.inj H theorem of_real_eq_of_real_iff (a b : ℝ) : of_real a = of_real b ↔ a = b := iff.intro eq_of_of_real_eq_of_real !congr_arg /- make complex an instance of ring -/ attribute [reducible] protected definition comm_ring : comm_ring complex := begin fapply comm_ring.mk, exact complex.add, exact complex.add_assoc, exact 0, exact complex.zero_add, exact complex.add_zero, exact complex.neg, exact complex.add_left_inv, exact complex.add_comm, exact complex.mul, exact complex.mul_assoc, exact 1, apply complex.one_mul, apply complex.mul_one, apply complex.left_distrib, apply complex.right_distrib, apply complex.mul_comm end local attribute complex.comm_ring [instance] attribute [instance, priority complex.prio] definition complex_has_sub : has_sub complex := has_sub.mk has_sub.sub theorem of_real_sub (x y : ℝ) : of_real (x - y) = of_real x - of_real y := rfl /- complex modulus and conjugate-/ definition cmod (z : ℂ) : ℝ := (complex.re z) * (complex.re z) + (complex.im z) * (complex.im z) theorem cmod_zero : cmod 0 = 0 := rfl theorem cmod_of_real (x : ℝ) : cmod x = x * x := by rewrite [↑cmod, re_of_real, im_of_real, mul_zero, add_zero] theorem eq_zero_of_cmod_eq_zero {z : ℂ} (H : cmod z = 0) : z = 0 := have H1 : (complex.re z) * (complex.re z) + (complex.im z) * (complex.im z) = 0, from H, have H2 : complex.re z = 0, from eq_zero_of_mul_self_add_mul_self_eq_zero H1, have H3 : complex.im z = 0, from eq_zero_of_mul_self_add_mul_self_eq_zero (!add.comm ▸ H1), show z = 0, from complex.eq H2 H3 definition conj (z : ℂ) : ℂ := complex.mk (complex.re z) (-(complex.im z)) theorem conj_of_real {x : ℝ} : conj (of_real x) = of_real x := rfl theorem conj_add (z w : ℂ) : conj (z + w) = conj z + conj w := by rewrite [↑conj, *complex.add_def, ▸*, neg_add] theorem conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w := by rewrite [↑conj, *complex.mul_def, ▸*, neg_mul_neg, neg_add, -neg_mul_eq_mul_neg, -neg_mul_eq_neg_mul] theorem conj_conj (z : ℂ) : conj (conj z) = z := by rewrite [↑conj, neg_neg, complex.eta] theorem mul_conj_eq_of_real_cmod (z : ℂ) : z * conj z = of_real (cmod z) := by rewrite [↑conj, ↑cmod, ↑of_real, complex.mul_def, ▸*, -*neg_mul_eq_neg_mul, sub_neg_eq_add, mul.comm (re z) (im z), add.right_inv] theorem cmod_conj (z : ℂ) : cmod (conj z) = cmod z := begin apply eq_of_of_real_eq_of_real, rewrite [-*mul_conj_eq_of_real_cmod, conj_conj, mul.comm] end theorem cmod_mul (z w : ℂ) : cmod (z * w) = cmod z * cmod w := begin apply eq_of_of_real_eq_of_real, rewrite [of_real_mul, -*mul_conj_eq_of_real_cmod, conj_mul, *mul.assoc, mul.left_comm w] end protected noncomputable definition inv (z : ℂ) : complex := conj z * of_real (cmod z)⁻¹ attribute [instance, priority complex.prio] protected noncomputable definition complex_has_inv : has_inv complex := has_inv.mk complex.inv protected theorem inv_def (z : ℂ) : z⁻¹ = conj z * of_real (cmod z)⁻¹ := rfl protected theorem inv_zero : 0⁻¹ = (0 : ℂ) := by krewrite [complex.inv_def, conj_of_real, zero_mul] theorem of_real_inv (x : ℝ) : of_real x⁻¹ = (of_real x)⁻¹ := classical.by_cases (assume H : x = 0, by krewrite [H, inv_zero, complex.inv_zero]) (assume H : x ≠ 0, by rewrite [complex.inv_def, cmod_of_real, conj_of_real, mul_inv_eq H H, -of_real_mul, -mul.assoc, mul_inv_cancel H, one_mul]) protected noncomputable definition div (z w : ℂ) : ℂ := z * w⁻¹ attribute [instance, priority complex.prio] noncomputable definition complex_has_div : has_div complex := has_div.mk complex.div protected theorem div_def (z w : ℂ) : z / w = z * w⁻¹ := rfl theorem of_real_div (x y : ℝ) : of_real (x / y) = of_real x / of_real y := have H : x / y = x * y⁻¹, from rfl, by rewrite [H, complex.div_def, of_real_mul, of_real_inv] theorem conj_inv (z : ℂ) : (conj z)⁻¹ = conj (z⁻¹) := by rewrite [*complex.inv_def, conj_mul, *conj_conj, conj_of_real, cmod_conj] protected theorem mul_inv_cancel {z : ℂ} (H : z ≠ 0) : z * z⁻¹ = 1 := by rewrite [complex.inv_def, -mul.assoc, mul_conj_eq_of_real_cmod, -of_real_mul, mul_inv_cancel (assume H', H (eq_zero_of_cmod_eq_zero H'))] protected theorem inv_mul_cancel {z : ℂ} (H : z ≠ 0) : z⁻¹ * z = 1 := !mul.comm ▸ complex.mul_inv_cancel H protected noncomputable definition has_decidable_eq : decidable_eq ℂ := take z w, classical.prop_decidable (z = w) protected theorem zero_ne_one : (0 : ℂ) ≠ 1 := assume H, zero_ne_one (eq_of_of_real_eq_of_real H) attribute [trans_instance] protected noncomputable definition discrete_field : discrete_field ℂ := ⦃ discrete_field, complex.comm_ring, mul_inv_cancel := @complex.mul_inv_cancel, inv_mul_cancel := @complex.inv_mul_cancel, zero_ne_one := complex.zero_ne_one, inv_zero := complex.inv_zero, has_decidable_eq := complex.has_decidable_eq ⦄ -- TODO : we still need the whole family of coercion properties, for nat, int, rat -- coercions theorem of_rat_eq (a : ℚ) : of_rat a = of_real (real.of_rat a) := rfl theorem of_int_eq (a : ℤ) : of_int a = of_real (real.of_int a) := rfl theorem of_nat_eq (a : ℕ) : of_nat a = of_real (real.of_nat a) := rfl theorem of_rat.inj {x y : ℚ} (H : of_rat x = of_rat y) : x = y := real.of_rat.inj (of_real.inj H) theorem eq_of_of_rat_eq_of_rat {x y : ℚ} (H : of_rat x = of_rat y) : x = y := of_rat.inj H theorem of_rat_eq_of_rat_iff (x y : ℚ) : of_rat x = of_rat y ↔ x = y := iff.intro eq_of_of_rat_eq_of_rat !congr_arg theorem of_int.inj {a b : ℤ} (H : of_int a = of_int b) : a = b := rat.of_int.inj (of_rat.inj H) theorem eq_of_of_int_eq_of_int {a b : ℤ} (H : of_int a = of_int b) : a = b := of_int.inj H theorem of_int_eq_of_int_iff (a b : ℤ) : of_int a = of_int b ↔ a = b := iff.intro of_int.inj !congr_arg theorem of_nat.inj {a b : ℕ} (H : of_nat a = of_nat b) : a = b := int.of_nat.inj (of_int.inj H) theorem eq_of_of_nat_eq_of_nat {a b : ℕ} (H : of_nat a = of_nat b) : a = b := of_nat.inj H theorem of_nat_eq_of_nat_iff (a b : ℕ) : of_nat a = of_nat b ↔ a = b := iff.intro of_nat.inj !congr_arg open rat theorem of_rat_add (a b : ℚ) : of_rat (a + b) = of_rat a + of_rat b := by rewrite [of_rat_eq] theorem of_rat_neg (a : ℚ) : of_rat (-a) = -of_rat a := by rewrite [of_rat_eq] -- these show why we have to use krewrite in the next theorem: there are -- two different instances of "has_mul". -- set_option pp.notation false -- set_option pp.coercions true -- set_option pp.implicit true theorem of_rat_mul (a b : ℚ) : of_rat (a * b) = of_rat a * of_rat b := by krewrite [of_rat_eq, real.of_rat_mul, of_real_mul] open int theorem of_int_add (a b : ℤ) : of_int (a + b) = of_int a + of_int b := by krewrite [of_int_eq, real.of_int_add, of_real_add] theorem of_int_neg (a : ℤ) : of_int (-a) = -of_int a := by krewrite [of_int_eq, real.of_int_neg, of_real_neg] theorem of_int_mul (a b : ℤ) : of_int (a * b) = of_int a * of_int b := by krewrite [of_int_eq, real.of_int_mul, of_real_mul] open nat theorem of_nat_add (a b : ℕ) : of_nat (a + b) = of_nat a + of_nat b := by krewrite [of_nat_eq, real.of_nat_add, of_real_add] theorem of_nat_mul (a b : ℕ) : of_nat (a * b) = of_nat a * of_nat b := by krewrite [of_nat_eq, real.of_nat_mul, of_real_mul] end complex
49285252ea53c89b01548af8f6323825f698758d
4727251e0cd73359b15b664c3170e5d754078599
/src/meta/coinductive_predicates.lean
1d9941f26d96078bfa2ef738fe84387137308a7a
[ "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,470
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 (CMU) -/ import tactic.core section universe u @[user_attribute] meta def monotonicity : user_attribute := { name := `monotonicity, descr := "Monotonicity rules for predicates" } lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (Πa, p a) (Πa, q a) := assume h' a, h a (h' a) lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) : implies (p → p') (q → q') := assume h, h₁ ∘ h ∘ h₂ @[monotonicity] lemma monotonicity.const (p : Prop) : implies p p := id @[monotonicity] lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial @[monotonicity] lemma monotonicity.false (p : Prop) : implies false p := false.elim @[monotonicity] lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (∃a, p a) (∃a, q a) := exists_imp_exists h @[monotonicity] lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∧ q) (p' ∧ q') := and.imp hp hq @[monotonicity] lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∨ q) (p' ∨ q') := or.imp hp hq @[monotonicity] lemma monotonicity.not {p q : Prop} (h : implies p q) : implies (¬ q) (¬ p) := mt h end namespace tactic open expr tactic /- TODO: use backchaining -/ private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do intros, (do `(implies %%p %%q) ← target, (do is_def_eq p q, eapplyc `monotone.const) <|> (do (expr.pi pn pbi pd pb) ← whnf p, (expr.pi qn qbi qd qb) ← whnf q, sort u ← infer_type pd, (do is_def_eq pd qd, let p' := expr.lam pn pbi pd pb, let q' := expr.lam qn qbi qd qb, eapply ((const `monotonicity.pi [u] : expr) pd p' q'), skip) <|> (do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q, let p' := pb.lower_vars 0 1, let q' := qb.lower_vars 0 1, eapply ((const `monotonicity.imp []: expr) pd p' qd q'), skip))) <|> first (hs.map $ λh, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|> first (ns.map $ λn, do c ← mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip), all_goals' mono_aux meta def mono (e : expr) (hs : list expr) : tactic unit := do t ← target, t' ← infer_type e, ns ← attribute.get_instances `monotonicity, ((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs), exact (p e) end tactic /- The coinductive predicate `pred`: coinductive {u} pred (A) : a → Prop | r : ∀A b, pred A p where `u` is a list of universe parameters `A` is a list of global parameters `pred` is a list predicates to be defined `a` are the indices for each `pred` `r` is a list of introduction rules for each `pred` `b` is a list of parameters for each rule in `r` and `pred` `p` is are the instances of `a` using `A` and `b` `pred` is compiled to the following defintions: inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop | r : ∀a [f], b[pred/pred'] → pred.functional a [f] p lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] : ∀p, pred.functional A pred₁ p → pred.functional A pred₂ p def {u} pred_i (A) (a) : Prop := ∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] : ∀a, C_i a → pred_i A a lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a) [Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a lemma {u} pred.r (A) (b) : pred_i A p -/ namespace tactic open level expr tactic namespace add_coinductive_predicate /- private -/ meta structure coind_rule : Type := (orig_nm : name) (func_nm : name) (type : expr) (loc_type : expr) (args : list expr) (loc_args : list expr) (concl : expr) (insts : list expr) /- private -/ meta structure coind_pred : Type := (u_names : list name) (params : list expr) (pd_name : name) (type : expr) (intros : list coind_rule) (locals : list expr) (f₁ f₂ : expr) (u_f : level) namespace coind_pred meta def u_params (pd : coind_pred) : list level := pd.u_names.map param meta def f₁_l (pd : coind_pred) : expr := pd.f₁.app_of_list pd.locals meta def f₂_l (pd : coind_pred) : expr := pd.f₂.app_of_list pd.locals meta def pred (pd : coind_pred) : expr := const pd.pd_name pd.u_params meta def func (pd : coind_pred) : expr := const (pd.pd_name ++ "functional") pd.u_params meta def func_g (pd : coind_pred) : expr := pd.func.app_of_list $ pd.params meta def pred_g (pd : coind_pred) : expr := pd.pred.app_of_list $ pd.params meta def impl_locals (pd : coind_pred) : list expr := pd.locals.map to_implicit_binder meta def impl_params (pd : coind_pred) : list expr := pd.params.map to_implicit_binder meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr := (imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals meta def corec_functional (pd : coind_pred) : expr := const (pd.pd_name ++ "corec_functional") pd.u_params meta def mono (pd : coind_pred) : expr := const (pd.func.const_name ++ "mono") pd.u_params meta def rec' (pd : coind_pred) : tactic expr := do let c := pd.func.const_name ++ "rec", env ← get_env, decl ← env.get c, let num := decl.univ_params.length, return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params) -- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false meta def construct (pd : coind_pred) : expr := const (pd.pd_name ++ "construct") pd.u_params meta def destruct (pd : coind_pred) : expr := const (pd.pd_name ++ "destruct") pd.u_params meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr := add_theorem_by n pd.u_names type tac end coind_pred end add_coinductive_predicate open add_coinductive_predicate /-- compact_relation bs as_ps: Product a relation of the form: R := λ as, ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/ meta def compact_relation : list expr → list (expr × expr) → list expr × list (expr × expr) | [] ps := ([], ps) | (list.cons b bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) end meta def add_coinductive_predicate (u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do let params_names := params.map local_pp_name, let u_params := u_names.map param, pre_info ← preds.mmap (λ⟨c, is⟩, do (ls, t) ← open_pis c.local_type, (is_def_eq t `(Prop) <|> fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++ "coinductive predicates are supported.")), let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string, f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type, f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type, return (ls, (f₁, f₂))), let fs := pre_info.map prod.snd, let fs₁ := fs.map prod.fst, let fs₂ := fs.map prod.snd, pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do sort u_f ← infer_type f₁ >>= infer_type, let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params, intros ← is.mmap (λi, do (args, t') ← open_pis i.local_type, (name.mk_string sub p) ← return i.local_uniq_name, let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩, e.replace_with (pred_g c) f) e, let t' := t'.replace_with (pred_g c) f₂, return { tactic.add_coinductive_predicate.coind_rule . orig_nm := i.local_uniq_name, func_nm := (p ++ "functional") ++ sub, type := i.local_type, loc_type := t'.pis loc_args, concl := t', loc_args := loc_args, args := args, insts := t'.get_app_args }), return { tactic.add_coinductive_predicate.coind_pred . pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f, intros := intros, locals := ls, params := params, u_names := u_names }), /- Introduce all functionals -/ pds.mmap' (λpd:coind_pred, do let func_f₁ := pd.func_g.app_of_list $ fs₁, let func_f₂ := pd.func_g.app_of_list $ fs₂, /- Define functional for `pd` as inductive predicate -/ func_intros ← pd.intros.mmap (λr:coind_rule, do let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type, return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)), add_inductive pd.func.const_name u_names (params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)), /- Prove monotonicity rule -/ mono_params ← pds.mmap (λpd, do h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂, return [pd.f₁, pd.f₂, h]), pd.add_theorem (pd.func.const_name ++ "mono") ((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join) (do ps ← intro_lst $ params.map expr.local_pp_name, fs ← pds.mmap (λpd, do [f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h], -- the type of h' reduces to h let h' := local_const h.local_uniq_name h.local_pp_name h.local_binding_info $ (((const `implies [] : expr) (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $ (ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv), return (f₂, h')), m ← pd.rec', eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work? func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do bs ← intros, ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all}, params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, bnot <$> is_assigned m.2), params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|> fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))), pds.mmap' (λpd, do let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁, /- define final predicate -/ pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $ mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals], add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $ pred_body.lambdas $ params ++ pd.locals, /- prove `corec_functional` rule -/ hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd), pd.add_theorem (pd.pred.const_name ++ "corec_functional") ((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs) (do intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, hs ← intro_lst $ hs.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, whnf_target, fs.mmap' existsi, hs.mmap' (λf, econstructor >> exact f), exact h)), let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g, /- prove `destruct` rules -/ pds.enum.mmap' (λ⟨n, pd⟩, do let destruct := pd.le pd.pred_g (func_f pd), pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do ps ← intro_lst $ params.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, (fs, h, _) ← elim_gen_prod pds.length h [] [], (hs, h, _) ← elim_gen_prod pds.length h [] [], eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd:coind_pred, focus1 $ do eapply $ pd.corec_functional, focus $ hs.map exact), some h' ← return $ hs.nth n, eapply h', exact h)), /- prove `construct` rules -/ pds.mmap' (λpd, pd.add_theorem (pd.pred.const_name ++ "construct") ((pd.le (func_f pd) pd.pred_g).pis params) (do ps ← intro_lst $ params.map local_pp_name, let func_pred_g := λpd:coind_pred, pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps), eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g, pds.mmap' (λpd:coind_pred, solve1 $ do eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd, solve1 $ eapply (pd.destruct.app_of_list ps) >> skip)))), /- prove `cases_on` rules -/ pds.mmap' (λpd, do let C := pd.f₁.to_implicit_binder, h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals, rules ← pd.intros.mmap (λr:coind_rule, do mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args), cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on") ((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, C ← intro `C, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, func_rec ← pd.rec', eapply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules, eapply $ pd.destruct, exact h), set_basic_attribute `elab_as_eliminator cases_on.const_name), /- prove `corec_on` rules -/ pds.mmap' (λpd, do rules ← pds.mmap (λpd, do intros ← pd.intros.mmap (λr, do let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts, eqs ← eqs.mmap (λ⟨l, i⟩, do sort u ← infer_type l.local_type, return $ (const `eq [u] : expr) l.local_type i l), match bs, eqs with | [], [] := return ((0, 0), mk_true) | _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type | _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs) end), let shape := intros.map prod.fst, let intros := intros.map prod.snd, prod.mk shape <$> mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string) (((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)), let shape := rules.map prod.fst, let rules := rules.map prod.snd, h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals, pd.add_theorem (pd.pred.const_name ++ "corec_on") ((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, eapply $ pd.corec_functional.app_of_list $ ps ++ fs, (pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do ls ← intro_lst $ pd.locals.map local_pp_name, h' ← intro `h, h' ← note `h' none $ hr.app_of_list ls h', match s.length with | 0 := induction h' >> skip -- h' : false | (n+1) := do hs ← elim_gen_sum n h', (hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do (as, h, _) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [] [], if n_eqs > 0 then do (eqs, eq', _) ← elim_gen_prod (n_eqs - 1) h [] [], (eqs ++ [eq']).mmap' subst else skip, eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs), iterate assumption) end), exact h)), /- prove constructors -/ pds.mmap' (λpd, pd.intros.mmap' (λr, pd.add_theorem r.orig_nm (r.type.pis params) $ do ps ← intro_lst $ params.map local_pp_name, bs ← intros, eapply $ pd.construct, exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)), pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name), try triv -- we setup a trivial goal for the tactic framework setup_tactic_parser @[user_command] meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do { decl ← inductive_decl.parse meta_info, add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ λ d, (d.sig, d.intros), decl.decls.mmap' $ λ d, do { get_env >>= λ env, set_env $ env.add_namespace d.name, meta_info.attrs.apply d.name, d.attrs.apply d.name, some doc_string ← pure meta_info.doc_string | skip, add_doc_string d.name doc_string } } /-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from the quantifiers in the current goal. Current version: do not support mutual inductive rules -/ meta def coinduction (rule : expr) (ns : list name) : tactic unit := focus1 $ do ctxts' ← intros, ctxts ← ctxts'.mmap (λv, local_const v.local_uniq_name v.local_pp_name v.local_binding_info <$> infer_type v), mvars ← apply_core rule {approx := ff, new_goals := new_goals.all}, -- analyse relation g ← list.head <$> get_goals, (list.cons _ m_is) ← return $ mvars.drop_while (λv, v.2 ≠ g), tgt ← target, (is, ty) ← open_pis tgt, -- construct coinduction predicate (bs, eqs) ← compact_relation ctxts <$> ((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m.2)), solve1 (do eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars) <|> do { x ← mk_psigma (eqs.map prod.fst), y ← mk_psigma (eqs.map prod.snd), t ← infer_type x, mk_mapp `eq [t,x,y] }, rel ← mk_exists_lst bs eqs, exact (rel.lambdas is)), -- prove predicate solve1 (do target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis bs.mmap existsi, iterate' (econstructor >> skip)), -- clean up remaining coinduction steps all_goals' (do ctxts'.reverse.mmap clear, target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis is ← intro_lst $ is.map expr.local_pp_name, h ← intro1, (_, h, ns) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [] ns, (match eqs with | [] := clear h | (e::eqs) := do (hs, h, ns) ← elim_gen_prod eqs.length h [] ns, (h::(hs.reverse) : list _).mfoldl (λ (hs : list name) (h : expr), do [(_,hs',σ)] ← cases_core h hs, clear (h.instantiate_locals σ), pure $ hs.drop hs'.length) ns, skip end)) namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many meta def coinduction (corec_name : parse ident) (ns : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do rule ← mk_const corec_name, locals ← mmap tactic.get_local $ revert.get_or_else [], revert_lst locals, tactic.coinduction rule ns, skip end interactive end tactic
7580d2104829c2c8144137f7157e38c535156c1c
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/ring_theory/derivation.lean
f0da3c1d8d5214e695d298ff08899b074a25e62a
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,359
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import algebra.lie.of_associative import ring_theory.algebra_tower /-! # Derivations This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an `R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`. ## Notation The notation `⁅D1, D2⁆` is used for the commutator of two derivations. TODO: this file is just a stub to go on with some PRs in the geometry section. It only implements the definition of derivations in commutative algebra. This will soon change: as soon as bimodules will be there in mathlib I will change this file to take into account the non-commutative case. Any development on the theory of derivations is discouraged until the definitive definition of derivation will be implemented. -/ open algebra ring_hom /-- `D : derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz` equality. TODO: update this when bimodules are defined. -/ @[protect_proj] structure derivation (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] (M : Type*) [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] extends A →ₗ[R] M := (leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a) namespace derivation section variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] variables [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩ instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) := ⟨λ D, D.to_linear_map⟩ @[simp] lemma to_fun_eq_coe : D.to_fun = ⇑D := rfl @[simp, norm_cast] lemma coe_fn_coe (f : derivation R A M) : ⇑(f : A →ₗ[R] M) = f := rfl lemma coe_injective (H : ⇑D1 = D2) : D1 = D2 := by { cases D1, cases D2, congr', exact linear_map.coe_injective H } @[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 := coe_injective $ funext H @[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b @[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D @[simp] lemma map_smul : D (r • a) = r • D a := linear_map.map_smul D r a @[simp] lemma leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _ @[simp] lemma map_one_eq_zero : D 1 = 0 := begin have h : D 1 = D (1 * 1) := by rw mul_one, rwa [leibniz D 1 1, one_smul, self_eq_add_right] at h end @[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 := by rw [←mul_one r, ring_hom.map_mul, map_one, ←smul_def, map_smul, map_one_eq_zero, smul_zero] instance : has_zero (derivation R A M) := ⟨⟨(0 : A →ₗ[R] M), λ a b, by simp only [add_zero, linear_map.zero_apply, linear_map.to_fun_eq_coe, smul_zero]⟩⟩ instance : inhabited (derivation R A M) := ⟨0⟩ instance : add_comm_monoid (derivation R A M) := { add := λ D1 D2, ⟨D1 + D2, λ a b, by { simp only [leibniz, linear_map.add_apply, linear_map.to_fun_eq_coe, coe_fn_coe, smul_add], cc }⟩, add_assoc := λ D E F, ext $ λ a, add_assoc _ _ _, zero_add := λ D, ext $ λ a, zero_add _, add_zero := λ D, ext $ λ a, add_zero _, add_comm := λ D E, ext $ λ a, add_comm _ _, ..derivation.has_zero } @[simp] lemma add_apply : (D1 + D2) a = D1 a + D2 a := rfl @[priority 100] instance derivation.Rsemimodule : semimodule R (derivation R A M) := { smul := λ r D, ⟨r • D, λ a b, by simp only [linear_map.smul_apply, leibniz, linear_map.to_fun_eq_coe, smul_algebra_smul_comm, coe_fn_coe, smul_add, add_comm],⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul _ _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul _ _ } @[simp] lemma smul_to_linear_map_coe : ↑(r • D) = (r • D : A →ₗ[R] M) := rfl @[simp] lemma Rsmul_apply : (r • D) a = r • D a := rfl instance : semimodule A (derivation R A M) := { smul := λ a D, ⟨a • D, λ b c, by { dsimp, simp only [smul_add, leibniz, smul_comm a, add_comm] }⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul A _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul A _ } @[simp] lemma smul_apply : (a • D) b = a • D b := rfl instance : is_scalar_tower R A (derivation R A M) := ⟨λ x y z, ext (λ a, smul_assoc _ _ _)⟩ end section variables {R : Type*} [comm_ring R] variables {A : Type*} [comm_ring A] [algebra R A] section variables {M : Type*} [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) @[simp] lemma map_neg : D (-a) = -D a := linear_map.map_neg D a @[simp] lemma map_sub : D (a - b) = D a - D b := linear_map.map_sub D a b instance : add_comm_group (derivation R A M) := { neg := λ D, ⟨-D, λ a b, by simp only [linear_map.neg_apply, smul_neg, neg_add_rev, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, add_comm]⟩, sub := λ D1 D2, ⟨D1 - D2, λ a b, by { simp only [linear_map.to_fun_eq_coe, linear_map.sub_apply, leibniz, coe_fn_coe, smul_sub], abel }⟩, sub_eq_add_neg := λ D1 D2, ext (λ i, sub_eq_add_neg _ _), add_left_neg := λ D, ext $ λ a, add_left_neg _, ..derivation.add_comm_monoid } @[simp] lemma sub_apply : (D1 - D2) a = D1 a - D2 a := rfl end section lie_structures /-! # Lie structures -/ variables (D : derivation R A A) {D1 D2 : derivation R A A} (r : R) (a b : A) /-- The commutator of derivations is again a derivation. -/ def commutator (D1 D2 : derivation R A A) : derivation R A A := { leibniz' := λ a b, by { simp only [ring.lie_def, map_add, id.smul_eq_mul, linear_map.mul_app, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, linear_map.sub_apply], ring, }, ..⁅(D1 : module.End R A), (D2 : module.End R A)⁆, } instance : has_bracket (derivation R A A) (derivation R A A) := ⟨derivation.commutator⟩ @[simp] lemma commutator_coe_linear_map : ↑⁅D1, D2⁆ = ⁅(D1 : module.End R A), (D2 : module.End R A)⁆ := rfl lemma commutator_apply : ⁅D1, D2⁆ a = D1 (D2 a) - D2 (D1 a) := rfl instance : lie_ring (derivation R A A) := { add_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, lie_add := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, lie_self := λ d, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, leibniz_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, sub_apply, map_sub], ring, } } instance : lie_algebra R (derivation R A A) := { lie_smul := λ r d e, by { ext a, simp only [commutator_apply, map_smul, smul_sub, Rsmul_apply]}, ..derivation.Rsemimodule } end lie_structures end end derivation section comp_der namespace linear_map variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] variables {N : Type*} [add_cancel_comm_monoid N] [semimodule A N] [semimodule R N] variables [is_scalar_tower R A M] [is_scalar_tower R A N] /-- The composition of a linear map and a derivation is a derivation. -/ def comp_der (f : M →ₗ[A] N) (D : derivation R A M) : derivation R A N := { to_fun := λ a, f (D a), map_add' := λ a1 a2, by rw [D.map_add, f.map_add], map_smul' := λ r a, by rw [derivation.map_smul, map_smul_of_tower], leibniz' := λ a b, by simp only [derivation.leibniz, linear_map.map_smul, linear_map.map_add, add_comm] } @[simp] lemma comp_der_apply (f : M →ₗ[A] N) (D : derivation R A M) (a : A) : f.comp_der D a = f (D a) := rfl end linear_map end comp_der
ca6bc8c3c95eb4740a157cdb9d43e6b9c96c4720
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/field_theory/subfield.lean
ff5ad04bbe09505368fd34086ef0937464ba5d0a
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,179
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.algebra.basic /-! # Subfields Let `K` be a field. This file defines the "bundled" subfield type `subfield K`, a type whose terms correspond to subfields of `K`. This is the preferred way to talk about subfields in mathlib. Unbundled subfields (`s : set K` and `is_subfield s`) are not in this file, and they will ultimately be deprecated. We prove that subfields are a complete lattice, and that you can `map` (pushforward) and `comap` (pull back) them along ring homomorphisms. We define the `closure` construction from `set R` to `subfield R`, sending a subset of `R` to the subfield it generates, and prove that it is a Galois insertion. ## Main definitions Notation used here: `(K : Type u) [field K] (L : Type u) [field L] (f g : K →+* L)` `(A : subfield K) (B : subfield L) (s : set K)` * `subfield R` : the type of subfields of a ring `R`. * `instance : complete_lattice (subfield R)` : the complete lattice structure on the subfields. * `subfield.closure` : subfield closure of a set, i.e., the smallest subfield that includes the set. * `subfield.gi` : `closure : set M → subfield M` and coercion `coe : subfield M → set M` form a `galois_insertion`. * `comap f B : subfield K` : the preimage of a subfield `B` along the ring homomorphism `f` * `map f A : subfield L` : the image of a subfield `A` along the ring homomorphism `f`. * `prod A B : subfield (K × L)` : the product of subfields * `f.field_range : subfield B` : the range of the ring homomorphism `f`. * `eq_locus_field f g : subfield K` : given ring homomorphisms `f g : K →+* R`, the subfield of `K` where `f x = g x` ## Implementation notes A subfield is implemented as a subring which is is closed under `⁻¹`. Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although `∈` is defined as membership of a subfield's underlying set. ## Tags subfield, subfields -/ open_locale big_operators universes u v w variables {K : Type u} {L : Type v} {M : Type w} [field K] [field L] [field M] set_option old_structure_cmd true /-- `subfield R` is the type of subfields of `R`. A subfield of `R` is a subset `s` that is a multiplicative submonoid and an additive subgroup. Note in particular that it shares the same 0 and 1 as R. -/ structure subfield (K : Type u) [field K] extends subring K := (inv_mem' : ∀ x ∈ carrier, x⁻¹ ∈ carrier) /-- Reinterpret a `subfield` as a `subring`. -/ add_decl_doc subfield.to_subring namespace subfield /-- The underlying `add_subgroup` of a subfield. -/ def to_add_subgroup (s : subfield K) : add_subgroup K := { ..s.to_subring.to_add_subgroup } /-- The underlying submonoid of a subfield. -/ def to_submonoid (s : subfield K) : submonoid K := { ..s.to_subring.to_submonoid } instance : set_like (subfield K) K := ⟨subfield.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {s : subfield K} {x : K} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp] lemma mem_mk {S : set K} {x : K} (h₁ h₂ h₃ h₄ h₅ h₆) : x ∈ (⟨S, h₁, h₂, h₃, h₄, h₅, h₆⟩ : subfield K) ↔ x ∈ S := iff.rfl @[simp] lemma coe_set_mk (S : set K) (h₁ h₂ h₃ h₄ h₅ h₆) : ((⟨S, h₁, h₂, h₃, h₄, h₅, h₆⟩ : subfield K) : set K) = S := rfl @[simp] lemma mk_le_mk {S S' : set K} (h₁ h₂ h₃ h₄ h₅ h₆ h₁' h₂' h₃' h₄' h₅' h₆') : (⟨S, h₁, h₂, h₃, h₄, h₅, h₆⟩ : subfield K) ≤ (⟨S', h₁', h₂', h₃', h₄', h₅', h₆'⟩ : subfield K) ↔ S ⊆ S' := iff.rfl /-- Two subfields are equal if they have the same elements. -/ @[ext] theorem ext {S T : subfield K} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a subfield with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : subfield K) (s : set K) (hs : s = ↑S) : subfield K := { carrier := s, inv_mem' := hs.symm ▸ S.inv_mem', ..S.to_subring.copy s hs } @[simp] lemma coe_copy (S : subfield K) (s : set K) (hs : s = ↑S) : (S.copy s hs : set K) = s := rfl lemma copy_eq (S : subfield K) (s : set K) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs @[simp] lemma coe_to_subring (s : subfield K) : (s.to_subring : set K) = s := rfl @[simp] lemma mem_to_subring (s : subfield K) (x : K) : x ∈ s.to_subring ↔ x ∈ s := iff.rfl end subfield /-- A `subring` containing inverses is a `subfield`. -/ def subring.to_subfield (s : subring K) (hinv : ∀ x ∈ s, x⁻¹ ∈ s) : subfield K := { inv_mem' := hinv ..s } namespace subfield variables (s t : subfield K) /-- A subfield contains the ring's 1. -/ theorem one_mem : (1 : K) ∈ s := s.one_mem' /-- A subfield contains the ring's 0. -/ theorem zero_mem : (0 : K) ∈ s := s.zero_mem' /-- A subfield is closed under multiplication. -/ theorem mul_mem : ∀ {x y : K}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem' /-- A subfield is closed under addition. -/ theorem add_mem : ∀ {x y : K}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem' /-- A subfield is closed under negation. -/ theorem neg_mem : ∀ {x : K}, x ∈ s → -x ∈ s := s.neg_mem' /-- A subfield is closed under subtraction. -/ theorem sub_mem {x y : K} : x ∈ s → y ∈ s → x - y ∈ s := s.to_subring.sub_mem /-- A subfield is closed under inverses. -/ theorem inv_mem : ∀ {x : K}, x ∈ s → x⁻¹ ∈ s := s.inv_mem' /-- A subfield is closed under division. -/ theorem div_mem {x y : K} (hx : x ∈ s) (hy : y ∈ s) : x / y ∈ s := by { rw div_eq_mul_inv, exact s.mul_mem hx (s.inv_mem hy) } /-- Product of a list of elements in a subfield is in the subfield. -/ lemma list_prod_mem {l : list K} : (∀ x ∈ l, x ∈ s) → l.prod ∈ s := s.to_submonoid.list_prod_mem /-- Sum of a list of elements in a subfield is in the subfield. -/ lemma list_sum_mem {l : list K} : (∀ x ∈ l, x ∈ s) → l.sum ∈ s := s.to_add_subgroup.list_sum_mem /-- Product of a multiset of elements in a subfield is in the subfield. -/ lemma multiset_prod_mem (m : multiset K) : (∀ a ∈ m, a ∈ s) → m.prod ∈ s := s.to_submonoid.multiset_prod_mem m /-- Sum of a multiset of elements in a `subfield` is in the `subfield`. -/ lemma multiset_sum_mem (m : multiset K) : (∀ a ∈ m, a ∈ s) → m.sum ∈ s := s.to_add_subgroup.multiset_sum_mem m /-- Product of elements of a subfield indexed by a `finset` is in the subfield. -/ lemma prod_mem {ι : Type*} {t : finset ι} {f : ι → K} (h : ∀ c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := s.to_submonoid.prod_mem h /-- Sum of elements in a `subfield` indexed by a `finset` is in the `subfield`. -/ lemma sum_mem {ι : Type*} {t : finset ι} {f : ι → K} (h : ∀ c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := s.to_add_subgroup.sum_mem h lemma pow_mem {x : K} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n lemma gsmul_mem {x : K} (hx : x ∈ s) (n : ℤ) : n • x ∈ s := s.to_add_subgroup.gsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : K) ∈ s := by simp only [← gsmul_one, gsmul_mem, one_mem] instance : ring s := s.to_subring.to_ring instance : has_div s := ⟨λ x y, ⟨x / y, s.div_mem x.2 y.2⟩⟩ instance : has_inv s := ⟨λ x, ⟨x⁻¹, s.inv_mem x.2⟩⟩ /-- A subfield inherits a field structure -/ instance to_field : field s := subtype.coe_injective.field coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subfield of a `linear_ordered_field` is a `linear_ordered_field`. -/ instance to_linear_ordered_field {K} [linear_ordered_field K] (s : subfield K) : linear_ordered_field s := subtype.coe_injective.linear_ordered_field coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) @[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : K) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_sub (x y : s) : (↑(x - y) : K) = ↑x - ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : K) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : K) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_div (x y : s) : (↑(x / y) : K) = ↑x / ↑y := rfl @[simp, norm_cast] lemma coe_inv (x : s) : (↑(x⁻¹) : K) = (↑x)⁻¹ := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : K) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : s) : K) = 1 := rfl /-- The embedding from a subfield of the field `K` to `K`. -/ def subtype (s : subfield K) : s →+* K := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype } instance to_algebra : algebra s K := ring_hom.to_algebra s.subtype @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl lemma to_subring.subtype_eq_subtype (F : Type*) [field F] (S : subfield F) : S.to_subring.subtype = S.subtype := rfl /-! # Partial order -/ variables (s t) @[simp] lemma mem_to_submonoid {s : subfield K} {x : K} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid : (s.to_submonoid : set K) = s := rfl @[simp] lemma mem_to_add_subgroup {s : subfield K} {x : K} : x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_subgroup : (s.to_add_subgroup : set K) = s := rfl /-! # top -/ /-- The subfield of `K` containing all elements of `K`. -/ instance : has_top (subfield K) := ⟨{ inv_mem' := λ x _, subring.mem_top x, .. (⊤ : subring K)}⟩ instance : inhabited (subfield K) := ⟨⊤⟩ @[simp] lemma mem_top (x : K) : x ∈ (⊤ : subfield K) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subfield K) : set K) = set.univ := rfl /-! # comap -/ variables (f : K →+* L) /-- The preimage of a subfield along a ring homomorphism is a subfield. -/ def comap (s : subfield L) : subfield K := { inv_mem' := λ x hx, show f (x⁻¹) ∈ s, by { rw f.map_inv, exact s.inv_mem hx }, .. s.to_subring.comap f } @[simp] lemma coe_comap (s : subfield L) : (s.comap f : set K) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subfield L} {f : K →+* L} {x : K} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subfield M) (g : L →+* M) (f : K →+* L) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-! # map -/ /-- The image of a subfield along a ring homomorphism is a subfield. -/ def map (s : subfield K) : subfield L := { inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, s.inv_mem hx, f.map_inv x⟩ }, .. s.to_subring.map f } @[simp] lemma coe_map : (s.map f : set L) = f '' s := rfl @[simp] lemma mem_map {f : K →+* L} {s : subfield K} {y : L} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex lemma map_map (g : L →+* M) (f : K →+* L) : (s.map f).map g = s.map (g.comp f) := set_like.ext' $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : K →+* L} {s : subfield K} {t : subfield L} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : K →+* L) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap end subfield namespace ring_hom variables (g : L →+* M) (f : K →+* L) /-! # range -/ /-- The range of a ring homomorphism, as a subfield of the target. See Note [range copy pattern]. -/ def field_range : subfield L := ((⊤ : subfield K).map f).copy (set.range f) set.image_univ.symm @[simp] lemma coe_field_range : (f.field_range : set L) = set.range f := rfl @[simp] lemma mem_field_range {f : K →+* L} {y : L} : y ∈ f.field_range ↔ ∃ x, f x = y := iff.rfl lemma field_range_eq_map : f.field_range = subfield.map f ⊤ := by { ext, simp } lemma map_field_range : f.field_range.map g = (g.comp f).field_range := by simpa only [field_range_eq_map] using (⊤ : subfield K).map_map g f /-- The range of a morphism of fields is a fintype, if the domain is a fintype. Note that this instance can cause a diamond with `subtype.fintype` if `L` is also a fintype.-/ instance fintype_field_range [fintype K] [decidable_eq L] (f : K →+* L) : fintype f.field_range := set.fintype_range f end ring_hom namespace subfield /-! # inf -/ /-- The inf of two subfields is their intersection. -/ instance : has_inf (subfield K) := ⟨λ s t, { inv_mem' := λ x hx, subring.mem_inf.mpr ⟨s.inv_mem (subring.mem_inf.mp hx).1, t.inv_mem (subring.mem_inf.mp hx).2⟩, .. s.to_subring ⊓ t.to_subring }⟩ @[simp] lemma coe_inf (p p' : subfield K) : ((p ⊓ p' : subfield K) : set K) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subfield K} {x : K} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subfield K) := ⟨λ S, { inv_mem' := begin rintros x hx, apply subring.mem_Inf.mpr, rintro _ ⟨p, p_mem, rfl⟩, exact p.inv_mem (subring.mem_Inf.mp hx p.to_subring ⟨p, p_mem, rfl⟩), end, .. Inf (subfield.to_subring '' S) }⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subfield K)) : ((Inf S : subfield K) : set K) = ⋂ s ∈ S, ↑s := show ((Inf (subfield.to_subring '' S) : subring K) : set K) = ⋂ s ∈ S, ↑s, begin ext x, rw [subring.coe_Inf, set.mem_Inter, set.mem_Inter], exact ⟨λ h s s' ⟨s_mem, s'_eq⟩, h s.to_subring _ ⟨⟨s, s_mem, rfl⟩, s'_eq⟩, λ h s s' ⟨⟨s'', s''_mem, s_eq⟩, (s'_eq : ↑s = s')⟩, h s'' _ ⟨s''_mem, by simp [←s_eq, ← s'_eq]⟩⟩ end lemma mem_Inf {S : set (subfield K)} {x : K} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := subring.mem_Inf.trans ⟨λ h p hp, h p.to_subring ⟨p, hp, rfl⟩, λ h p ⟨p', hp', p_eq⟩, p_eq ▸ h p' hp'⟩ @[simp] lemma Inf_to_subring (s : set (subfield K)) : (Inf s).to_subring = ⨅ t ∈ s, subfield.to_subring t := begin ext x, rw [mem_to_subring, mem_Inf], erw subring.mem_Inf, exact ⟨λ h p ⟨p', hp⟩, hp ▸ subring.mem_Inf.mpr (λ p ⟨hp', hp⟩, hp ▸ h _ hp'), λ h p hp, h p.to_subring ⟨p, subring.ext (λ x, ⟨λ hx, subring.mem_Inf.mp hx _ ⟨hp, rfl⟩, λ hx, subring.mem_Inf.mpr (λ p' ⟨hp, p'_eq⟩, p'_eq ▸ hx)⟩)⟩⟩ end lemma is_glb_Inf (S : set (subfield K)) : is_glb S (Inf S) := begin refine is_glb.of_image (λ s t, show (s : set K) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) _, convert is_glb_binfi, exact coe_Inf _ end /-- Subfields of a ring form a complete lattice. -/ instance : complete_lattice (subfield K) := { top := ⊤, le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subfield K) is_glb_Inf } /-! # subfield closure of a subset -/ /-- The `subfield` generated by a set. -/ def closure (s : set K) : subfield K := { carrier := { (x / y) | (x ∈ subring.closure s) (y ∈ subring.closure s) }, zero_mem' := ⟨0, subring.zero_mem _, 1, subring.one_mem _, div_one _⟩, one_mem' := ⟨1, subring.one_mem _, 1, subring.one_mem _, div_one _⟩, neg_mem' := λ x ⟨y, hy, z, hz, x_eq⟩, ⟨-y, subring.neg_mem _ hy, z, hz, x_eq ▸ neg_div _ _⟩, inv_mem' := λ x ⟨y, hy, z, hz, x_eq⟩, ⟨z, hz, y, hy, x_eq ▸ inv_div.symm⟩, add_mem' := λ x y x_mem y_mem, begin obtain ⟨nx, hnx, dx, hdx, rfl⟩ := id x_mem, obtain ⟨ny, hny, dy, hdy, rfl⟩ := id y_mem, by_cases hx0 : dx = 0, { rwa [hx0, div_zero, zero_add] }, by_cases hy0 : dy = 0, { rwa [hy0, div_zero, add_zero] }, exact ⟨nx * dy + dx * ny, subring.add_mem _ (subring.mul_mem _ hnx hdy) (subring.mul_mem _ hdx hny), dx * dy, subring.mul_mem _ hdx hdy, (div_add_div nx ny hx0 hy0).symm⟩ end, mul_mem' := λ x y x_mem y_mem, begin obtain ⟨nx, hnx, dx, hdx, rfl⟩ := id x_mem, obtain ⟨ny, hny, dy, hdy, rfl⟩ := id y_mem, exact ⟨nx * ny, subring.mul_mem _ hnx hny, dx * dy, subring.mul_mem _ hdx hdy, (div_mul_div _ _ _ _).symm⟩ end } lemma mem_closure_iff {s : set K} {x} : x ∈ closure s ↔ ∃ (y ∈ subring.closure s) (z ∈ subring.closure s), y / z = x := iff.rfl lemma subring_closure_le (s : set K) : subring.closure s ≤ (closure s).to_subring := λ x hx, ⟨x, hx, 1, subring.one_mem _, div_one x⟩ /-- The subfield generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set K} : s ⊆ closure s := set.subset.trans subring.subset_closure (subring_closure_le s) lemma not_mem_of_not_mem_closure {s : set K} {P : K} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) lemma mem_closure {x : K} {s : set K} : x ∈ closure s ↔ ∀ S : subfield K, s ⊆ S → x ∈ S := ⟨λ ⟨y, hy, z, hz, x_eq⟩ t le, x_eq ▸ t.div_mem (subring.mem_closure.mp hy t.to_subring le) (subring.mem_closure.mp hz t.to_subring le), λ h, h (closure s) subset_closure⟩ /-- A subfield `t` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set K} {t : subfield K} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h x hx, mem_closure.mp hx t h⟩ /-- Subfield closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set K⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set K} {t : subfield K} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1`, and all elements of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set K} {p : K → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p (x⁻¹)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul, @add_neg_self K _ 1 ▸ Hadd _ _ H1 (Hneg _ H1), Hadd, Hneg, Hinv⟩).2 Hs h variable (K) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure K _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {K} /-- Closure of a subfield `S` equals `S`. -/ lemma closure_eq (s : subfield K) : closure (s : set K) = s := (subfield.gi K).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set K) = ⊥ := (subfield.gi K).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set K) = ⊤ := @coe_top K _ ▸ closure_eq ⊤ lemma closure_union (s t : set K) : closure (s ∪ t) = closure s ⊔ closure t := (subfield.gi K).gc.l_sup lemma closure_Union {ι} (s : ι → set K) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subfield.gi K).gc.l_supr lemma closure_sUnion (s : set (set K)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subfield.gi K).gc.l_Sup lemma map_sup (s t : subfield K) (f : K →+* L) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : K →+* L) (s : ι → subfield K) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subfield L) (f : K →+* L) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : K →+* L) (s : ι → subfield L) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : K →+* L) : (⊥ : subfield K).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : K →+* L) : (⊤ : subfield L).comap f = ⊤ := (gc_map_comap f).u_top /-- The underlying set of a non-empty directed Sup of subfields is just a union of the subfields. Note that this fails without the directedness assumption (the union of two subfields is typically not a subfield) -/ lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subfield K} (hS : directed (≤) S) {x : K} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set K)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq], refine λ hx, closure_induction hx (λ x, set.mem_Union.mp) _ _ _ _ _, { exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, obtain ⟨k, hki, hkj⟩ := hS i j, exact ⟨k, (S k).add_mem (hki hi) (hkj hj)⟩ }, { rintros x ⟨i, hi⟩, exact ⟨i, (S i).neg_mem hi⟩ }, { rintros x ⟨i, hi⟩, exact ⟨i, (S i).inv_mem hi⟩ }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, obtain ⟨k, hki, hkj⟩ := hS i j, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subfield K} (hS : directed (≤) S) : ((⨆ i, S i : subfield K) : set K) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subfield K)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : K} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subfield K)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set K) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subfield namespace ring_hom variables {s : subfield K} open subfield /-- Restrict the codomain of a ring homomorphism to a subfield that includes the range. -/ def cod_restrict_field (f : K →+* L) (s : subfield L) (h : ∀ x, f x ∈ s) : K →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } /-- Restriction of a ring homomorphism to a subfield of the domain. -/ def restrict_field (f : K →+* L) (s : subfield K) : s →+* L := f.comp s.subtype @[simp] lemma restrict_field_apply (f : K →+* L) (x : s) : f.restrict_field s x = f x := rfl /-- Restriction of a ring homomorphism to its range interpreted as a subfield. -/ def range_restrict_field (f : K →+* L) : K →+* f.field_range := f.srange_restrict @[simp] lemma coe_range_restrict_field (f : K →+* L) (x : K) : (f.range_restrict_field x : L) = f x := rfl /-- The subfield of elements `x : R` such that `f x = g x`, i.e., the equalizer of f and g as a subfield of R -/ def eq_locus_field (f g : K →+* L) : subfield K := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], carrier := {x | f x = g x}, .. (f : K →+* L).eq_locus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subfield closure. -/ lemma eq_on_field_closure {f g : K →+* L} {s : set K} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus_field g, from closure_le.2 h lemma eq_of_eq_on_subfield_top {f g : K →+* L} (h : set.eq_on f g (⊤ : subfield K)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_of_field_closure_eq_top {s : set K} (hs : closure s = ⊤) {f g : K →+* L} (h : s.eq_on f g) : f = g := eq_of_eq_on_subfield_top $ hs ▸ eq_on_field_closure h lemma field_closure_preimage_le (f : K →+* L) (s : set L) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subfield generated by a set equals the subfield generated by the image of the set. -/ lemma map_field_closure (f : K →+* L) (s : set K) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (field_closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subfield open ring_hom /-- The ring homomorphism associated to an inclusion of subfields. -/ def inclusion {S T : subfield K} (h : S ≤ T) : S →+* T := S.subtype.cod_restrict_field _ (λ x, h x.2) @[simp] lemma field_range_subtype (s : subfield K) : s.subtype.field_range = s := set_like.ext' $ (coe_srange _).trans subtype.range_coe end subfield namespace ring_equiv variables {s t : subfield K} /-- Makes the identity isomorphism from a proof two subfields of a multiplicative monoid are equal. -/ def subfield_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ set_like.ext'_iff.1 h } end ring_equiv namespace subfield variables {s : set K} lemma closure_preimage_le (f : K →+* L) (s : set L) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx end subfield
0d12eacda8ddd8872416af8730765ddc26e9115b
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/logic/unnamed_185.lean
8119aec0fde74915db682f9517af0c386bc35b21
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
394
lean
variables A B C : Prop -- BEGIN example : A → A := λ h : A, h example : A → A := λ h, h example (h₁ : A → B) (h₂ : B → C) : A → C := begin intro h₃, apply h₂ (h₁ h₃) end example (h₁ : A → B) (h₂ : B → C) : A → C := begin intro h₃, exact h₂ (h₁ h₃) end example (h₁ : A → B) (h₂ : B → C) : A → C := λ h₃, h₂ (h₁ h₃) -- END
ad1dc3fed25bba416fd2f6e3fa0f45fb05bbd4d9
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Init/Control/State.lean
4cb6b9c87a0597b89762f165a098813d38f66945
[ "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
3,971
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, Sebastian Ullrich The State monad transformer. -/ prelude import Init.Control.Basic import Init.Control.Id import Init.Control.Except universe u v w def StateT (σ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := σ → m (α × σ) @[inline] def StateT.run {σ : Type u} {m : Type u → Type v} {α : Type u} (x : StateT σ m α) (s : σ) : m (α × σ) := x s @[inline] def StateT.run' {σ : Type u} {m : Type u → Type v} [Functor m] {α : Type u} (x : StateT σ m α) (s : σ) : m α := (·.1) <$> x s @[reducible] def StateM (σ α : Type u) : Type u := StateT σ Id α instance {σ α} [Subsingleton σ] [Subsingleton α] : Subsingleton (StateM σ α) where allEq x y := by apply funext intro s match x s, y s with | (a₁, s₁), (a₂, s₂) => rw [Subsingleton.elim a₁ a₂, Subsingleton.elim s₁ s₂] namespace StateT section variable {σ : Type u} {m : Type u → Type v} variable [Monad m] {α β : Type u} @[inline] protected def pure (a : α) : StateT σ m α := fun s => pure (a, s) @[inline] protected def bind (x : StateT σ m α) (f : α → StateT σ m β) : StateT σ m β := fun s => do let (a, s) ← x s; f a s @[inline] protected def map (f : α → β) (x : StateT σ m α) : StateT σ m β := fun s => do let (a, s) ← x s; pure (f a, s) instance : Monad (StateT σ m) where pure := StateT.pure bind := StateT.bind map := StateT.map @[inline] protected def orElse [Alternative m] {α : Type u} (x₁ : StateT σ m α) (x₂ : Unit → StateT σ m α) : StateT σ m α := fun s => x₁ s <|> x₂ () s @[inline] protected def failure [Alternative m] {α : Type u} : StateT σ m α := fun _ => failure instance [Alternative m] : Alternative (StateT σ m) where failure := StateT.failure orElse := StateT.orElse @[inline] protected def get : StateT σ m σ := fun s => pure (s, s) @[inline] protected def set : σ → StateT σ m PUnit := fun s' _ => pure (⟨⟩, s') @[inline] protected def modifyGet (f : σ → α × σ) : StateT σ m α := fun s => pure (f s) @[inline] protected def lift {α : Type u} (t : m α) : StateT σ m α := fun s => do let a ← t; pure (a, s) instance : MonadLift m (StateT σ m) := ⟨StateT.lift⟩ instance (σ m) [Monad m] : MonadFunctor m (StateT σ m) := ⟨fun f x s => f (x s)⟩ instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (StateT σ m) := { throw := StateT.lift ∘ throwThe ε tryCatch := fun x c s => tryCatchThe ε (x s) (fun e => c e s) } end end StateT /-- Adapter to create a ForIn instance from a ForM instance -/ @[inline] def ForM.forIn [Monad m] [ForM (StateT β (ExceptT β m)) ρ α] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β := do let g a b := .mk do match ← f a b with | .yield b' => pure (.ok (⟨⟩, b')) | .done b' => pure (.error b') match ← forM (m := StateT β (ExceptT β m)) (α := α) x g |>.run b |>.run with | .ok a => pure a.2 | .error a => pure a section variable {σ : Type u} {m : Type u → Type v} instance [Monad m] : MonadStateOf σ (StateT σ m) where get := StateT.get set := StateT.set modifyGet := StateT.modifyGet end instance StateT.monadControl (σ : Type u) (m : Type u → Type v) [Monad m] : MonadControl m (StateT σ m) where stM := fun α => α × σ liftWith := fun f => do let s ← get; liftM (f (fun x => x.run s)) restoreM := fun x => do let (a, s) ← liftM x; set s; pure a instance StateT.tryFinally {m : Type u → Type v} {σ : Type u} [MonadFinally m] [Monad m] : MonadFinally (StateT σ m) where tryFinally' := fun x h s => do let ((a, _), (b, s'')) ← tryFinally' (x s) fun | some (a, s') => h (some a) s' | none => h none s pure ((a, b), s'')
7b8f506d227eb0d688cae6d193c0c4e7291e6785
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/interactive/completionOption.lean
581681072f58b7fdc90438d8f25991544b2dc1a4
[ "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
716
lean
set_option fo --^ textDocument/completion set_option format --^ textDocument/completion set_option format.in --^ textDocument/completion set_option trace.p --^ textDocument/completion set_option trace.pp --^ textDocument/completion set_option trace.pp.ana --^ textDocument/completion set_option trace.pp.analyze --^ textDocument/completion set_option fo true --^ textDocument/completion set_option format. --^ textDocument/completion #check false -- curiously completion with a trailing dot worked even before special casing if triggered on the last token
a2d1352af716daebdb579fe45c00f4f05fc5b17e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/Internalize.lean
6c41cadcb4e6e0629eb014651a15296a2edcc402
[ "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
4,589
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.Compiler.LCNF.Types import Lean.Compiler.LCNF.Bind import Lean.Compiler.LCNF.CompilerM namespace Lean.Compiler.LCNF private def refreshBinderName (binderName : Name) : CompilerM Name := do match binderName with | .num p _ => let r := .num p (← get).nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1 } return r | _ => return binderName namespace Internalize abbrev InternalizeM := StateRefT FVarSubst CompilerM /-- The `InternalizeM` monad is a translator. It "translates" the free variables in the input expressions and `Code`, into new fresh free variables in the local context. -/ instance : MonadFVarSubst InternalizeM true where getSubst := get instance : MonadFVarSubstState InternalizeM where modifySubst := modify private def mkNewFVarId (fvarId : FVarId) : InternalizeM FVarId := do let fvarId' ← Lean.mkFreshFVarId addFVarSubst fvarId fvarId' return fvarId' def internalizeParam (p : Param) : InternalizeM Param := do let binderName ← refreshBinderName p.binderName let type ← normExpr p.type let fvarId ← mkNewFVarId p.fvarId let p := { p with binderName, fvarId, type } modifyLCtx fun lctx => lctx.addParam p return p def internalizeLetDecl (decl : LetDecl) : InternalizeM LetDecl := do let binderName ← refreshBinderName decl.binderName let type ← normExpr decl.type let value ← normLetValue decl.value let fvarId ← mkNewFVarId decl.fvarId let decl := { decl with binderName, fvarId, type, value } modifyLCtx fun lctx => lctx.addLetDecl decl return decl mutual partial def internalizeFunDecl (decl : FunDecl) : InternalizeM FunDecl := do let type ← normExpr decl.type let binderName ← refreshBinderName decl.binderName let params ← decl.params.mapM internalizeParam let value ← internalizeCode decl.value let fvarId ← mkNewFVarId decl.fvarId let decl := { decl with binderName, fvarId, params, type, value } modifyLCtx fun lctx => lctx.addFunDecl decl return decl partial def internalizeCode (code : Code) : InternalizeM Code := do match code with | .let decl k => return .let (← internalizeLetDecl decl) (← internalizeCode k) | .fun decl k => return .fun (← internalizeFunDecl decl) (← internalizeCode k) | .jp decl k => return .jp (← internalizeFunDecl decl) (← internalizeCode k) | .return fvarId => withNormFVarResult (← normFVar fvarId) fun fvarId => return .return fvarId | .jmp fvarId args => withNormFVarResult (← normFVar fvarId) fun fvarId => return .jmp fvarId (← args.mapM normArg) | .unreach type => return .unreach (← normExpr type) | .cases c => withNormFVarResult (← normFVar c.discr) fun discr => do let resultType ← normExpr c.resultType let internalizeAltCode (k : Code) : InternalizeM Code := internalizeCode k let alts ← c.alts.mapM fun | .alt ctorName params k => return .alt ctorName (← params.mapM internalizeParam) (← internalizeAltCode k) | .default k => return .default (← internalizeAltCode k) return .cases { c with discr, alts, resultType } end partial def internalizeCodeDecl (decl : CodeDecl) : InternalizeM CodeDecl := do match decl with | .let decl => return .let (← internalizeLetDecl decl) | .fun decl => return .fun (← internalizeFunDecl decl) | .jp decl => return .jp (← internalizeFunDecl decl) end Internalize /-- Refresh free variables ids in `code`, and store their declarations in the local context. -/ partial def Code.internalize (code : Code) (s : FVarSubst := {}) : CompilerM Code := Internalize.internalizeCode code |>.run' s open Internalize in def Decl.internalize (decl : Decl) (s : FVarSubst := {}): CompilerM Decl := go decl |>.run' s where go (decl : Decl) : InternalizeM Decl := do let type ← normExpr decl.type let params ← decl.params.mapM internalizeParam let value ← internalizeCode decl.value return { decl with type, params, value } /-- Create a fresh local context and internalize the given decls. -/ def cleanup (decl : Array Decl) : CompilerM (Array Decl) := do modify fun _ => {} decl.mapM fun decl => do modify fun s => { s with nextIdx := 1 } decl.internalize def normalizeFVarIds (decl : Decl) : CoreM Decl := do let ngenSaved ← getNGen setNGen {} try CompilerM.run <| decl.internalize finally setNGen ngenSaved end Lean.Compiler.LCNF