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
bb621dbc58cd8bc8b71af7f81c5bfa99f426d86b
22c48ae6a9e6627f926537035c9a55dde9138135
/src/game/intro.lean
79536120cfeb5e77c1e1a72f4edc06f799ada0c9
[ "Apache-2.0" ]
permissive
stanescuUW/rational-number-game
f23826b857266728588c5caf5880aa1fa7f09230
7504b764f7d95e3655a41cd131bd36234d23b1fc
refs/heads/master
1,669,987,436,451
1,597,963,810,000
1,597,963,810,000
289,119,348
0
1
null
null
null
null
UTF-8
Lean
false
false
1,641
lean
/- # The Rational Number Game, version 0.1beta ## By Dan Stanescu # What is this game? Welcome to the rational number game -- a game to help undergraduates learn analysis through Lean, a formal proof verification system. The game explores some basic facts about the rationals, starting with the fact that the square root of two is not a rational number. This game is a sequel to <a href="http://wwwf.imperial.ac.uk/~buzzard/xena/natural_number_game/" target="blank">the natural number game</a>. The levels in the Rational Number Game need to be solved using tactics. To learn how to use these tactics, I would recommend that you first play the Natural Number Game up to at least "Advanced Proposition world". I will not go through a careful explanation of the tactics taught by the natural number game here. Blue nodes in the graph on the right are ones that you are ready to enter. Gray nodes you should stay away from -- try blue ones higher up the chain first. Green nodes are completed. # Thanks Many thanks to both Kevin Buzzard and Mohammad Pedramfar, without whom this game would not exist. # Questions? You can ask questions on the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a>, where I am often to be found. You can also ask me questions if you take a class with me, or bump into me somewhere on the UWyo campus. The Rational Number Game is brought to you by the Proof Games project at the University of Wyoming, which aims to develop interactive tools for teaching and learning undergraduate mathematics. Prove a theorem. Write a function. Learn more mathematics while having fun. -/
12bfb36775184b43f02d01a77703633502aff0b5
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/bench/rbmap3.lean
ea3fbaae9cfbe47c3ce6e0dc885cf601a8b7a7c9
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,997
lean
prelude import init.core init.system.io init.data.ordering universes u v w inductive Rbcolor | red | black inductive Rbnode (α : Type u) (β : α → Type v) | leaf {} : Rbnode | Node (c : Rbcolor) (lchild : Rbnode) (key : α) (val : β key) (rchild : Rbnode) : Rbnode instance Rbcolor.DecidableEq : DecidableEq Rbcolor := {decEq := fun a b => Rbcolor.casesOn a (Rbcolor.casesOn b (isTrue rfl) (isFalse (fun h => Rbcolor.noConfusion h))) (Rbcolor.casesOn b (isFalse (fun h => Rbcolor.noConfusion h)) (isTrue rfl))} namespace Rbnode variables {α : Type u} {β : α → Type v} {σ : Type w} open Rbcolor def depth (f : Nat → Nat → Nat) : Rbnode α β → Nat | leaf => 0 | Node _ l _ _ r => (f (depth l) (depth r)) + 1 protected def min : Rbnode α β → Option (Sigma (fun k => β k)) | leaf => none | Node _ leaf k v _ => some ⟨k, v⟩ | Node _ l k v _ => min l protected def max : Rbnode α β → Option (Sigma (fun k => β k)) | leaf => none | Node _ _ k v leaf => some ⟨k, v⟩ | Node _ _ k v r => max r @[specialize] def fold (f : ∀ (k : α), β k → σ → σ) : Rbnode α β → σ → σ | leaf, b => b | Node _ l k v r, b => fold r (f k v (fold l b)) @[specialize] def revFold (f : ∀ (k : α), β k → σ → σ) : Rbnode α β → σ → σ | leaf, b => b | Node _ l k v r, b => revFold l (f k v (revFold r b)) @[specialize] def all (p : ∀ (k : α), β k → Bool) : Rbnode α β → Bool | leaf => true | Node _ l k v r => p k v && all l && all r @[specialize] def any (p : ∀ (k : α), β k → Bool) : Rbnode α β → Bool | leaf => false | Node _ l k v r => p k v || any l || any r def isRed : Rbnode α β → Bool | Node red _ _ _ _ => true | _ => false def rotateLeft : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node hc hl hk hv (Node red xl xk xv xr)), _ => if !isRed hl then (Node hc (Node red hl hk hv xl) xk xv xr) else n | leaf, h => absurd rfl h | e, _ => e theorem ifNodeNodeNeLeaf {c : Prop} [Decidable c] {l1 l2 : Rbnode α β} {c1 k1 v1 r1 c2 k2 v2 r2} : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) ≠ leaf := fun h => if hc : c then have h1 : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) = Node c1 l1 k1 v1 r1 from ifPos hc; Rbnode.noConfusion (Eq.trans h1.symm h) else have h1 : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) = Node c2 l2 k2 v2 r2 from ifNeg hc; Rbnode.noConfusion (Eq.trans h1.symm h) theorem rotateLeftNeLeaf : ∀ (n : Rbnode α β) (h : n ≠ leaf), rotateLeft n h ≠ leaf | Node _ hl _ _ (Node red _ _ _ _), _, h => ifNodeNodeNeLeaf h | leaf, h, _ => absurd rfl h | Node _ _ _ _ (Node black _ _ _ _), _, h => Rbnode.noConfusion h def rotateRight : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node hc (Node red xl xk xv xr) hk hv hr), _ => if isRed xl then (Node hc xl xk xv (Node red xr hk hv hr)) else n | leaf, h => absurd rfl h | e, _ => e theorem rotateRightNeLeaf : ∀ (n : Rbnode α β) (h : n ≠ leaf), rotateRight n h ≠ leaf | Node _ (Node red _ _ _ _) _ _ _, _, h => ifNodeNodeNeLeaf h | leaf, h, _ => absurd rfl h | Node _ (Node black _ _ _ _) _ _ _, _, h => Rbnode.noConfusion h def flip : Rbcolor → Rbcolor | red => black | black => red def flipColor : Rbnode α β → Rbnode α β | Node c l k v r => Node (flip c) l k v r | leaf => leaf def flipColors : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node c l k v r), _ => if isRed l ∧ isRed r then Node (flip c) (flipColor l) k v (flipColor r) else n | leaf, h => absurd rfl h def fixup (n : Rbnode α β) (h : n ≠ leaf) : Rbnode α β := let n₁ := rotateLeft n h; let h₁ := (rotateLeftNeLeaf n h); let n₂ := rotateRight n₁ h₁; let h₂ := (rotateRightNeLeaf n₁ h₁); flipColors n₂ h₂ def setBlack : Rbnode α β → Rbnode α β | Node red l k v r => Node black l k v r | n => n section insert variables (lt : α → α → Prop) [DecidableRel lt] def ins (x : α) (vx : β x) : Rbnode α β → Rbnode α β | leaf => Node red leaf x vx leaf | Node c l k v r => if lt x k then fixup (Node c (ins l) k v r) (fun h => Rbnode.noConfusion h) else if lt k x then fixup (Node c l k v (ins r)) (fun h => Rbnode.noConfusion h) else Node c l x vx r def insert (t : Rbnode α β) (k : α) (v : β k) : Rbnode α β := setBlack (ins lt k v t) end insert section membership variable (lt : α → α → Prop) variable [DecidableRel lt] def findCore : Rbnode α β → ∀ (k : α), Option (Sigma (fun k => β k)) | leaf, x => none | Node _ a ky vy b, x => (match cmpUsing lt x ky with | Ordering.lt => findCore a x | Ordering.Eq => some ⟨ky, vy⟩ | Ordering.gt => findCore b x) def find {β : Type v} : Rbnode α (fun _ => β) → α → Option β | leaf, x => none | Node _ a ky vy b, x => (match cmpUsing lt x ky with | Ordering.lt => find a x | Ordering.Eq => some vy | Ordering.gt => find b x) def lowerBound : Rbnode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, x, lb => lb | Node _ a ky vy b, x, lb => (match cmpUsing lt x ky with | Ordering.lt => lowerBound a x lb | Ordering.Eq => some ⟨ky, vy⟩ | Ordering.gt => lowerBound b x (some ⟨ky, vy⟩)) end membership inductive WellFormed (lt : α → α → Prop) : Rbnode α β → Prop | leafWff : WellFormed leaf | insertWff {n n' : Rbnode α β} {k : α} {v : β k} [DecidableRel lt] : WellFormed n → n' = insert lt n k v → WellFormed n' end Rbnode open Rbnode /- TODO(Leo): define dRbmap -/ def Rbmap (α : Type u) (β : Type v) (lt : α → α → Prop) : Type (max u v) := {t : Rbnode α (fun _ => β) // t.WellFormed lt } @[inline] def mkRbmap (α : Type u) (β : Type v) (lt : α → α → Prop) : Rbmap α β lt := ⟨leaf, WellFormed.leafWff lt⟩ namespace Rbmap variables {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Prop} def depth (f : Nat → Nat → Nat) (t : Rbmap α β lt) : Nat := t.val.depth f @[inline] def fold (f : α → β → σ → σ) : Rbmap α β lt → σ → σ | ⟨t, _⟩, b => t.fold f b @[inline] def revFold (f : α → β → σ → σ) : Rbmap α β lt → σ → σ | ⟨t, _⟩, b => t.revFold f b @[inline] def empty : Rbmap α β lt → Bool | ⟨leaf, _⟩ => true | _ => false @[specialize] def toList : Rbmap α β lt → List (α × β) | ⟨t, _⟩ => t.revFold (fun k v ps => (k, v)::ps) [] @[inline] protected def min : Rbmap α β lt → Option (α × β) | ⟨t, _⟩ => match t.min with | some ⟨k, v⟩ => some (k, v) | none => none @[inline] protected def max : Rbmap α β lt → Option (α × β) | ⟨t, _⟩ => match t.max with | some ⟨k, v⟩ => some (k, v) | none => none instance [Repr α] [Repr β] : Repr (Rbmap α β lt) := ⟨fun t => "rbmapOf " ++ repr t.toList⟩ variables [DecidableRel lt] def insert : Rbmap α β lt → α → β → Rbmap α β lt | ⟨t, w⟩, k, v => ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩ @[specialize] def ofList : List (α × β) → Rbmap α β lt | [] => mkRbmap _ _ _ | ⟨k,v⟩::xs => (ofList xs).insert k v def findCore : Rbmap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.findCore lt x def find : Rbmap α β lt → α → Option β | ⟨t, _⟩, x => t.find lt x /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ def lowerBound : Rbmap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.lowerBound lt x none @[inline] def contains (t : Rbmap α β lt) (a : α) : Bool := (t.find a).isSome def fromList (l : List (α × β)) (lt : α → α → Prop) [DecidableRel lt] : Rbmap α β lt := l.foldl (fun r p => r.insert p.1 p.2) (mkRbmap α β lt) @[inline] def all : Rbmap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.all p @[inline] def any : Rbmap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.any p end Rbmap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Prop) [DecidableRel lt] : Rbmap α β lt := Rbmap.fromList l lt /- Test -/ @[reducible] def map : Type := Rbmap Nat Bool Less.Less def mkMapAux : Nat → map → map | 0, m => m | n+1, m => mkMapAux n (m.insert n (n % 10 = 0)) def mkMap (n : Nat) := mkMapAux n (mkRbmap Nat Bool Less.Less) def main (xs : List String) : IO UInt32 := let m := mkMap xs.head.toNat; let v := Rbmap.fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0; IO.println (toString v) *> pure 0
dea69f37a3f81200a073196b07a76c166f8053c3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/converter/apply_congr_auto.lean
3a0c7339d7a826638c658cf917123b434c46d840
[]
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,452
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.interactive import Mathlib.tactic.converter.interactive import Mathlib.PostPort namespace Mathlib /-! ## Introduce the `apply_congr` conv mode tactic. `apply_congr` will apply congruence lemmas inside `conv` mode. It is particularly useful when the automatically generated congruence lemmas are not of the optimal shape. An example, described in the doc-string is rewriting inside the operand of a `finset.sum`. -/ namespace conv.interactive /-- Apply a congruence lemma inside `conv` mode. When called without an argument `apply_congr` will try applying all lemmas marked with `@[congr]`. Otherwise `apply_congr e` will apply the lemma `e`. Recall that a goal that appears as `∣ X` in `conv` mode represents a goal of `⊢ X = ?m`, i.e. an equation with a metavariable for the right hand side. To successfully use `apply_congr e`, `e` will need to be an equation (possibly after function arguments), which can be unified with a goal of the form `X = ?m`. The right hand side of `e` will then determine the metavariable, and `conv` will subsequently replace `X` with that right hand side. As usual, `apply_congr` can create new goals; any of these which are _not_ equations with a metavariable on the right hand side will be hard to deal with in `conv` mode. Thus `apply_congr` automatically calls `intros` on any new goals, and fails if they are not then equations. In particular it is useful for rewriting inside the operand of a `finset.sum`, as it provides an extra hypothesis asserting we are inside the domain. For example: ```lean example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.sum S f = finset.sum S g := begin conv_lhs { -- If we just call `congr` here, in the second goal we're helpless, -- because we are only given the opportunity to rewrite `f`. -- However `apply_congr` uses the appropriate `@[congr]` lemma, -- so we get to rewrite `f x`, in the presence of the crucial `H : x ∈ S` hypothesis. apply_congr, skip, simp [h, H], } end ``` In the above example, when the `apply_congr` tactic is called it gives the hypothesis `H : x ∈ S` which is then used to rewrite the `f x` to `g x`. -/ end Mathlib
a8da04dd1334bdfdbf4f62a9d25f45a341b83e85
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/lint/frontend.lean
6c844152f169bab667602cc09732def96b35e232
[ "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
14,630
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, Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint.basic /-! # Linter frontend and commands This file defines the linter commands which spot common mistakes in the code. * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) For a list of default / non-default linters, see the "Linting Commands" user command doc entry. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output if all checks pass. A silent lint will fail if any test fails. You can append a `+` to any command (e.g. `#lint_mathlib+`) to run a verbose lint that reports the result of each linter, including the successes. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ open tactic expr native setup_tactic_parser /-- Verbosity for the linter output. * `low`: only print failing checks, print nothing on success. * `medium`: only print failing checks, print confirmation on success. * `high`: print output of every check. -/ @[derive [decidable_eq, inhabited]] inductive lint_verbosity | low | medium | high /-- `get_checks slow extra use_only` produces a list of linters. `extras` is a list of names that should resolve to declarations with type `linter`. If `use_only` is true, it only uses the linters in `extra`. Otherwise, it uses all linters in the environment tagged with `@[linter]`. If `slow` is false, it only uses the fast default tests. -/ meta def get_checks (slow : bool) (extra : list name) (use_only : bool) : tactic (list (name × linter)) := do default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters, let default := if slow then default else default.filter (λ l, l.2.is_fast), list.append default <$> get_linters extra /-- `lint_core all_decls non_auto_decls checks` applies the linters `checks` to the list of declarations. If `auto_decls` is false for a linter (default) the linter is applied to `non_auto_decls`. If `auto_decls` is true, then it is applied to `all_decls`. The resulting list has one element for each linter, containing the linter as well as a map from declaration name to warning. -/ meta def lint_core (all_decls non_auto_decls : list declaration) (checks : list (name × linter)) : tactic (list (name × linter × rb_map name string)) := do checks.mmap $ λ ⟨linter_name, linter⟩, do let test_decls := if linter.auto_decls then all_decls else non_auto_decls, test_decls ← test_decls.mfilter (λ decl, should_be_linted linter_name decl.to_name), s ← read, let results := test_decls.map_async_chunked $ λ decl, prod.mk decl.to_name $ match linter.test decl s with | result.success w _ := w | result.exception msg _ _ := some $ "LINTER FAILED:\n" ++ msg.elim "(no message)" (λ msg, to_string $ msg ()) end, let results := results.foldl (λ (results : rb_map name string) warning, match warning with | (decl_name, some w) := results.insert decl_name w | (_, none) := results end) mk_rb_map, pure (linter_name, linter, results) /-- Sorts a map with declaration keys as names by line number. -/ meta def sort_results {α} (e : environment) (results : rb_map name α) : list (name × α) := list.reverse $ rb_lmap.values $ rb_lmap.of_list $ results.fold [] $ λ decl linter_warning results, (((e.decl_pos decl).get_or_else ⟨0,0⟩).line, (decl, linter_warning)) :: results /-- Formats a linter warning as `#print` command with comment. -/ meta def print_warning (decl_name : name) (warning : string) : format := "#check @" ++ to_fmt decl_name ++ " /- " ++ warning ++ " -/" /-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/ meta def print_warnings (env : environment) (results : rb_map name string) : format := format.intercalate format.line $ (sort_results env results).map $ λ ⟨decl_name, warning⟩, print_warning decl_name warning /-- Formats a map of linter warnings grouped by filename with `-- filename` comments. The first `drop_fn_chars` characters are stripped from the filename. -/ meta def grouped_by_filename (e : environment) (results : rb_map name string) (drop_fn_chars := 0) (formatter: rb_map name string → format) : format := let results := results.fold (rb_map.mk string (rb_map name string)) $ λ decl_name linter_warning results, let fn := (e.decl_olean decl_name).get_or_else "" in results.insert fn (((results.find fn).get_or_else mk_rb_map).insert decl_name linter_warning) in let l := results.to_list.reverse.map (λ ⟨fn, results⟩, ("-- " ++ fn.popn drop_fn_chars ++ "\n" ++ formatter results : format)) in format.intercalate "\n\n" l ++ "\n" /-- Formats the linter results as Lean code with comments and `#print` commands. -/ meta def format_linter_results (env : environment) (results : list (name × linter × rb_map name string)) (decls non_auto_decls : list declaration) (group_by_filename : option ℕ) (where_desc : string) (slow : bool) (verbose : lint_verbosity) (num_linters : ℕ) : format := do let formatted_results := results.map $ λ ⟨linter_name, linter, results⟩, let report_str : format := to_fmt "/- The `" ++ to_fmt linter_name ++ "` linter reports: -/\n" in if ¬ results.empty then let warnings := match group_by_filename with | none := print_warnings env results | some dropped := grouped_by_filename env results dropped (print_warnings env) end in report_str ++ "/- " ++ linter.errors_found ++ " -/\n" ++ warnings ++ "\n" else if verbose = lint_verbosity.high then "/- OK: " ++ linter.no_errors_found ++ " -/" else format.nil, let s := format.intercalate "\n" (formatted_results.filter (λ f, ¬ f.is_nil)), let s := if verbose = lint_verbosity.low then s else format!("/- Checking {non_auto_decls.length} declarations (plus " ++ "{decls.length - non_auto_decls.length} automatically generated ones) {where_desc} " ++ "with {num_linters} linters -/\n\n") ++ s, let s := if slow then s else s ++ "/- (slow tests skipped) -/\n", s /-- The common denominator of `#lint[|mathlib|all]`. The different commands have different configurations for `l`, `group_by_filename` and `where_desc`. If `slow` is false, doesn't do the checks that take a lot of time. If `verbose` is false, it will suppress messages from passing checks. By setting `checks` you can customize which checks are performed. Returns a `name_set` containing the names of all declarations that fail any check in `check`, and a `format` object describing the failures. -/ meta def lint_aux (decls : list declaration) (group_by_filename : option ℕ) (where_desc : string) (slow : bool) (verbose : lint_verbosity) (checks : list (name × linter)) : tactic (name_set × format) := do e ← get_env, let non_auto_decls := decls.filter (λ d, ¬ d.is_auto_or_internal e), results ← lint_core decls non_auto_decls checks, let s := format_linter_results e results decls non_auto_decls group_by_filename where_desc slow verbose checks.length, let ns := name_set.of_list (do (_,_,rs) ← results, rs.keys), pure (ns, s) /-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/ meta def lint (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, let l := e.filter (λ d, e.in_current_file d.to_name), lint_aux l none "in the current file" slow verbose checks /-- Returns the declarations in the folder `proj_folder`. -/ meta def lint_project_decls (proj_folder : string) : tactic (list declaration) := do e ← get_env, pure $ e.filter $ λ d, e.is_prefix_of_file proj_folder d.to_name /-- Returns the linter message by running the linter on all declarations in project `proj_name` in folder `proj_folder`. It also returns a `name_set` containing all declarations that fail. To add a linter command for your own project, write ``` open lean.parser lean tactic interactive @[user_command] meta def lint_my_project_cmd (_ : parse $ tk "#lint_my_project") : parser unit := do str ← get_project_dir n k, lint_cmd_aux (@lint_project str "my project") ``` Here `n` is the name of any declaration in the project (like `` `lint_my_project_cmd`` and `k` is the number of characters in the filename of `n` *after* the `src/` directory (so e.g. the number of characters in `tactic/lint/frontend.lean`). Warning: the linter will not work in the file where `n` is declared. -/ meta def lint_project (proj_folder proj_name : string) (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, decls ← lint_project_decls proj_folder, lint_aux decls proj_folder.length ("in " ++ proj_name ++ " (only in imported files)") slow verbose checks /-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/ meta def lint_all (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, let l := e.get_decls, lint_aux l (some 0) "in all imported files (including this one)" slow verbose checks /-- Parses an optional `only`, followed by a sequence of zero or more identifiers. Prepends `linter.` to each of these identifiers. -/ meta def parse_lint_additions : parser (bool × list name) := prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident*) /-- Parses a "-" or "+", returning `lint_verbosity.low` or `lint_verbosity.high` respectively, or returns `none`. -/ meta def parse_verbosity : parser (option lint_verbosity) := tk "-" >> return lint_verbosity.low <|> tk "+" >> return lint_verbosity.high <|> return none /-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/ meta def lint_cmd_aux (scope : bool → lint_verbosity → list name → bool → tactic (name_set × format)) : parser unit := do verbosity ← parse_verbosity, fast_only ← optional (tk "*"), -- allow either order of *- verbosity ← if verbosity.is_some then return verbosity else parse_verbosity, let verbosity := verbosity.get_or_else lint_verbosity.medium, (use_only, extra) ← parse_lint_additions, (failed, s) ← scope fast_only.is_none verbosity extra use_only, when (¬ s.is_nil) $ trace s, when (verbosity = lint_verbosity.low ∧ ¬ failed.empty) $ fail "Linting did not succeed", when (verbosity = lint_verbosity.medium ∧ failed.empty) $ trace "/- All linting checks passed! -/" /-- The command `#lint` at the bottom of a file will warn you about some common mistakes in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`. `#lint-` will suppress the output if all checks pass. `#lint+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit := lint_cmd_aux @lint /-- The command `#lint_mathlib` checks all of mathlib for certain mistakes. Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`. `#lint_mathlib-` will suppress the output if all checks pass. `lint_mathlib+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit := do str ← get_mathlib_dir, lint_cmd_aux (@lint_project str "mathlib") /-- The command `#lint_all` checks all imported files for certain mistakes. Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`. `#lint_all-` will suppress the output if all checks pass. `lint_all+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit := lint_cmd_aux @lint_all /-- The command `#list_linters` prints a list of all available linters. -/ @[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit := do env ← get_env, let ns := env.decl_filter_map $ λ dcl, if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none, trace "Available linters:\n linters marked with (*) are in the default lint set\n", ns.mmap' $ λ n, do b ← has_attribute' `linter n, trace $ n.pop_prefix.to_string ++ if b then " (*)" else "" /-- Invoking the hole command `lint` ("Find common mistakes in current file") will print text that indicates mistakes made in the file above the command. It is equivalent to copying and pasting the output of `#lint`. On large files, it may take some time before the output appears. -/ @[hole_command] meta def lint_hole_cmd : hole_command := { name := "Lint", descr := "Lint: Find common mistakes in current file.", action := λ es, do (_, s) ← lint, return [(s.to_string,"")] } add_tactic_doc { name := "Lint", category := doc_category.hole_cmd, decl_names := [`lint_hole_cmd], tags := ["linting"] }
903f28955bd57aebb18966d4313a3ca02b62aeeb
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/algebra/ordered_group.lean
0be71159cd07a9d4d3523b17512b458069898c32
[ "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
28,109
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl Ordered monoids and groups. -/ import algebra.group.units algebra.group.with_one algebra.group.type_tags import order.bounded_lattice tactic.basic universe u variable {α : Type u} section old_structure_cmd set_option old_structure_cmd true set_option default_priority 100 -- see Note [default priority] /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that addition is an order embedding, i.e. `a + b ≤ a + c ↔ b ≤ c`. These monoids are automatically cancellative. -/ class ordered_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α, order_bot α := (le_iff_exists_add : ∀a b:α, a ≤ b ↔ ∃c, b = a + c) end old_structure_cmd section ordered_comm_monoid variables [ordered_comm_monoid α] {a b c d : α} lemma add_le_add_left' (h : a ≤ b) : c + a ≤ c + b := ordered_comm_monoid.add_le_add_left a b h c lemma add_le_add_right' (h : a ≤ b) : a + c ≤ b + c := add_comm c a ▸ add_comm c b ▸ add_le_add_left' h lemma lt_of_add_lt_add_left' : a + b < a + c → b < c := ordered_comm_monoid.lt_of_add_lt_add_left a b c lemma add_le_add' (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (add_le_add_right' h₁) (add_le_add_left' h₂) lemma le_add_of_nonneg_right' (h : 0 ≤ b) : a ≤ a + b := have a + b ≥ a + 0, from add_le_add_left' h, by rwa add_zero at this lemma le_add_of_nonneg_left' (h : 0 ≤ b) : a ≤ b + a := have 0 + a ≤ b + a, from add_le_add_right' h, by rwa zero_add at this lemma lt_of_add_lt_add_right' (h : a + b < c + b) : a < c := lt_of_add_lt_add_left' (show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end) -- here we start using properties of zero. lemma le_add_of_nonneg_of_le' (ha : 0 ≤ a) (hbc : b ≤ c) : b ≤ a + c := zero_add b ▸ add_le_add' ha hbc lemma le_add_of_le_of_nonneg' (hbc : b ≤ c) (ha : 0 ≤ a) : b ≤ c + a := add_zero b ▸ add_le_add' hbc ha lemma add_nonneg' (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := le_add_of_nonneg_of_le' ha hb lemma add_pos_of_pos_of_nonneg' (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b := lt_of_lt_of_le ha $ le_add_of_nonneg_right' hb lemma add_pos' (ha : 0 < a) (hb : 0 < b) : 0 < a + b := add_pos_of_pos_of_nonneg' ha $ le_of_lt hb lemma add_pos_of_nonneg_of_pos' (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b := lt_of_lt_of_le hb $ le_add_of_nonneg_left' ha lemma add_nonpos' (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 := zero_add (0:α) ▸ (add_le_add' ha hb) lemma add_le_of_nonpos_of_le' (ha : a ≤ 0) (hbc : b ≤ c) : a + b ≤ c := zero_add c ▸ add_le_add' ha hbc lemma add_le_of_le_of_nonpos' (hbc : b ≤ c) (ha : a ≤ 0) : b + a ≤ c := add_zero c ▸ add_le_add' hbc ha lemma add_neg_of_neg_of_nonpos' (ha : a < 0) (hb : b ≤ 0) : a + b < 0 := lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) hb) ha lemma add_neg_of_nonpos_of_neg' (ha : a ≤ 0) (hb : b < 0) : a + b < 0 := lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hb lemma add_neg' (ha : a < 0) (hb : b < 0) : a + b < 0 := add_neg_of_nonpos_of_neg' (le_of_lt ha) hb lemma lt_add_of_nonneg_of_lt' (ha : 0 ≤ a) (hbc : b < c) : b < a + c := lt_of_lt_of_le hbc $ le_add_of_nonneg_left' ha lemma lt_add_of_lt_of_nonneg' (hbc : b < c) (ha : 0 ≤ a) : b < c + a := lt_of_lt_of_le hbc $ le_add_of_nonneg_right' ha lemma lt_add_of_pos_of_lt' (ha : 0 < a) (hbc : b < c) : b < a + c := lt_add_of_nonneg_of_lt' (le_of_lt ha) hbc lemma lt_add_of_lt_of_pos' (hbc : b < c) (ha : 0 < a) : b < c + a := lt_add_of_lt_of_nonneg' hbc (le_of_lt ha) lemma add_lt_of_nonpos_of_lt' (ha : a ≤ 0) (hbc : b < c) : a + b < c := lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hbc lemma add_lt_of_lt_of_nonpos' (hbc : b < c) (ha : a ≤ 0) : b + a < c := lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) ha) hbc lemma add_lt_of_neg_of_lt' (ha : a < 0) (hbc : b < c) : a + b < c := add_lt_of_nonpos_of_lt' (le_of_lt ha) hbc lemma add_lt_of_lt_of_neg' (hbc : b < c) (ha : a < 0) : b + a < c := add_lt_of_lt_of_nonpos' hbc (le_of_lt ha) lemma add_eq_zero_iff' (ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume hab : a + b = 0, have a ≤ 0, from hab ▸ le_add_of_le_of_nonneg' (le_refl _) hb, have a = 0, from le_antisymm this ha, have b ≤ 0, from hab ▸ le_add_of_nonneg_of_le' ha (le_refl _), have b = 0, from le_antisymm this hb, and.intro ‹a = 0› ‹b = 0›) (assume ⟨ha', hb'⟩, by rw [ha', hb', add_zero]) lemma bit0_pos {a : α} (h : 0 < a) : 0 < bit0 a := add_pos' h h end ordered_comm_monoid namespace units instance [monoid α] [i : preorder α] : preorder (units α) := preorder.lift (coe : units α → α) i @[simp] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl @[simp] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} : (a : α) < b ↔ a < b := iff.rfl instance [monoid α] [i : partial_order α] : partial_order (units α) := partial_order.lift (coe : units α → α) (by ext) i instance [monoid α] [i : linear_order α] : linear_order (units α) := linear_order.lift (coe : units α → α) (by ext) i instance [monoid α] [i : decidable_linear_order α] : decidable_linear_order (units α) := decidable_linear_order.lift (coe : units α → α) (by ext) i theorem max_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [max, h] theorem min_coe [monoid α] [decidable_linear_order α] {a b : units α} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [min, h] end units namespace with_zero instance [preorder α] : preorder (with_zero α) := with_bot.preorder instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot instance [lattice α] : lattice (with_zero α) := with_bot.lattice instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order instance [decidable_linear_order α] : decidable_linear_order (with_zero α) := with_bot.decidable_linear_order def ordered_comm_monoid [ordered_comm_monoid α] (zero_le : ∀ a : α, 0 ≤ a) : ordered_comm_monoid (with_zero α) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left' $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca h₂, cases b with b, { rw le_antisymm h bot_le at h₂, exact ⟨_, h₂, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at h₂, simp at h₂, simp [h₂], exact ⟨_, rfl, by simpa using add_le_add_left' (zero_le b)⟩ }, { simp at h, cases c with c; change some _ = _ at h₂; simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left' h } } } end end with_zero namespace with_top instance [add_semigroup α] : add_semigroup (with_top α) := { add := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b)), ..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative α) _ } lemma coe_add [add_semigroup α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative α) _ } instance [add_monoid α] : add_monoid (with_top α) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @with_zero.monoid (multiplicative α) _ } instance [add_comm_monoid α] : add_comm_monoid (with_top α) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @with_zero.comm_monoid (multiplicative α) _ } instance [ordered_comm_monoid α] : ordered_comm_monoid (with_top α) := begin suffices, refine { add_le_add_left := this, ..with_top.partial_order, ..with_top.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ c h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim le_top }, cases b with b, { exact (not_le_of_lt h).elim le_top }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $ with_top.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases b with b; cases h₂, cases a with a, {cases le_antisymm h le_top }, simp at h, exact ⟨_, rfl, add_le_add_left' h⟩, } end @[simp] lemma zero_lt_top [ordered_comm_monoid α] : (0 : with_top α) < ⊤ := coe_lt_top 0 @[simp] lemma zero_lt_coe [ordered_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a := coe_lt_coe @[simp] lemma add_top [ordered_comm_monoid α] : ∀{a : with_top α}, a + ⊤ = ⊤ | none := rfl | (some a) := rfl @[simp] lemma top_add [ordered_comm_monoid α] {a : with_top α} : ⊤ + a = ⊤ := rfl lemma add_eq_top [ordered_comm_monoid α] (a b : with_top α) : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by cases a; cases b; simp [none_eq_top, some_eq_coe, coe_add.symm] lemma add_lt_top [ordered_comm_monoid α] (a b : with_top α) : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := begin apply not_iff_not.1, simp [lt_top_iff_ne_top, add_eq_top], finish, apply classical.dec _, apply classical.dec _, end instance [canonically_ordered_monoid α] : canonically_ordered_monoid (with_top α) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl | (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c, begin simp [canonically_ordered_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, simp [coe_add] }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_comm_monoid } end with_top namespace with_bot instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid instance [ordered_comm_monoid α] : ordered_comm_monoid (with_bot α) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases a with a; cases h₂, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left' h⟩, } end @[simp] lemma coe_zero [add_monoid α] : ((0 : α) : with_bot α) = 0 := rfl @[simp] lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := rfl @[simp] lemma bot_add [ordered_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl @[simp] lemma add_bot [ordered_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl instance has_one [has_one α] : has_one (with_bot α) := ⟨(1 : α)⟩ @[simp] lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl end with_bot section canonically_ordered_monoid variables [canonically_ordered_monoid α] {a b c d : α} lemma le_iff_exists_add : a ≤ b ↔ ∃c, b = a + c := canonically_ordered_monoid.le_iff_exists_add a b @[simp] lemma zero_le (a : α) : 0 ≤ a := le_iff_exists_add.mpr ⟨a, by simp⟩ @[simp] lemma bot_eq_zero : (⊥ : α) = 0 := le_antisymm bot_le (zero_le ⊥) @[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 := add_eq_zero_iff' (zero_le _) (zero_le _) @[simp] lemma le_zero_iff_eq : a ≤ 0 ↔ a = 0 := iff.intro (assume h, le_antisymm h (zero_le a)) (assume h, h ▸ le_refl a) protected lemma zero_lt_iff_ne_zero : 0 < a ↔ a ≠ 0 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (zero_le _) hne.symm lemma le_add_left (h : a ≤ c) : a ≤ b + c := calc a = 0 + a : by simp ... ≤ b + c : add_le_add' (zero_le _) h lemma le_add_right (h : a ≤ b) : a ≤ b + c := calc a = a + 0 : by simp ... ≤ b + c : add_le_add' h (zero_le _) instance with_zero.canonically_ordered_monoid : canonically_ordered_monoid (with_zero α) := { le_iff_exists_add := λ a b, begin cases a with a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm bot_le) (by simp)) (λ ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_comm_monoid zero_le } end canonically_ordered_monoid @[priority 100] -- see Note [lower instance priority] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid [H : ordered_cancel_comm_monoid α] : ordered_comm_monoid α := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, ..H } section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] {a b c x y : α} @[simp] lemma add_le_add_iff_left (a : α) {b c : α} : a + b ≤ a + c ↔ b ≤ c := ⟨le_of_add_le_add_left, λ h, add_le_add_left h _⟩ @[simp] lemma add_le_add_iff_right (c : α) : a + c ≤ b + c ↔ a ≤ b := add_comm c a ▸ add_comm c b ▸ add_le_add_iff_left c @[simp] lemma add_lt_add_iff_left (a : α) {b c : α} : a + b < a + c ↔ b < c := ⟨lt_of_add_lt_add_left, λ h, add_lt_add_left h _⟩ @[simp] lemma add_lt_add_iff_right (c : α) : a + c < b + c ↔ a < b := add_comm c a ▸ add_comm c b ▸ add_lt_add_iff_left c @[simp] lemma le_add_iff_nonneg_right (a : α) {b : α} : a ≤ a + b ↔ 0 ≤ b := have a + 0 ≤ a + b ↔ 0 ≤ b, from add_le_add_iff_left a, by rwa add_zero at this @[simp] lemma le_add_iff_nonneg_left (a : α) {b : α} : a ≤ b + a ↔ 0 ≤ b := by rw [add_comm, le_add_iff_nonneg_right] @[simp] lemma lt_add_iff_pos_right (a : α) {b : α} : a < a + b ↔ 0 < b := have a + 0 < a + b ↔ 0 < b, from add_lt_add_iff_left a, by rwa add_zero at this @[simp] lemma lt_add_iff_pos_left (a : α) {b : α} : a < b + a ↔ 0 < b := by rw [add_comm, lt_add_iff_pos_right] @[simp] lemma add_le_iff_nonpos_left : x + y ≤ y ↔ x ≤ 0 := by { convert add_le_add_iff_right y, rw [zero_add] } @[simp] lemma add_le_iff_nonpos_right : x + y ≤ x ↔ y ≤ 0 := by { convert add_le_add_iff_left x, rw [add_zero] } @[simp] lemma add_lt_iff_neg_right : x + y < y ↔ x < 0 := by { convert add_lt_add_iff_right y, rw [zero_add] } @[simp] lemma add_lt_iff_neg_left : x + y < x ↔ y < 0 := by { convert add_lt_add_iff_left x, rw [add_zero] } lemma add_eq_zero_iff_eq_zero_of_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := ⟨λ hab : a + b = 0, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], λ ⟨ha', hb'⟩, by rw [ha', hb', add_zero]⟩ lemma with_top.add_lt_add_iff_left : ∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊤ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { rw [← with_top.coe_add], exact with_top.coe_lt_top _ }, { rw [← with_top.coe_add, ← with_top.coe_add, with_top.coe_lt_coe], exact add_lt_add_iff_left _ } end lemma with_top.add_lt_add_iff_right {a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c end ordered_cancel_comm_monoid section ordered_comm_group /-- The `add_lt_add_left` field of `ordered_comm_group` is redundant, but it is in core so we can't remove it for now. This alternative constructor is the best we can do. -/ def ordered_comm_group.mk' {α : Type u} [add_comm_group α] [partial_order α] (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) : ordered_comm_group α := { add_le_add_left := add_le_add_left, add_lt_add_left := λ a b h c, begin rw lt_iff_le_not_le at h, rw lt_iff_le_not_le, split, { apply add_le_add_left _ _ h.1 }, { intro w, replace w : -c + (c + b) ≤ -c + (c + a) := add_le_add_left _ _ w _, simp only [add_zero, add_comm, add_left_neg, add_left_comm] at w, exact h.2 w }, end, ..(by apply_instance : add_comm_group α), ..(by apply_instance : partial_order α) } variables [ordered_comm_group α] {a b c : α} lemma neg_neg_iff_pos {α : Type} [_inst_1 : ordered_comm_group α] {a : α} : -a < 0 ↔ 0 < a := ⟨ pos_of_neg_neg, neg_neg_of_pos ⟩ @[simp] lemma neg_le_neg_iff : -a ≤ -b ↔ b ≤ a := have a + b + -a ≤ a + b + -b ↔ -a ≤ -b, from add_le_add_iff_left _, by simp at this; simp [this] lemma neg_le : -a ≤ b ↔ -b ≤ a := have -a ≤ -(-b) ↔ -b ≤ a, from neg_le_neg_iff, by rwa neg_neg at this lemma le_neg : a ≤ -b ↔ b ≤ -a := have -(-a) ≤ -b ↔ b ≤ -a, from neg_le_neg_iff, by rwa neg_neg at this lemma neg_le_iff_add_nonneg : -a ≤ b ↔ 0 ≤ a + b := (add_le_add_iff_left a).symm.trans $ by rw add_neg_self lemma le_neg_iff_add_nonpos : a ≤ -b ↔ a + b ≤ 0 := (add_le_add_iff_right b).symm.trans $ by rw neg_add_self @[simp] lemma neg_nonpos : -a ≤ 0 ↔ 0 ≤ a := have -a ≤ -0 ↔ 0 ≤ a, from neg_le_neg_iff, by rwa neg_zero at this @[simp] lemma neg_nonneg : 0 ≤ -a ↔ a ≤ 0 := have -0 ≤ -a ↔ a ≤ 0, from neg_le_neg_iff, by rwa neg_zero at this lemma neg_le_self (h : 0 ≤ a) : -a ≤ a := le_trans (neg_nonpos.2 h) h lemma self_le_neg (h : a ≤ 0) : a ≤ -a := le_trans h (neg_nonneg.2 h) @[simp] lemma neg_lt_neg_iff : -a < -b ↔ b < a := have a + b + -a < a + b + -b ↔ -a < -b, from add_lt_add_iff_left _, by simp at this; simp [this] lemma neg_lt_zero : -a < 0 ↔ 0 < a := have -a < -0 ↔ 0 < a, from neg_lt_neg_iff, by rwa neg_zero at this lemma neg_pos : 0 < -a ↔ a < 0 := have -0 < -a ↔ a < 0, from neg_lt_neg_iff, by rwa neg_zero at this lemma neg_lt : -a < b ↔ -b < a := have -a < -(-b) ↔ -b < a, from neg_lt_neg_iff, by rwa neg_neg at this lemma lt_neg : a < -b ↔ b < -a := have -(-a) < -b ↔ b < -a, from neg_lt_neg_iff, by rwa neg_neg at this @[simp] lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b := (add_le_add_iff_left _).trans neg_le_neg_iff @[simp] lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b := add_le_add_iff_right _ @[simp] lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b := (add_lt_add_iff_left _).trans neg_lt_neg_iff @[simp] lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b := add_lt_add_iff_right _ @[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a := have a - a ≤ a - b ↔ b ≤ a, from sub_le_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b := have a - b ≤ b - b ↔ a ≤ b, from sub_le_sub_iff_right b, by rwa sub_self at this @[simp] lemma sub_pos : 0 < a - b ↔ b < a := have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a, by rwa sub_self at this @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b, by rwa sub_self at this lemma le_neg_add_iff_add_le : b ≤ -a + c ↔ a + b ≤ c := have -a + (a + b) ≤ -a + c ↔ a + b ≤ c, from add_le_add_iff_left _, by rwa neg_add_cancel_left at this lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c := by rw [le_sub_iff_add_le', add_comm] @[simp] lemma neg_add_le_iff_le_add : -b + a ≤ c ↔ a ≤ b + c := have -b + a ≤ -b + (b + c) ↔ a ≤ b + c, from add_le_add_iff_left _, by rwa neg_add_cancel_left at this lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c := by rw [sub_le_iff_le_add', add_comm] lemma add_neg_le_iff_le_add : a + -c ≤ b ↔ a ≤ b + c := sub_le_iff_le_add @[simp] lemma add_neg_le_iff_le_add' : a + -b ≤ c ↔ a ≤ b + c := sub_le_iff_le_add' lemma neg_add_le_iff_le_add' : -c + a ≤ b ↔ a ≤ b + c := by rw [neg_add_le_iff_le_add, add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≤ c ↔ a - c ≤ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≤ b - c ↔ c ≤ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm @[simp] lemma lt_neg_add_iff_add_lt : b < -a + c ↔ a + b < c := have -a + (a + b) < -a + c ↔ a + b < c, from add_lt_add_iff_left _, by rwa neg_add_cancel_left at this lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] @[simp] lemma neg_add_lt_iff_lt_add : -b + a < c ↔ a < b + c := have -b + a < -b + (b + c) ↔ a < b + c, from add_lt_add_iff_left _, by rwa neg_add_cancel_left at this lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] lemma neg_add_lt_iff_lt_add_right : -c + a < b ↔ a < b + c := by rw [neg_add_lt_iff_lt_add, add_comm] @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm lemma sub_le_self_iff (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b := sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _) lemma sub_lt_self_iff (a : α) {b : α} : a - b < a ↔ 0 < b := sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _) end ordered_comm_group namespace decidable_linear_ordered_comm_group variables [s : decidable_linear_ordered_comm_group α] include s @[priority 100] -- see Note [lower instance priority] instance : decidable_linear_ordered_cancel_comm_monoid α := { le_of_add_le_add_left := λ x y z, le_of_add_le_add_left, add_left_cancel := λ x y z, add_left_cancel, add_right_cancel := λ x y z, add_right_cancel, ..s } lemma eq_of_abs_sub_nonpos {a b : α} (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm _ _ h (abs_nonneg (a - b))) end decidable_linear_ordered_comm_group set_option old_structure_cmd true section prio set_option default_priority 100 -- see Note [default priority] /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_comm_group (α : Type*) extends add_comm_group α := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) end prio namespace nonneg_comm_group variable [s : nonneg_comm_group α] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_comm_group : ordered_comm_group α := { le := λ a b, nonneg (b - a), lt := λ a b, pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp, le_refl := λ a, by simp [zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, add_lt_add_left := λ a b nab c, by simpa [(<), preorder.lt] using nab, ..s } theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem pos_def {a : α} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : ¬ pos (0 : α) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : α} : 0 < a ↔ nonneg a ∧ ¬ nonneg (-a) := pos_def.symm.trans (pos_iff α _) theorem nonneg_total_iff : (∀ a : α, nonneg a ∨ nonneg (-a)) ↔ (∀ a b : α, a ≤ b ∨ b ≤ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ def to_decidable_linear_ordered_comm_group [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : decidable_linear_ordered_comm_group α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_comm_group.to_ordered_comm_group _ s } end nonneg_comm_group namespace order_dual instance [ordered_comm_monoid α] : ordered_comm_monoid (order_dual α) := { add_le_add_left := λ a b h c, @add_le_add_left' α _ b a c h, lt_of_add_lt_add_left := λ a b c h, @lt_of_add_lt_add_left' α _ a c b h, ..order_dual.partial_order α, ..show add_comm_monoid α, by apply_instance } instance [ordered_cancel_comm_monoid α] : ordered_cancel_comm_monoid (order_dual α) := { le_of_add_le_add_left := λ a b c : α, le_of_add_le_add_left, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, ..order_dual.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_comm_group (order_dual α) := { add_lt_add_left := λ a b : α, ordered_comm_group.add_lt_add_left b a, add_left_neg := λ a : α, add_left_neg a, ..order_dual.ordered_comm_monoid, ..show add_comm_group α, by apply_instance } end order_dual
b3792e88cb752190527963fea1e988252548c4a7
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/lint/type_classes.lean
6a0ed508acd37a00c40feb4cd52413ee49451a95
[ "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
18,032
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, Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint.basic /-! # Linters about type classes This file defines several linters checking the correct usage of type classes and the appropriate definition of instances: * `instance_priority` ensures that blanket instances have low priority. * `has_inhabited_instances` checks that every type has an `inhabited` instance. * `impossible_instance` checks that there are no instances which can never apply. * `incorrect_type_class_argument` checks that only type classes are used in instance-implicit arguments. * `dangerous_instance` checks for instances that generate subproblems with metavariables. * `fails_quickly` checks that type class resolution finishes quickly. * `class_structure` checks that every `class` is a structure, i.e. `@[class] def` is forbidden. * `has_coe_variable` checks that there is no instance of type `has_coe α t`. * `inhabited_nonempty` checks whether `[inhabited α]` arguments could be generalized to `[nonempty α]`. * `decidable_classical` checks propositions for `[decidable_... p]` hypotheses that are not used in the statement, and could thus be removed by using `classical` in the proof. * `linter.has_coe_to_fun` checks whether necessary `has_coe_to_fun` instances are declared. -/ open tactic /-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions and binders (or any other element that can be pretty printed). `l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by `get_pi_binders`. -/ meta def print_arguments {α} [has_to_tactic_format α] (l : list (ℕ × α)) : tactic string := do fs ← l.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt (n+1) ++ ": " ++ s) <$> pp b), return $ fs.to_string_aux tt /-- checks whether an instance that always applies has priority ≥ 1000. -/ private meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do (is_persistent, prio) ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do (_, tp) ← open_pis d.type, tp ← whnf tp transparency.none, let (fn, args) := tp.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_local_constant ∧ relevant_args.nodup, if always_applies then return $ some "set priority below 1000" else return none /-- There are places where typeclass arguments are specified with implicit `{}` brackets instead of the usual `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type of one of the other arguments. When they can be inferred from these other arguments, it is faster to use this method than to use type class inference. For example, when writing lemmas about `(f : α →+* β)`, it is faster to specify the fact that `α` and `β` are `semiring`s as `{rα : semiring α} {rβ : semiring β}` rather than the usual `[semiring α] [semiring β]`. -/ library_note "implicit instance arguments" /-- Certain instances always apply during type-class resolution. For example, the instance `add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class resolution problems of the form `add_group _`, and type-class inference will then do an exhaustive search to find a commutative group. These instances take a long time to fail. Other instances will only apply if the goal has a certain shape. For example `int.add_group : add_group ℤ` or `add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances will fail quickly, and when they apply, they are almost the desired instance. For this reason, we want the instances of the second type (that only apply in specific cases) to always have higher priority than the instances of the first type (that always apply). See also #1561. Therefore, if we create an instance that always applies, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000). -/ library_note "lower instance priority" /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good.", errors_found := "DANGEROUS INSTANCE PRIORITIES. The following instances always apply, and therefore should have a priority < 1000. If you don't know what priority to choose, use priority 100. See note [lower instance priority] for instructions to change the priority.", auto_decls := tt } /-- Reports declarations of types that do not have an associated `inhabited` instance. -/ private meta def has_inhabited_instance (d : declaration) : tactic (option string) := do tt ← pure d.is_trusted | pure none, ff ← has_attribute' `reducible d.to_name | pure none, ff ← has_attribute' `class d.to_name | pure none, (_, ty) ← open_pis d.type, ty ← whnf ty, if ty = `(Prop) then pure none else do `(Sort _) ← whnf ty | pure none, insts ← attribute.get_instances `instance, insts_tys ← insts.mmap $ λ i, expr.pi_codomain <$> declaration.type <$> get_decl i, let inhabited_insts := insts_tys.filter (λ i, i.app_fn.const_name = ``inhabited ∨ i.app_fn.const_name = `unique), let inhabited_tys := inhabited_insts.map (λ i, i.app_arg.get_app_fn.const_name), if d.to_name ∈ inhabited_tys then pure none else pure "inhabited instance missing" /-- A linter for missing `inhabited` instances. -/ @[linter] meta def linter.has_inhabited_instance : linter := { test := has_inhabited_instance, auto_decls := ff, no_errors_found := "No types have missing inhabited instances.", errors_found := "TYPES ARE MISSING INHABITED INSTANCES:", is_fast := ff } attribute [nolint has_inhabited_instance] pempty /-- Checks whether an instance can never be applied. -/ private meta def impossible_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let bad_arguments := binders.filter $ λ nb, nb.2.info ≠ binder_info.inst_implicit, _ :: _ ← return bad_arguments | return none, (λ s, some $ "Impossible to infer " ++ s) <$> print_arguments bad_arguments /-- A linter object for `impossible_instance`. -/ @[linter] meta def linter.impossible_instance : linter := { test := impossible_instance, auto_decls := tt, no_errors_found := "All instances are applicable.", errors_found := "IMPOSSIBLE INSTANCES FOUND. These instances have an argument that cannot be found during type-class resolution, and " ++ "therefore can never succeed. Either mark the arguments with square brackets (if it is a " ++ "class), or don't make it an instance." } /-- Checks whether an instance can never be applied. -/ private meta def incorrect_type_class_argument (d : declaration) : tactic (option string) := do (binders, _) ← get_pi_binders d.type, let instance_arguments := binders.indexes_values $ λ b : binder, b.info = binder_info.inst_implicit, /- the head of the type should either unfold to a class, or be a local constant. A local constant is allowed, because that could be a class when applied to the proper arguments. -/ bad_arguments ← instance_arguments.mfilter (λ ⟨_, b⟩, do (_, head) ← open_pis b.type, if head.get_app_fn.is_local_constant then return ff else do bnot <$> is_class head), _ :: _ ← return bad_arguments | return none, (λ s, some $ "These are not classes. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `incorrect_type_class_argument`. -/ @[linter] meta def linter.incorrect_type_class_argument : linter := { test := incorrect_type_class_argument, auto_decls := tt, no_errors_found := "All declarations have correct type-class arguments.", errors_found := "INCORRECT TYPE-CLASS ARGUMENTS. Some declarations have non-classes between [square brackets]:" } /-- Checks whether an instance is dangerous: it creates a new type-class problem with metavariable arguments. -/ private meta def dangerous_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (local_constants, target) ← open_pis d.type, let instance_arguments := local_constants.indexes_values $ λ e : expr, e.local_binding_info = binder_info.inst_implicit, let bad_arguments := local_constants.indexes_values $ λ x, !target.has_local_constant x && (x.local_binding_info ≠ binder_info.inst_implicit) && instance_arguments.any (λ nb, nb.2.local_type.has_local_constant x), let bad_arguments : list (ℕ × binder) := bad_arguments.map $ λ ⟨n, e⟩, ⟨n, e.to_binder⟩, _ :: _ ← return bad_arguments | return none, (λ s, some $ "The following arguments become metavariables. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `dangerous_instance`. -/ @[linter] meta def linter.dangerous_instance : linter := { test := dangerous_instance, no_errors_found := "No dangerous instances.", errors_found := "DANGEROUS INSTANCES FOUND.\nThese instances are recursive, and create a new " ++ "type-class problem which will have metavariables. Possible solution: remove the instance attribute or make it a local instance instead. Currently this linter does not check whether the metavariables only occur in arguments marked " ++ "with `out_param`, in which case this linter gives a false positive.", auto_decls := tt } /-- Applies expression `e` to local constants, but lifts all the arguments that are `Sort`-valued to `Type`-valued sorts. -/ meta def apply_to_fresh_variables (e : expr) : tactic expr := do t ← infer_type e, (xs, b) ← open_pis t, xs.mmap' $ λ x, try $ do { u ← mk_meta_univ, tx ← infer_type x, ttx ← infer_type tx, unify ttx (expr.sort u.succ) }, return $ e.app_of_list xs /-- Tests whether type-class inference search for a class will end quickly when applied to variables. This tactic succeeds if `mk_instance` succeeds quickly or fails quickly with the error message that it cannot find an instance. It fails if the tactic takes too long, or if any other error message is raised. We make sure that we apply the tactic to variables living in `Type u` instead of `Sort u`, because many instances only apply in that special case, and we do want to catch those loops. -/ meta def fails_quickly (max_steps : ℕ) (d : declaration) : tactic (option string) := do e ← mk_const d.to_name, tt ← is_class e | return none, e' ← apply_to_fresh_variables e, sum.inr msg ← retrieve_or_report_error $ tactic.try_for max_steps $ succeeds_or_fails_with_msg (mk_instance e') $ λ s, "tactic.mk_instance failed to generate instance for".is_prefix_of s | return none, return $ some $ if msg = "try_for tactic failed, timeout" then "type-class inference timed out" else msg /-- A linter object for `fails_quickly`. If we want to increase the maximum number of steps type-class inference is allowed to take, we can increase the number `3000` in the definition. As of 5 Mar 2020 the longest trace (for `is_add_hom`) takes 2900-3000 "heartbeats". -/ @[linter] meta def linter.fails_quickly : linter := { test := fails_quickly 3000, auto_decls := tt, no_errors_found := "No type-class searches timed out.", errors_found := "TYPE CLASS SEARCHES TIMED OUT. For the following classes, there is an instance that causes a loop, or an excessively long search.", is_fast := ff } /-- Checks that all uses of the `@[class]` attribute apply to structures or inductive types. This is future-proofing for lean 4, which no longer supports `@[class] def`. -/ private meta def class_structure (n : name) : tactic (option string) := do is_class ← has_attribute' `class n, if is_class then do env ← get_env, pure $ if env.is_inductive n then none else "is a non-structure or inductive type marked @[class]" else pure none /-- A linter object for `class_structure`. -/ @[linter] meta def linter.class_structure : linter := { test := λ d, class_structure d.to_name, auto_decls := tt, no_errors_found := "All classes are structures.", errors_found := "USE OF @[class] def IS DISALLOWED:" } /-- Tests whether there is no instance of type `has_coe α t` where `α` is a variable, or `has_coe t α` where `α` does not occur in `t`. See note [use has_coe_t]. -/ private meta def has_coe_variable (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, `(has_coe %%a %%b) ← return d.type.pi_codomain | return none, if a.is_var then return $ some $ "illegal instance, first argument is variable" else if b.is_var ∧ ¬ b.occurs a then return $ some $ "illegal instance, second argument is variable not occurring in first argument" else return none /-- A linter object for `has_coe_variable`. -/ @[linter] meta def linter.has_coe_variable : linter := { test := has_coe_variable, auto_decls := tt, no_errors_found := "No invalid `has_coe` instances.", errors_found := "INVALID `has_coe` INSTANCES. Make the following declarations instances of the class `has_coe_t` instead of `has_coe`." } /-- Checks whether a declaration is prop-valued and takes an `inhabited _` argument that is unused elsewhere in the type. In this case, that argument can be replaced with `nonempty _`. -/ private meta def inhabited_nonempty (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_nondep d.type, let inhd_binders := binders.filter $ λ pr, pr.2.type.is_app_of `inhabited, if inhd_binders.length = 0 then return none else (λ s, some $ "The following `inhabited` instances should be `nonempty`. " ++ s) <$> print_arguments inhd_binders /-- A linter object for `inhabited_nonempty`. -/ @[linter] meta def linter.inhabited_nonempty : linter := { test := inhabited_nonempty, auto_decls := ff, no_errors_found := "No uses of `inhabited` arguments should be replaced with `nonempty`.", errors_found := "USES OF `inhabited` SHOULD BE REPLACED WITH `nonempty`." } /-- Checks whether a declaration is `Prop`-valued and takes a `decidable* _` hypothesis that is unused lsewhere in the type. In this case, that hypothesis can be replaced with `classical` in the proof. Theorems in the `decidable` namespace are exempt from the check. -/ private meta def decidable_classical (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, ff ← pure $ (`decidable).is_prefix_of d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let deceq_binders := binders.filter $ λ pr, pr.2.type.is_app_of `decidable_eq ∨ pr.2.type.is_app_of `decidable_pred ∨ pr.2.type.is_app_of `decidable_rel ∨ pr.2.type.is_app_of `decidable, if deceq_binders.length = 0 then return none else (λ s, some $ "The following `decidable` hypotheses should be replaced with `classical` in the proof. " ++ s) <$> print_arguments deceq_binders /-- A linter object for `decidable_classical`. -/ @[linter] meta def linter.decidable_classical : linter := { test := decidable_classical, auto_decls := ff, no_errors_found := "No uses of `decidable` arguments should be replaced with `classical`.", errors_found := "USES OF `decidable` SHOULD BE REPLACED WITH `classical` IN THE PROOF." } /- The file `logic/basic.lean` emphasizes the differences between what holds under classical and non-classical logic. It makes little sense to make all these lemmas classical, so we add them to the list of lemmas which are not checked by the linter `decidable_classical`. -/ attribute [nolint decidable_classical] dec_em dec_em' not.decidable_imp_symm private meta def has_coe_to_fun_linter (d : declaration) : tactic (option string) := retrieve $ do tt ← return d.is_trusted | pure none, mk_meta_var d.type >>= set_goals ∘ pure, args ← unfreezing intros, expr.sort _ ← target | pure none, let ty : expr := (expr.const d.to_name d.univ_levels).mk_app args, some coe_fn_inst ← try_core $ to_expr ``(_root_.has_coe_to_fun %%ty) >>= mk_instance | pure none, some trans_inst@(expr.app (expr.app _ trans_inst_1) trans_inst_2) ← try_core $ to_expr ``(@_root_.coe_fn_trans %%ty _ _ _) | pure none, tt ← succeeds $ unify trans_inst coe_fn_inst transparency.reducible | pure none, set_bool_option `pp.all true, trans_inst_1 ← pp trans_inst_1, trans_inst_2 ← pp trans_inst_2, pure $ format.to_string $ "`has_coe_to_fun` instance is definitionally equal to a transitive instance composed of: " ++ trans_inst_1.group.indent 2 ++ format.line ++ "and" ++ trans_inst_2.group.indent 2 /-- Linter that checks whether `has_coe_to_fun` instances comply with Note [function coercion]. -/ @[linter] meta def linter.has_coe_to_fun : linter := { test := has_coe_to_fun_linter, auto_decls := tt, no_errors_found := "has_coe_to_fun is used correctly", errors_found := "INVALID/MISSING `has_coe_to_fun` instances. You should add a `has_coe_to_fun` instance for the following types. See Note [function coercion]." }
fa6f11f4f69cc57d1d5727c9f3a9b2304e366371
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/ordered_ring.lean
761d3c4cb7a60a2599da94e1ee47f55e65962347
[ "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
29,386
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Here an "ordered_ring" is partially ordered ring, which is ordered with respect to both a weak order and an associated strict order. Our numeric structures (int, rat, and real) will be instances of "linear_ordered_comm_ring". This development is modeled after Isabelle's library. -/ import algebra.ordered_group algebra.ring open eq variable {A : Type} private definition absurd_a_lt_a {B : Type} {a : A} [s : strict_order A] (H : a < a) : B := absurd H (lt.irrefl a) /- semiring structures -/ structure ordered_semiring [class] (A : Type) extends semiring A, ordered_cancel_comm_monoid A := (mul_le_mul_of_nonneg_left: ∀a b c, le a b → le zero c → le (mul c a) (mul c b)) (mul_le_mul_of_nonneg_right: ∀a b c, le a b → le zero c → le (mul a c) (mul b c)) (mul_lt_mul_of_pos_left: ∀a b c, lt a b → lt zero c → lt (mul c a) (mul c b)) (mul_lt_mul_of_pos_right: ∀a b c, lt a b → lt zero c → lt (mul a c) (mul b c)) section variable [s : ordered_semiring A] variables (a b c d e : A) include s theorem mul_le_mul_of_nonneg_left {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := ordered_semiring.mul_le_mul_of_nonneg_left a b c Hab Hc theorem mul_le_mul_of_nonneg_right {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := ordered_semiring.mul_le_mul_of_nonneg_right a b c Hab Hc -- TODO: there are four variations, depending on which variables we assume to be nonneg theorem mul_le_mul {a b c d : A} (Hac : a ≤ c) (Hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right Hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_nonneg {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) : a * b ≥ 0 := sorry /- begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end -/ theorem mul_nonpos_of_nonneg_of_nonpos {a b : A} (Ha : a ≥ 0) (Hb : b ≤ 0) : a * b ≤ 0 := sorry /- begin have H : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left Hb Ha, rewrite mul_zero at H, exact H end -/ theorem mul_nonpos_of_nonpos_of_nonneg {a b : A} (Ha : a ≤ 0) (Hb : b ≥ 0) : a * b ≤ 0 := sorry /- begin have H : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end -/ theorem mul_lt_mul_of_pos_left {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c Hab Hc theorem mul_lt_mul_of_pos_right {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c Hab Hc -- TODO: once again, there are variations theorem mul_lt_mul {a b c d : A} (Hac : a < c) (Hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right Hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_lt_mul' {a b c d : A} (H1 : a < c) (H2 : b < d) (H3 : b ≥ 0) (H4 : c > 0) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right (le_of_lt H1) H3 ... < c * d : mul_lt_mul_of_pos_left H2 H4 theorem mul_pos {a b : A} (Ha : a > 0) (Hb : b > 0) : a * b > 0 := sorry /- begin have H : 0 * b < a * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end -/ theorem mul_neg_of_pos_of_neg {a b : A} (Ha : a > 0) (Hb : b < 0) : a * b < 0 := sorry /- begin have H : a * b < a * 0, from mul_lt_mul_of_pos_left Hb Ha, rewrite mul_zero at H, exact H end -/ theorem mul_neg_of_neg_of_pos {a b : A} (Ha : a < 0) (Hb : b > 0) : a * b < 0 := sorry /- begin have H : a * b < 0 * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end -/ theorem mul_self_lt_mul_self {a b : A} (H1 : 0 ≤ a) (H2 : a < b) : a * a < b * b := mul_lt_mul' H2 H2 H1 (lt_of_le_of_lt H1 H2) end structure linear_ordered_semiring [class] (A : Type) extends ordered_semiring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) section variable [s : linear_ordered_semiring A] variables {a b c : A} include s theorem zero_lt_one : 0 < (1:A) := linear_ordered_semiring.zero_lt_one A theorem lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_ge H2 H) theorem lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_ge H2 H) theorem le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_gt H2 H) theorem le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_gt H2 H) theorem le_iff_mul_le_mul_left (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ c * a ≤ c * b := iff.intro (assume H', mul_le_mul_of_nonneg_left H' (le_of_lt H)) (assume H', le_of_mul_le_mul_left H' H) theorem le_iff_mul_le_mul_right (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ a * c ≤ b * c := iff.intro (assume H', mul_le_mul_of_nonneg_right H' (le_of_lt H)) (assume H', le_of_mul_le_mul_right H' H) theorem pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_ge H3 H) theorem pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_ge H3 H) theorem nonneg_of_mul_nonneg_left (H : 0 ≤ a * b) (H1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume H2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg H1 H2) H) theorem nonneg_of_mul_nonneg_right (H : 0 ≤ a * b) (H1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume H2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos H2 H1) H) theorem neg_of_mul_neg_left (H : a * b < 0) (H1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume H2 : b ≥ 0, not_lt_of_ge (mul_nonneg H1 H2) H) theorem neg_of_mul_neg_right (H : a * b < 0) (H1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume H2 : a ≥ 0, not_lt_of_ge (mul_nonneg H2 H1) H) theorem nonpos_of_mul_nonpos_left (H : a * b ≤ 0) (H1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume H2 : b > 0, not_le_of_gt (mul_pos H1 H2) H) theorem nonpos_of_mul_nonpos_right (H : a * b ≤ 0) (H1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume H2 : a > 0, not_le_of_gt (mul_pos H2 H1) H) end structure decidable_linear_ordered_semiring [class] (A : Type) extends linear_ordered_semiring A, decidable_linear_ordered_cancel_comm_monoid A /- ring structures -/ structure ordered_ring [class] (A : Type) extends ring A, ordered_comm_group A, zero_ne_one_class A := (mul_nonneg : ∀a b, le zero a → le zero b → le zero (mul a b)) (mul_pos : ∀a b, lt zero a → lt zero b → lt zero (mul a b)) theorem ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from iff.elim_right (sub_nonneg_iff_le b a) Hab, have H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg c (b - a) Hc H1, sorry /- begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end -/ theorem ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right (sub_nonneg_iff_le b a) Hab, have H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c H1 Hc, sorry /- begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end -/ theorem ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right (sub_pos_iff_lt b a) Hab, have H2 : 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) Hc H1, sorry /- begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end -/ theorem ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right (sub_pos_iff_lt b a) Hab, have H2 : 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c H1 Hc, sorry /- begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end -/ attribute [instance] definition ordered_ring.to_ordered_semiring [s : ordered_ring A] : ordered_semiring A := ⦃ ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A _, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _⦄ section variable [s : ordered_ring A] variables {a b c : A} include s theorem mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := sorry /- have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, have H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 -/ theorem mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := sorry /- have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, have H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 -/ theorem mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := sorry /- begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rewrite zero_mul at H, exact H end -/ theorem mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := sorry /- have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, have H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 -/ theorem mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := sorry /- have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, have H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 -/ theorem mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := sorry /- begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rewrite zero_mul at H, exact H end -/ end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance structure linear_ordered_ring [class] (A : Type) extends ordered_ring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) attribute [instance] definition linear_ordered_ring.to_linear_ordered_semiring [s : linear_ordered_ring A] : linear_ordered_semiring A := ⦃ linear_ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A _, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _ ⦄ structure linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_ring A, comm_monoid A theorem linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring A] {a b : A} (H : a * b = 0) : a = 0 ∨ b = 0 := sorry /- lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 < a * b, from mul_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 > a * b, from mul_neg_of_pos_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) (assume Ha : 0 = a, or.inl (Ha⁻¹)) (assume Ha : 0 > a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 > a * b, from mul_neg_of_neg_of_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 < a * b, from mul_pos_of_neg_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) -/ -- Linearity implies no zero divisors. Doesn't need commutativity. attribute [instance] definition linear_ordered_comm_ring.to_integral_domain [s: linear_ordered_comm_ring A] : integral_domain A := ⦃ integral_domain, s, eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero A s ⦄ section variable [s : linear_ordered_ring A] variables (a b c : A) include s theorem mul_self_nonneg : a * a ≥ 0 := or.elim (le.total 0 a) (assume H : a ≥ 0, mul_nonneg H H) (assume H : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos H H) theorem zero_le_one : 0 ≤ (1:A) := have H : 1 * 1 ≥ 0, from mul_self_nonneg (1:A), sorry /- begin rewrite one_mul at H, assumption end -/ theorem pos_and_pos_or_neg_and_neg_of_mul_pos {a b : A} (Hab : a * b > 0) : (a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := sorry /- lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, or.inl (and.intro Ha Hb)) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, absurd Hab (lt.asymm (mul_neg_of_pos_of_neg Ha Hb)))) (assume Ha : 0 = a, begin rewrite [-Ha at Hab, zero_mul at Hab], apply absurd_a_lt_a Hab end) (assume Ha : a < 0, lt.by_cases (assume Hb : 0 < b, absurd Hab (lt.asymm (mul_neg_of_neg_of_pos Ha Hb))) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, or.inr (and.intro Ha Hb))) -/ theorem gt_of_mul_lt_mul_neg_left {a b c : A} (H : c * a < c * b) (Hc : c ≤ 0) : a > b := sorry /- have nhc : -c ≥ 0, from neg_nonneg_of_nonpos Hc, have H2 : -(c * b) < -(c * a), from iff.mpr (neg_lt_neg_iff_lt _ _) H, have H3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : H2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left H3 nhc -/ theorem zero_gt_neg_one : -1 < (0:A) := neg_zero ▸ (neg_lt_neg zero_lt_one) theorem le_of_mul_le_of_ge_one {a b c : A} (H : a * c ≤ b) (Hb : b ≥ 0) (Hc : c ≥ 1) : a ≤ b := sorry /- have H' : a * c ≤ b * c, from calc a * c ≤ b : H ... = b * 1 : by rewrite mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left Hc Hb, le_of_mul_le_mul_right H' (lt_of_lt_of_le zero_lt_one Hc) -/ theorem nonneg_le_nonneg_of_squares_le {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b := sorry /- begin apply le_of_not_gt, intro Hab, note Hposa := lt_of_le_of_lt Hb Hab, note H' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb ... < a * a : mul_lt_mul_of_pos_left Hab Hposa, apply (not_le_of_gt H') H end -/ end /- TODO: Isabelle's library has all kinds of cancelation rules for the simplifier. Search on mult_le_cancel_right1 in Rings.thy. -/ structure decidable_linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_comm_ring A, decidable_linear_ordered_comm_group A definition decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [instance] [s : decidable_linear_ordered_comm_ring A] : decidable_linear_ordered_semiring A := ⦃decidable_linear_ordered_semiring, s, @linear_ordered_ring.to_linear_ordered_semiring A _⦄ section variable [s : decidable_linear_ordered_comm_ring A] variables {a b c : A} include s definition sign (a : A) : A := lt.cases a 0 (-1) 0 1 theorem sign_of_neg (H : a < 0) : sign a = -1 := lt.cases_of_lt H theorem sign_zero : sign 0 = (0:A) := lt.cases_of_eq rfl theorem sign_of_pos (H : a > 0) : sign a = 1 := lt.cases_of_gt H theorem sign_one : sign 1 = (1:A) := sign_of_pos zero_lt_one theorem sign_neg_one : sign (-1) = -(1:A) := sign_of_neg (neg_neg_of_pos zero_lt_one) theorem sign_sign (a : A) : sign (sign a) = sign a := sorry /- lt.by_cases (assume H : a > 0, calc sign (sign a) = sign 1 : by rewrite (sign_of_pos H) ... = 1 : by rewrite sign_one ... = sign a : by rewrite (sign_of_pos H)) (assume H : 0 = a, calc sign (sign a) = sign (sign 0) : by rewrite H ... = sign 0 : by rewrite sign_zero at {1} ... = sign a : by rewrite -H) (assume H : a < 0, calc sign (sign a) = sign (-1) : by rewrite (sign_of_neg H) ... = -1 : by rewrite sign_neg_one ... = sign a : by rewrite (sign_of_neg H)) -/ theorem pos_of_sign_eq_one (H : sign a = 1) : a > 0 := sorry /- lt.by_cases (assume H1 : 0 < a, H1) (assume H1 : 0 = a, begin rewrite [-H1 at H, sign_zero at H], apply absurd H zero_ne_one end) (assume H1 : 0 > a, have H2 : -1 = 1, from (sign_of_neg H1)⁻¹ ⬝ H, absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) -/ theorem eq_zero_of_sign_eq_zero (H : sign a = 0) : a = 0 := sorry /- lt.by_cases (assume H1 : 0 < a, absurd (H⁻¹ ⬝ sign_of_pos H1) zero_ne_one) (assume H1 : 0 = a, H1⁻¹) (assume H1 : 0 > a, have H2 : 0 = -1, from H⁻¹ ⬝ sign_of_neg H1, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) -/ theorem neg_of_sign_eq_neg_one (H : sign a = -1) : a < 0 := sorry /- lt.by_cases (assume H1 : 0 < a, have H2 : -1 = 1, from H⁻¹ ⬝ (sign_of_pos H1), absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) (assume H1 : 0 = a, have H2 : (0:A) = -1, begin rewrite [-H1 at H, sign_zero at H], exact H end, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) (assume H1 : 0 > a, H1) -/ theorem sign_neg (a : A) : sign (-a) = -(sign a) := sorry /- lt.by_cases (assume H1 : 0 < a, calc sign (-a) = -1 : sign_of_neg (neg_neg_of_pos H1) ... = -(sign a) : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc sign (-a) = sign (-0) : by rewrite H1 ... = sign 0 : by rewrite neg_zero ... = 0 : by rewrite sign_zero ... = -0 : by rewrite neg_zero ... = -(sign 0) : by rewrite sign_zero ... = -(sign a) : by rewrite -H1) (assume H1 : 0 > a, calc sign (-a) = 1 : sign_of_pos (neg_pos_of_neg H1) ... = -(-1) : by rewrite neg_neg ... = -(sign a) : by rewrite (sign_of_neg H1)) -/ theorem sign_mul (a b : A) : sign (a * b) = sign a * sign b := sorry /- lt.by_cases (assume z_lt_a : 0 < a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_pos z_lt_a, sign_of_pos z_lt_b, sign_of_pos (mul_pos z_lt_a z_lt_b), one_mul]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_pos z_lt_a, sign_of_neg z_gt_b, sign_of_neg (mul_neg_of_pos_of_neg z_lt_a z_gt_b), one_mul])) (assume z_eq_a : 0 = a, by rewrite [-z_eq_a, zero_mul, *sign_zero, zero_mul]) (assume z_gt_a : 0 > a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_neg z_gt_a, sign_of_pos z_lt_b, sign_of_neg (mul_neg_of_neg_of_pos z_gt_a z_lt_b), mul_one]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_neg z_gt_a, sign_of_neg z_gt_b, sign_of_pos (mul_pos_of_neg_of_neg z_gt_a z_gt_b), neg_mul_neg, one_mul])) -/ theorem abs_eq_sign_mul (a : A) : abs a = sign a * a := sorry /- lt.by_cases (assume H1 : 0 < a, calc abs a = a : abs_of_pos H1 ... = 1 * a : by rewrite one_mul ... = sign a * a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc abs a = abs 0 : by rewrite H1 ... = 0 : by rewrite abs_zero ... = 0 * a : by rewrite zero_mul ... = sign 0 * a : by rewrite sign_zero ... = sign a * a : by rewrite H1) (assume H1 : a < 0, calc abs a = -a : abs_of_neg H1 ... = -1 * a : by rewrite neg_eq_neg_one_mul ... = sign a * a : by rewrite (sign_of_neg H1)) -/ theorem eq_sign_mul_abs (a : A) : a = sign a * abs a := sorry /- lt.by_cases (assume H1 : 0 < a, calc a = abs a : by rewrite (abs_of_pos H1) ... = 1 * abs a : by rewrite one_mul ... = sign a * abs a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc a = 0 : H1⁻¹ ... = 0 * abs a : by rewrite zero_mul ... = sign 0 * abs a : by rewrite sign_zero ... = sign a * abs a : by rewrite H1) (assume H1 : a < 0, calc a = -(-a) : by rewrite neg_neg ... = -abs a : by rewrite (abs_of_neg H1) ... = -1 * abs a : by rewrite neg_eq_neg_one_mul ... = sign a * abs a : by rewrite (sign_of_neg H1)) -/ theorem abs_dvd_iff (a b : A) : abs a ∣ b ↔ a ∣ b := abs.by_cases (iff.refl $ a ∣ b) (neg_dvd_iff_dvd a b) theorem abs_dvd_of_dvd {a b : A} : a ∣ b → abs a ∣ b := iff.mpr $ abs_dvd_iff a b theorem dvd_abs_iff (a b : A) : a ∣ abs b ↔ a ∣ b := abs.by_cases (iff.refl $ a ∣ b) (dvd_neg_iff_dvd a b) theorem dvd_abs_of_dvd {a b : A} : a ∣ b → a ∣ abs b := iff.mpr $ dvd_abs_iff a b theorem abs_mul (a b : A) : abs (a * b) = abs a * abs b := sorry /- or.elim (le.total 0 a) (assume H1 : 0 ≤ a, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg H1 H2) ... = abs a * b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos H1 H2) ... = a * -b : by rewrite neg_mul_eq_mul_neg ... = abs a * -b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) (assume H1 : a ≤ 0, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg H1 H2) ... = -a * b : by rewrite neg_mul_eq_neg_mul ... = abs a * b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos H1 H2) ... = -a * -b : by rewrite neg_mul_neg ... = abs a * -b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) -/ theorem abs_mul_abs_self (a : A) : abs a * abs a = a * a := abs.by_cases rfl (neg_mul_neg a a) theorem abs_mul_self (a : A) : abs (a * a) = a * a := sorry -- by rewrite [abs_mul, abs_mul_abs_self] theorem sub_le_of_abs_sub_le_left (H : abs (a - b) ≤ c) : b - c ≤ a := sorry /- if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... ≥ b - c : sub_le_of_nonneg _ (le.trans !abs_nonneg H)) else (have Habs : b - a ≤ c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b ≤ c + a, from (iff.mpr !le_add_iff_sub_right_le) Habs, (iff.mp !le_add_iff_sub_left_le) Habs') -/ theorem sub_le_of_abs_sub_le_right (H : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub a b ▸ H) theorem sub_lt_of_abs_sub_lt_left (H : abs (a - b) < c) : b - c < a := sorry /- if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... > b - c : sub_lt_of_pos _ (lt_of_le_of_lt !abs_nonneg H)) else (have Habs : b - a < c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b < c + a, from lt_add_of_sub_lt_right Habs, sub_lt_left_of_lt_add Habs') -/ theorem sub_lt_of_abs_sub_lt_right (H : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ H) theorem abs_sub_square (a b : A) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := sorry /- begin rewrite [abs_mul_abs_self, *mul_sub_left_distrib, *mul_sub_right_distrib, sub_eq_add_neg (a*b), sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul, *add.assoc, {_ + b * b}add.comm, *sub_eq_add_neg], rewrite [{a*a + b*b}add.comm], rewrite [mul.comm b a, *add.assoc] end -/ theorem abs_abs_sub_abs_le_abs_sub (a b : A) : abs (abs a - abs b) ≤ abs (a - b) := sorry /- begin apply nonneg_le_nonneg_of_squares_le, repeat apply abs_nonneg, rewrite [*abs_sub_square, *abs_abs, *abs_mul_abs_self], apply sub_le_sub_left, rewrite *mul.assoc, apply mul_le_mul_of_nonneg_left, rewrite -abs_mul, apply le_abs_self, apply le_of_lt, apply add_pos, apply zero_lt_one, apply zero_lt_one end -/ lemma eq_zero_of_mul_self_add_mul_self_eq_zero {x y : A} (H : x * x + y * y = 0) : x = 0 := have x * x ≤ (0 : A), from calc x * x ≤ x * x + y * y : le_add_of_nonneg_right (mul_self_nonneg y) ... = 0 : H, eq_zero_of_mul_self_eq_zero (le.antisymm this (mul_self_nonneg x)) end /- TODO: Multiplication and one, starting with mult_right_le_one_le. -/ namespace norm_num theorem pos_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : bit0 a > 0 := sorry -- by rewrite ↑bit0; apply add_pos H H theorem nonneg_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit0 a ≥ 0 := sorry -- by rewrite ↑bit0; apply add_nonneg H H theorem pos_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a > 0 := sorry /- begin rewrite ↑bit1, apply add_pos_of_nonneg_of_pos, apply nonneg_bit0_helper _ H, apply zero_lt_one end -/ theorem nonneg_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a ≥ 0 := sorry -- by apply le_of_lt; apply pos_bit1_helper _ H theorem nonzero_of_pos_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : a ≠ 0 := ne_of_gt H theorem nonzero_of_neg_helper [s : linear_ordered_ring A] (a : A) (H : a ≠ 0) : -a ≠ 0 := sorry -- begin intro Ha, apply H, apply eq_of_neg_eq_neg, rewrite neg_zero, exact Ha end end norm_num
7bccd865742322fe4c94f8ed915e8ea98c49328c
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/sum/order.lean
d4480d93a0e80dfff56f00b80d00870a85f57b40
[ "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
22,596
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.hom.basic /-! # Orders on a sum type This file defines the disjoint sum and the linear (aka lexicographic) sum of two orders and provides relation instances for `sum.lift_rel` and `sum.lex`. We declare the disjoint sum of orders as the default set of instances. The linear order goes on a type synonym. ## Main declarations * `sum.has_le`, `sum.has_lt`: Disjoint sum of orders. * `sum.lex.has_le`, `sum.lex.has_lt`: Lexicographic/linear sum of orders. ## Notation * `α ⊕ₗ β`: The linear sum of `α` and `β`. -/ namespace sum variables {α β γ δ : Type*} /-! ### Unbundled relation classes -/ section lift_rel variables (r : α → α → Prop) (s : β → β → Prop) @[refl] lemma lift_rel.refl [is_refl α r] [is_refl β s] : ∀ x, lift_rel r s x x | (inl a) := lift_rel.inl (refl _) | (inr a) := lift_rel.inr (refl _) instance [is_refl α r] [is_refl β s] : is_refl (α ⊕ β) (lift_rel r s) := ⟨lift_rel.refl _ _⟩ instance [is_irrefl α r] [is_irrefl β s] : is_irrefl (α ⊕ β) (lift_rel r s) := ⟨by { rintro _ (⟨a, _, h⟩ | ⟨a, _, h⟩); exact irrefl _ h }⟩ @[trans] lemma lift_rel.trans [is_trans α r] [is_trans β s] : ∀ {a b c}, lift_rel r s a b → lift_rel r s b c → lift_rel r s a c | _ _ _ (lift_rel.inl hab) (lift_rel.inl hbc) := lift_rel.inl $ trans hab hbc | _ _ _ (lift_rel.inr hab) (lift_rel.inr hbc) := lift_rel.inr $ trans hab hbc instance [is_trans α r] [is_trans β s] : is_trans (α ⊕ β) (lift_rel r s) := ⟨λ _ _ _, lift_rel.trans _ _⟩ instance [is_antisymm α r] [is_antisymm β s] : is_antisymm (α ⊕ β) (lift_rel r s) := ⟨by { rintro _ _ (⟨a, b, hab⟩ | ⟨a, b, hab⟩) (⟨_, _, hba⟩ | ⟨_, _, hba⟩); rw antisymm hab hba }⟩ end lift_rel section lex variables (r : α → α → Prop) (s : β → β → Prop) instance [is_refl α r] [is_refl β s] : is_refl (α ⊕ β) (lex r s) := ⟨by { rintro (a | a), exacts [lex.inl (refl _), lex.inr (refl _)] }⟩ instance [is_irrefl α r] [is_irrefl β s] : is_irrefl (α ⊕ β) (lex r s) := ⟨by { rintro _ (⟨a, _, h⟩ | ⟨a, _, h⟩); exact irrefl _ h }⟩ instance [is_trans α r] [is_trans β s] : is_trans (α ⊕ β) (lex r s) := ⟨by { rintro _ _ _ (⟨a, b, hab⟩ | ⟨a, b, hab⟩) (⟨_, c, hbc⟩ | ⟨_, c, hbc⟩), exacts [lex.inl (trans hab hbc), lex.sep _ _, lex.inr (trans hab hbc), lex.sep _ _] }⟩ instance [is_antisymm α r] [is_antisymm β s] : is_antisymm (α ⊕ β) (lex r s) := ⟨by { rintro _ _ (⟨a, b, hab⟩ | ⟨a, b, hab⟩) (⟨_, _, hba⟩ | ⟨_, _, hba⟩); rw antisymm hab hba }⟩ instance [is_total α r] [is_total β s] : is_total (α ⊕ β) (lex r s) := ⟨λ a b, match a, b with | inl a, inl b := (total_of r a b).imp lex.inl lex.inl | inl a, inr b := or.inl (lex.sep _ _) | inr a, inl b := or.inr (lex.sep _ _) | inr a, inr b := (total_of s a b).imp lex.inr lex.inr end⟩ instance [is_trichotomous α r] [is_trichotomous β s] : is_trichotomous (α ⊕ β) (lex r s) := ⟨λ a b, match a, b with | inl a, inl b := (trichotomous_of r a b).imp3 lex.inl (congr_arg _) lex.inl | inl a, inr b := or.inl (lex.sep _ _) | inr a, inl b := or.inr (or.inr $ lex.sep _ _) | inr a, inr b := (trichotomous_of s a b).imp3 lex.inr (congr_arg _) lex.inr end⟩ instance [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { wf := sum.lex_wf is_well_order.wf is_well_order.wf } end lex /-! ### Disjoint sum of two orders -/ section disjoint instance [has_le α] [has_le β] : has_le (α ⊕ β) := ⟨lift_rel (≤) (≤)⟩ instance [has_lt α] [has_lt β] : has_lt (α ⊕ β) := ⟨lift_rel (<) (<)⟩ lemma le_def [has_le α] [has_le β] {a b : α ⊕ β} : a ≤ b ↔ lift_rel (≤) (≤) a b := iff.rfl lemma lt_def [has_lt α] [has_lt β] {a b : α ⊕ β} : a < b ↔ lift_rel (<) (<) a b := iff.rfl @[simp] lemma inl_le_inl_iff [has_le α] [has_le β] {a b : α} : (inl a : α ⊕ β) ≤ inl b ↔ a ≤ b := lift_rel_inl_inl @[simp] lemma inr_le_inr_iff [has_le α] [has_le β] {a b : β} : (inr a : α ⊕ β) ≤ inr b ↔ a ≤ b := lift_rel_inr_inr @[simp] lemma inl_lt_inl_iff [has_lt α] [has_lt β] {a b : α} : (inl a : α ⊕ β) < inl b ↔ a < b := lift_rel_inl_inl @[simp] lemma inr_lt_inr_iff [has_lt α] [has_lt β] {a b : β} : (inr a : α ⊕ β) < inr b ↔ a < b := lift_rel_inr_inr @[simp] lemma not_inl_le_inr [has_le α] [has_le β] {a : α} {b : β} : ¬ inl b ≤ inr a := not_lift_rel_inl_inr @[simp] lemma not_inl_lt_inr [has_lt α] [has_lt β] {a : α} {b : β} : ¬ inl b < inr a := not_lift_rel_inl_inr @[simp] lemma not_inr_le_inl [has_le α] [has_le β] {a : α} {b : β} : ¬ inr b ≤ inl a := not_lift_rel_inr_inl @[simp] lemma not_inr_lt_inl [has_lt α] [has_lt β] {a : α} {b : β} : ¬ inr b < inl a := not_lift_rel_inr_inl section preorder variables [preorder α] [preorder β] instance : preorder (α ⊕ β) := { le_refl := λ _, refl _, le_trans := λ _ _ _, trans, lt_iff_le_not_le := λ a b, begin refine ⟨λ hab, ⟨hab.mono (λ _ _, le_of_lt) (λ _ _, le_of_lt), _⟩, _⟩, { rintro (⟨b, a, hba⟩ | ⟨b, a, hba⟩), { exact hba.not_lt (inl_lt_inl_iff.1 hab) }, { exact hba.not_lt (inr_lt_inr_iff.1 hab) } }, { rintro ⟨⟨a, b, hab⟩ | ⟨a, b, hab⟩, hba⟩, { exact lift_rel.inl (hab.lt_of_not_le $ λ h, hba $ lift_rel.inl h) }, { exact lift_rel.inr (hab.lt_of_not_le $ λ h, hba $ lift_rel.inr h) } } end, .. sum.has_le, .. sum.has_lt } lemma inl_mono : monotone (inl : α → α ⊕ β) := λ a b, lift_rel.inl lemma inr_mono : monotone (inr : β → α ⊕ β) := λ a b, lift_rel.inr lemma inl_strict_mono : strict_mono (inl : α → α ⊕ β) := λ a b, lift_rel.inl lemma inr_strict_mono : strict_mono (inr : β → α ⊕ β) := λ a b, lift_rel.inr end preorder instance [partial_order α] [partial_order β] : partial_order (α ⊕ β) := { le_antisymm := λ _ _, antisymm, .. sum.preorder } instance no_min_order [has_lt α] [has_lt β] [no_min_order α] [no_min_order β] : no_min_order (α ⊕ β) := ⟨λ a, match a with | inl a := let ⟨b, h⟩ := exists_lt a in ⟨inl b, inl_lt_inl_iff.2 h⟩ | inr a := let ⟨b, h⟩ := exists_lt a in ⟨inr b, inr_lt_inr_iff.2 h⟩ end⟩ instance no_max_order [has_lt α] [has_lt β] [no_max_order α] [no_max_order β] : no_max_order (α ⊕ β) := ⟨λ a, match a with | inl a := let ⟨b, h⟩ := exists_gt a in ⟨inl b, inl_lt_inl_iff.2 h⟩ | inr a := let ⟨b, h⟩ := exists_gt a in ⟨inr b, inr_lt_inr_iff.2 h⟩ end⟩ @[simp] lemma no_min_order_iff [has_lt α] [has_lt β] : no_min_order (α ⊕ β) ↔ no_min_order α ∧ no_min_order β := ⟨λ _, by exactI ⟨⟨λ a, begin obtain ⟨b | b, h⟩ := exists_lt (inl a : α ⊕ β), { exact ⟨b, inl_lt_inl_iff.1 h⟩ }, { exact (not_inr_lt_inl h).elim } end⟩, ⟨λ a, begin obtain ⟨b | b, h⟩ := exists_lt (inr a : α ⊕ β), { exact (not_inl_lt_inr h).elim }, { exact ⟨b, inr_lt_inr_iff.1 h⟩ } end⟩⟩, λ h, @sum.no_min_order _ _ _ _ h.1 h.2⟩ @[simp] lemma no_max_order_iff [has_lt α] [has_lt β] : no_max_order (α ⊕ β) ↔ no_max_order α ∧ no_max_order β := ⟨λ _, by exactI ⟨⟨λ a, begin obtain ⟨b | b, h⟩ := exists_gt (inl a : α ⊕ β), { exact ⟨b, inl_lt_inl_iff.1 h⟩ }, { exact (not_inl_lt_inr h).elim } end⟩, ⟨λ a, begin obtain ⟨b | b, h⟩ := exists_gt (inr a : α ⊕ β), { exact (not_inr_lt_inl h).elim }, { exact ⟨b, inr_lt_inr_iff.1 h⟩ } end⟩⟩, λ h, @sum.no_max_order _ _ _ _ h.1 h.2⟩ instance densely_ordered [has_lt α] [has_lt β] [densely_ordered α] [densely_ordered β] : densely_ordered (α ⊕ β) := ⟨λ a b h, match a, b, h with | inl a, inl b, lift_rel.inl h := let ⟨c, ha, hb⟩ := exists_between h in ⟨to_lex (inl c), lift_rel.inl ha, lift_rel.inl hb⟩ | inr a, inr b, lift_rel.inr h := let ⟨c, ha, hb⟩ := exists_between h in ⟨to_lex (inr c), lift_rel.inr ha, lift_rel.inr hb⟩ end⟩ @[simp] lemma densely_ordered_iff [has_lt α] [has_lt β] : densely_ordered (α ⊕ β) ↔ densely_ordered α ∧ densely_ordered β := ⟨λ _, by exactI ⟨⟨λ a b h, begin obtain ⟨c | c, ha, hb⟩ := @exists_between (α ⊕ β) _ _ _ _ (inl_lt_inl_iff.2 h), { exact ⟨c, inl_lt_inl_iff.1 ha, inl_lt_inl_iff.1 hb⟩ }, { exact (not_inl_lt_inr ha).elim } end⟩, ⟨λ a b h, begin obtain ⟨c | c, ha, hb⟩ := @exists_between (α ⊕ β) _ _ _ _ (inr_lt_inr_iff.2 h), { exact (not_inl_lt_inr hb).elim }, { exact ⟨c, inr_lt_inr_iff.1 ha, inr_lt_inr_iff.1 hb⟩ } end⟩⟩, λ h, @sum.densely_ordered _ _ _ _ h.1 h.2⟩ @[simp] lemma swap_le_swap_iff [has_le α] [has_le β] {a b : α ⊕ β} : a.swap ≤ b.swap ↔ a ≤ b := lift_rel_swap_iff @[simp] lemma swap_lt_swap_iff [has_lt α] [has_lt β] {a b : α ⊕ β} : a.swap < b.swap ↔ a < b := lift_rel_swap_iff end disjoint /-! ### Linear sum of two orders -/ namespace lex notation α ` ⊕ₗ `:30 β:29 := _root_.lex (α ⊕ β) --TODO: Can we make `inlₗ`, `inrₗ` `local notation`? /-- Lexicographical `sum.inl`. Only used for pattern matching. -/ @[pattern] abbreviation _root_.sum.inlₗ (x : α) : α ⊕ₗ β := to_lex (sum.inl x) /-- Lexicographical `sum.inr`. Only used for pattern matching. -/ @[pattern] abbreviation _root_.sum.inrₗ (x : β) : α ⊕ₗ β := to_lex (sum.inr x) /-- The linear/lexicographical `≤` on a sum. -/ instance has_le [has_le α] [has_le β] : has_le (α ⊕ₗ β) := ⟨lex (≤) (≤)⟩ /-- The linear/lexicographical `<` on a sum. -/ instance has_lt [has_lt α] [has_lt β] : has_lt (α ⊕ₗ β) := ⟨lex (<) (<)⟩ @[simp] lemma to_lex_le_to_lex [has_le α] [has_le β] {a b : α ⊕ β} : to_lex a ≤ to_lex b ↔ lex (≤) (≤) a b := iff.rfl @[simp] lemma to_lex_lt_to_lex [has_lt α] [has_lt β] {a b : α ⊕ β} : to_lex a < to_lex b ↔ lex (<) (<) a b := iff.rfl lemma le_def [has_le α] [has_le β] {a b : α ⊕ₗ β} : a ≤ b ↔ lex (≤) (≤) (of_lex a) (of_lex b) := iff.rfl lemma lt_def [has_lt α] [has_lt β] {a b : α ⊕ₗ β} : a < b ↔ lex (<) (<) (of_lex a) (of_lex b) := iff.rfl @[simp] lemma inl_le_inl_iff [has_le α] [has_le β] {a b : α} : to_lex (inl a : α ⊕ β) ≤ to_lex (inl b) ↔ a ≤ b := lex_inl_inl @[simp] lemma inr_le_inr_iff [has_le α] [has_le β] {a b : β} : to_lex (inr a : α ⊕ β) ≤ to_lex (inr b) ↔ a ≤ b := lex_inr_inr @[simp] lemma inl_lt_inl_iff [has_lt α] [has_lt β] {a b : α} : to_lex (inl a : α ⊕ β) < to_lex (inl b) ↔ a < b := lex_inl_inl @[simp] lemma inr_lt_inr_iff [has_lt α] [has_lt β] {a b : β} : to_lex (inr a : α ⊕ₗ β) < to_lex (inr b) ↔ a < b := lex_inr_inr @[simp] lemma inl_le_inr [has_le α] [has_le β] (a : α) (b : β) : to_lex (inl a) ≤ to_lex (inr b) := lex.sep _ _ @[simp] lemma inl_lt_inr [has_lt α] [has_lt β] (a : α) (b : β) : to_lex (inl a) < to_lex (inr b) := lex.sep _ _ @[simp] lemma not_inr_le_inl [has_le α] [has_le β] {a : α} {b : β} : ¬ to_lex (inr b) ≤ to_lex (inl a) := lex_inr_inl @[simp] lemma not_inr_lt_inl [has_lt α] [has_lt β] {a : α} {b : β} : ¬ to_lex (inr b) < to_lex (inl a) := lex_inr_inl section preorder variables [preorder α] [preorder β] instance preorder : preorder (α ⊕ₗ β) := { le_refl := refl_of (lex (≤) (≤)), le_trans := λ _ _ _, trans_of (lex (≤) (≤)), lt_iff_le_not_le := λ a b, begin refine ⟨λ hab, ⟨hab.mono (λ _ _, le_of_lt) (λ _ _, le_of_lt), _⟩, _⟩, { rintro (⟨b, a, hba⟩ | ⟨b, a, hba⟩ | ⟨b, a⟩), { exact hba.not_lt (inl_lt_inl_iff.1 hab) }, { exact hba.not_lt (inr_lt_inr_iff.1 hab) }, { exact not_inr_lt_inl hab } }, { rintro ⟨⟨a, b, hab⟩ | ⟨a, b, hab⟩ | ⟨a, b⟩, hba⟩, { exact lex.inl (hab.lt_of_not_le $ λ h, hba $ lex.inl h) }, { exact lex.inr (hab.lt_of_not_le $ λ h, hba $ lex.inr h) }, { exact lex.sep _ _} } end, .. lex.has_le, .. lex.has_lt } lemma to_lex_mono : monotone (@to_lex (α ⊕ β)) := λ a b h, h.lex lemma to_lex_strict_mono : strict_mono (@to_lex (α ⊕ β)) := λ a b h, h.lex lemma inl_mono : monotone (to_lex ∘ inl : α → α ⊕ₗ β) := to_lex_mono.comp inl_mono lemma inr_mono : monotone (to_lex ∘ inr : β → α ⊕ₗ β) := to_lex_mono.comp inr_mono lemma inl_strict_mono : strict_mono (to_lex ∘ inl : α → α ⊕ₗ β) := to_lex_strict_mono.comp inl_strict_mono lemma inr_strict_mono : strict_mono (to_lex ∘ inr : β → α ⊕ₗ β) := to_lex_strict_mono.comp inr_strict_mono end preorder instance partial_order [partial_order α] [partial_order β] : partial_order (α ⊕ₗ β) := { le_antisymm := λ _ _, antisymm_of (lex (≤) (≤)), .. lex.preorder } instance linear_order [linear_order α] [linear_order β] : linear_order (α ⊕ₗ β) := { le_total := total_of (lex (≤) (≤)), decidable_le := lex.decidable_rel, decidable_eq := sum.decidable_eq _ _, .. lex.partial_order } /-- The lexicographical bottom of a sum is the bottom of the left component. -/ instance order_bot [has_le α] [order_bot α] [has_le β] : order_bot (α ⊕ₗ β) := { bot := inl ⊥, bot_le := begin rintro (a | b), { exact lex.inl bot_le }, { exact lex.sep _ _ } end } @[simp] lemma inl_bot [has_le α] [order_bot α] [has_le β]: to_lex (inl ⊥ : α ⊕ β) = ⊥ := rfl /-- The lexicographical top of a sum is the top of the right component. -/ instance order_top [has_le α] [has_le β] [order_top β] : order_top (α ⊕ₗ β) := { top := inr ⊤, le_top := begin rintro (a | b), { exact lex.sep _ _ }, { exact lex.inr le_top } end } @[simp] lemma inr_top [has_le α] [has_le β] [order_top β] : to_lex (inr ⊤ : α ⊕ β) = ⊤ := rfl instance bounded_order [has_le α] [has_le β] [order_bot α] [order_top β] : bounded_order (α ⊕ₗ β) := { .. lex.order_bot, .. lex.order_top } instance no_min_order [has_lt α] [has_lt β] [no_min_order α] [no_min_order β] : no_min_order (α ⊕ₗ β) := ⟨λ a, match a with | inl a := let ⟨b, h⟩ := exists_lt a in ⟨to_lex (inl b), inl_lt_inl_iff.2 h⟩ | inr a := let ⟨b, h⟩ := exists_lt a in ⟨to_lex (inr b), inr_lt_inr_iff.2 h⟩ end⟩ instance no_max_order [has_lt α] [has_lt β] [no_max_order α] [no_max_order β] : no_max_order (α ⊕ₗ β) := ⟨λ a, match a with | inl a := let ⟨b, h⟩ := exists_gt a in ⟨to_lex (inl b), inl_lt_inl_iff.2 h⟩ | inr a := let ⟨b, h⟩ := exists_gt a in ⟨to_lex (inr b), inr_lt_inr_iff.2 h⟩ end⟩ instance no_min_order_of_nonempty [has_lt α] [has_lt β] [no_min_order α] [nonempty α] : no_min_order (α ⊕ₗ β) := ⟨λ a, match a with | inl a := let ⟨b, h⟩ := exists_lt a in ⟨to_lex (inl b), inl_lt_inl_iff.2 h⟩ | inr a := ⟨to_lex (inl $ classical.arbitrary α), inl_lt_inr _ _⟩ end⟩ instance no_max_order_of_nonempty [has_lt α] [has_lt β] [no_max_order β] [nonempty β] : no_max_order (α ⊕ₗ β) := ⟨λ a, match a with | inl a := ⟨to_lex (inr $ classical.arbitrary β), inl_lt_inr _ _⟩ | inr a := let ⟨b, h⟩ := exists_gt a in ⟨to_lex (inr b), inr_lt_inr_iff.2 h⟩ end⟩ instance densely_ordered_of_no_max_order [has_lt α] [has_lt β] [densely_ordered α] [densely_ordered β] [no_max_order α] : densely_ordered (α ⊕ₗ β) := ⟨λ a b h, match a, b, h with | inl a, inl b, lex.inl h := let ⟨c, ha, hb⟩ := exists_between h in ⟨to_lex (inl c), inl_lt_inl_iff.2 ha, inl_lt_inl_iff.2 hb⟩ | inl a, inr b, lex.sep _ _ := let ⟨c, h⟩ := exists_gt a in ⟨to_lex (inl c), inl_lt_inl_iff.2 h, inl_lt_inr _ _⟩ | inr a, inr b, lex.inr h := let ⟨c, ha, hb⟩ := exists_between h in ⟨to_lex (inr c), inr_lt_inr_iff.2 ha, inr_lt_inr_iff.2 hb⟩ end⟩ instance densely_ordered_of_no_min_order [has_lt α] [has_lt β] [densely_ordered α] [densely_ordered β] [no_min_order β] : densely_ordered (α ⊕ₗ β) := ⟨λ a b h, match a, b, h with | inl a, inl b, lex.inl h := let ⟨c, ha, hb⟩ := exists_between h in ⟨to_lex (inl c), inl_lt_inl_iff.2 ha, inl_lt_inl_iff.2 hb⟩ | inl a, inr b, lex.sep _ _ := let ⟨c, h⟩ := exists_lt b in ⟨to_lex (inr c), inl_lt_inr _ _, inr_lt_inr_iff.2 h⟩ | inr a, inr b, lex.inr h := let ⟨c, ha, hb⟩ := exists_between h in ⟨to_lex (inr c), inr_lt_inr_iff.2 ha, inr_lt_inr_iff.2 hb⟩ end⟩ end lex end sum /-! ### Order isomorphisms -/ open order_dual sum namespace order_iso variables {α β γ : Type*} [has_le α] [has_le β] [has_le γ] (a : α) (b : β) (c : γ) /-- `equiv.sum_comm` promoted to an order isomorphism. -/ @[simps apply] def sum_comm (α β : Type*) [has_le α] [has_le β] : α ⊕ β ≃o β ⊕ α := { map_rel_iff' := λ a b, swap_le_swap_iff, ..equiv.sum_comm α β } @[simp] lemma sum_comm_symm (α β : Type*) [has_le α] [has_le β] : (order_iso.sum_comm α β).symm = order_iso.sum_comm β α := rfl /-- `equiv.sum_assoc` promoted to an order isomorphism. -/ def sum_assoc (α β γ : Type*) [has_le α] [has_le β] [has_le γ] : (α ⊕ β) ⊕ γ ≃o α ⊕ β ⊕ γ := { map_rel_iff' := by { rintro ((a | a) | a) ((b | b) | b); simp }, ..equiv.sum_assoc α β γ } @[simp] lemma sum_assoc_apply_inl_inl : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] lemma sum_assoc_apply_inl_inr : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] lemma sum_assoc_apply_inr : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] lemma sum_assoc_symm_apply_inl : (sum_assoc α β γ).symm (inl a) = inl (inl a) := rfl @[simp] lemma sum_assoc_symm_apply_inr_inl : (sum_assoc α β γ).symm (inr (inl b)) = inl (inr b) := rfl @[simp] lemma sum_assoc_symm_apply_inr_inr : (sum_assoc α β γ).symm (inr (inr c)) = inr c := rfl /-- `order_dual` is distributive over `⊕` up to an order isomorphism. -/ def sum_dual_distrib (α β : Type*) [has_le α] [has_le β] : (α ⊕ β)ᵒᵈ ≃o αᵒᵈ ⊕ βᵒᵈ := { map_rel_iff' := begin rintro (a | a) (b | b), { change inl (to_dual a) ≤ inl (to_dual b) ↔ to_dual (inl a) ≤ to_dual (inl b), simp only [to_dual_le_to_dual, inl_le_inl_iff] }, { exact iff_of_false not_inl_le_inr not_inr_le_inl }, { exact iff_of_false not_inr_le_inl not_inl_le_inr }, { change inr (to_dual a) ≤ inr (to_dual b) ↔ to_dual (inr a) ≤ to_dual (inr b), simp only [to_dual_le_to_dual, inr_le_inr_iff] } end, ..equiv.refl _ } @[simp] lemma sum_dual_distrib_inl : sum_dual_distrib α β (to_dual (inl a)) = inl (to_dual a) := rfl @[simp] lemma sum_dual_distrib_inr : sum_dual_distrib α β (to_dual (inr b)) = inr (to_dual b) := rfl @[simp] lemma sum_dual_distrib_symm_inl : (sum_dual_distrib α β).symm (inl (to_dual a)) = to_dual (inl a) := rfl @[simp] lemma sum_dual_distrib_symm_inr : (sum_dual_distrib α β).symm (inr (to_dual b)) = to_dual (inr b) := rfl /-- `equiv.sum_assoc` promoted to an order isomorphism. -/ def sum_lex_assoc (α β γ : Type*) [has_le α] [has_le β] [has_le γ] : (α ⊕ₗ β) ⊕ₗ γ ≃o α ⊕ₗ β ⊕ₗ γ := { map_rel_iff' := λ a b, ⟨λ h, match a, b, h with | inlₗ (inlₗ a), inlₗ (inlₗ b), lex.inl h := lex.inl $ lex.inl h | inlₗ (inlₗ a), inlₗ (inrₗ b), lex.sep _ _ := lex.inl $ lex.sep _ _ | inlₗ (inlₗ a), inrₗ b, lex.sep _ _ := lex.sep _ _ | inlₗ (inrₗ a), inlₗ (inrₗ b), lex.inr (lex.inl h) := lex.inl $ lex.inr h | inlₗ (inrₗ a), inrₗ b, lex.inr (lex.sep _ _) := lex.sep _ _ | inrₗ a, inrₗ b, lex.inr (lex.inr h) := lex.inr h end, λ h, match a, b, h with | inlₗ (inlₗ a), inlₗ (inlₗ b), lex.inl (lex.inl h) := lex.inl h | inlₗ (inlₗ a), inlₗ (inrₗ b), lex.inl (lex.sep _ _) := lex.sep _ _ | inlₗ (inlₗ a), inrₗ b, lex.sep _ _ := lex.sep _ _ | inlₗ (inrₗ a), inlₗ (inrₗ b), lex.inl (lex.inr h) := lex.inr $ lex.inl h | inlₗ (inrₗ a), inrₗ b, lex.sep _ _ := lex.inr $ lex.sep _ _ | inrₗ a, inrₗ b, lex.inr h := lex.inr $ lex.inr h end⟩, ..equiv.sum_assoc α β γ } @[simp] lemma sum_lex_assoc_apply_inl_inl : sum_lex_assoc α β γ (to_lex $ inl $ to_lex $ inl a) = to_lex (inl a) := rfl @[simp] lemma sum_lex_assoc_apply_inl_inr : sum_lex_assoc α β γ (to_lex $ inl $ to_lex $ inr b) = to_lex (inr $ to_lex $ inl b) := rfl @[simp] lemma sum_lex_assoc_apply_inr : sum_lex_assoc α β γ (to_lex $ inr c) = to_lex (inr $ to_lex $ inr c) := rfl @[simp] lemma sum_lex_assoc_symm_apply_inl : (sum_lex_assoc α β γ).symm (inl a) = inl (inl a) := rfl @[simp] lemma sum_lex_assoc_symm_apply_inr_inl : (sum_lex_assoc α β γ).symm (inr (inl b)) = inl (inr b) := rfl @[simp] lemma sum_lex_assoc_symm_apply_inr_inr : (sum_lex_assoc α β γ).symm (inr (inr c)) = inr c := rfl /-- `order_dual` is antidistributive over `⊕ₗ` up to an order isomorphism. -/ def sum_lex_dual_antidistrib (α β : Type*) [has_le α] [has_le β] : (α ⊕ₗ β)ᵒᵈ ≃o βᵒᵈ ⊕ₗ αᵒᵈ := { map_rel_iff' := begin rintro (a | a) (b | b), simp, { change to_lex (inr $ to_dual a) ≤ to_lex (inr $ to_dual b) ↔ to_dual (to_lex $ inl a) ≤ to_dual (to_lex $ inl b), simp only [to_dual_le_to_dual, lex.inl_le_inl_iff, lex.inr_le_inr_iff] }, { exact iff_of_false lex.not_inr_le_inl lex.not_inr_le_inl }, { exact iff_of_true (lex.inl_le_inr _ _) (lex.inl_le_inr _ _) }, { change to_lex (inl $ to_dual a) ≤ to_lex (inl $ to_dual b) ↔ to_dual (to_lex $ inr a) ≤ to_dual (to_lex $ inr b), simp only [to_dual_le_to_dual, lex.inl_le_inl_iff, lex.inr_le_inr_iff] } end, ..equiv.sum_comm α β } @[simp] lemma sum_lex_dual_antidistrib_inl : sum_lex_dual_antidistrib α β (to_dual (inl a)) = inr (to_dual a) := rfl @[simp] lemma sum_lex_dual_antidistrib_inr : sum_lex_dual_antidistrib α β (to_dual (inr b)) = inl (to_dual b) := rfl @[simp] lemma sum_lex_dual_antidistrib_symm_inl : (sum_lex_dual_antidistrib α β).symm (inl (to_dual b)) = to_dual (inr b) := rfl @[simp] lemma sum_lex_dual_antidistrib_symm_inr : (sum_lex_dual_antidistrib α β).symm (inr (to_dual a)) = to_dual (inl a) := rfl end order_iso
a1914dd7d9f87a569797cfd370065e2db4dac296
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/topology.lean
c8248ad88ad8928b0251e01d2ff4ff72883823c6
[ "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
16,543
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudryashov -/ import analysis.convex.combination import analysis.convex.strict import topology.path_connected import topology.algebra.affine import topology.algebra.module.basic /-! # Topological properties of convex sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We prove the following facts: * `convex.interior` : interior of a convex set is convex; * `convex.closure` : closure of a convex set is convex; * `set.finite.compact_convex_hull` : convex hull of a finite set is compact; * `set.finite.is_closed_convex_hull` : convex hull of a finite set is closed. -/ assert_not_exists has_norm open metric set open_locale pointwise convex variables {ι 𝕜 E : Type*} lemma real.convex_iff_is_preconnected {s : set ℝ} : convex ℝ s ↔ is_preconnected s := convex_iff_ord_connected.trans is_preconnected_iff_ord_connected.symm alias real.convex_iff_is_preconnected ↔ _ is_preconnected.convex /-! ### Standard simplex -/ section std_simplex variables [fintype ι] /-- Every vector in `std_simplex 𝕜 ι` has `max`-norm at most `1`. -/ lemma std_simplex_subset_closed_ball : std_simplex ℝ ι ⊆ metric.closed_ball 0 1 := begin assume f hf, rw [metric.mem_closed_ball, dist_pi_le_iff zero_le_one], intros x, rw [pi.zero_apply, real.dist_0_eq_abs, abs_of_nonneg $ hf.1 x], exact (mem_Icc_of_mem_std_simplex hf x).2, end variable (ι) /-- `std_simplex ℝ ι` is bounded. -/ lemma bounded_std_simplex : metric.bounded (std_simplex ℝ ι) := (metric.bounded_iff_subset_ball 0).2 ⟨1, std_simplex_subset_closed_ball⟩ /-- `std_simplex ℝ ι` is closed. -/ lemma is_closed_std_simplex : is_closed (std_simplex ℝ ι) := (std_simplex_eq_inter ℝ ι).symm ▸ is_closed.inter (is_closed_Inter $ λ i, is_closed_le continuous_const (continuous_apply i)) (is_closed_eq (continuous_finset_sum _ $ λ x _, continuous_apply x) continuous_const) /-- `std_simplex ℝ ι` is compact. -/ lemma is_compact_std_simplex : is_compact (std_simplex ℝ ι) := metric.is_compact_iff_is_closed_bounded.2 ⟨is_closed_std_simplex ι, bounded_std_simplex ι⟩ end std_simplex /-! ### Topological vector space -/ section topological_space variables [linear_ordered_ring 𝕜] [densely_ordered 𝕜] [topological_space 𝕜] [order_topology 𝕜] [add_comm_group E] [topological_space E] [has_continuous_add E] [module 𝕜 E] [has_continuous_smul 𝕜 E] {x y : E} lemma segment_subset_closure_open_segment : [x -[𝕜] y] ⊆ closure (open_segment 𝕜 x y) := begin rw [segment_eq_image, open_segment_eq_image, ←closure_Ioo (zero_ne_one' 𝕜)], exact image_closure_subset_closure_image (by continuity), end end topological_space section pseudo_metric_space variables [linear_ordered_ring 𝕜] [densely_ordered 𝕜] [pseudo_metric_space 𝕜] [order_topology 𝕜] [proper_space 𝕜] [compact_Icc_space 𝕜] [add_comm_group E] [topological_space E] [t2_space E] [has_continuous_add E] [module 𝕜 E] [has_continuous_smul 𝕜 E] @[simp] lemma closure_open_segment (x y : E) : closure (open_segment 𝕜 x y) = [x -[𝕜] y] := begin rw [segment_eq_image, open_segment_eq_image, ←closure_Ioo (zero_ne_one' 𝕜)], exact (image_closure_of_is_compact (bounded_Ioo _ _).is_compact_closure $ continuous.continuous_on $ by continuity).symm, end end pseudo_metric_space section has_continuous_const_smul variables [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] /-- If `s` is a convex set, then `a • interior s + b • closure s ⊆ interior s` for all `0 < a`, `0 ≤ b`, `a + b = 1`. See also `convex.combo_interior_self_subset_interior` for a weaker version. -/ lemma convex.combo_interior_closure_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • interior s + b • closure s ⊆ interior s := interior_smul₀ ha.ne' s ▸ calc interior (a • s) + b • closure s ⊆ interior (a • s) + closure (b • s) : add_subset_add subset.rfl (smul_closure_subset b s) ... = interior (a • s) + b • s : by rw is_open_interior.add_closure (b • s) ... ⊆ interior (a • s + b • s) : subset_interior_add_left ... ⊆ interior s : interior_mono $ hs.set_combo_subset ha.le hb hab /-- If `s` is a convex set, then `a • interior s + b • s ⊆ interior s` for all `0 < a`, `0 ≤ b`, `a + b = 1`. See also `convex.combo_interior_closure_subset_interior` for a stronger version. -/ lemma convex.combo_interior_self_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • interior s + b • s ⊆ interior s := calc a • interior s + b • s ⊆ a • interior s + b • closure s : add_subset_add subset.rfl $ image_subset _ subset_closure ... ⊆ interior s : hs.combo_interior_closure_subset_interior ha hb hab /-- If `s` is a convex set, then `a • closure s + b • interior s ⊆ interior s` for all `0 ≤ a`, `0 < b`, `a + b = 1`. See also `convex.combo_self_interior_subset_interior` for a weaker version. -/ lemma convex.combo_closure_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • closure s + b • interior s ⊆ interior s := by { rw add_comm, exact hs.combo_interior_closure_subset_interior hb ha (add_comm a b ▸ hab) } /-- If `s` is a convex set, then `a • s + b • interior s ⊆ interior s` for all `0 ≤ a`, `0 < b`, `a + b = 1`. See also `convex.combo_closure_interior_subset_interior` for a stronger version. -/ lemma convex.combo_self_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • s + b • interior s ⊆ interior s := by { rw add_comm, exact hs.combo_interior_self_subset_interior hb ha (add_comm a b ▸ hab) } lemma convex.combo_interior_closure_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ closure s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_interior_closure_subset_interior ha hb hab $ add_mem_add (smul_mem_smul_set hx) (smul_mem_smul_set hy) lemma convex.combo_interior_self_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_interior_closure_mem_interior hx (subset_closure hy) ha hb hab lemma convex.combo_closure_interior_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_closure_interior_subset_interior ha hb hab $ add_mem_add (smul_mem_smul_set hx) (smul_mem_smul_set hy) lemma convex.combo_self_interior_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_closure_interior_mem_interior (subset_closure hx) hy ha hb hab lemma convex.open_segment_interior_closure_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ closure s) : open_segment 𝕜 x y ⊆ interior s := begin rintro _ ⟨a, b, ha, hb, hab, rfl⟩, exact hs.combo_interior_closure_mem_interior hx hy ha hb.le hab end lemma convex.open_segment_interior_self_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ interior s := hs.open_segment_interior_closure_subset_interior hx (subset_closure hy) lemma convex.open_segment_closure_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) : open_segment 𝕜 x y ⊆ interior s := begin rintro _ ⟨a, b, ha, hb, hab, rfl⟩, exact hs.combo_closure_interior_mem_interior hx hy ha.le hb hab end lemma convex.open_segment_self_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) : open_segment 𝕜 x y ⊆ interior s := hs.open_segment_closure_interior_subset_interior (subset_closure hx) hy /-- If `x ∈ closure s` and `y ∈ interior s`, then the segment `(x, y]` is included in `interior s`. -/ lemma convex.add_smul_sub_mem_interior' {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • (y - x) ∈ interior s := by simpa only [sub_smul, smul_sub, one_smul, add_sub, add_comm] using hs.combo_interior_closure_mem_interior hy hx ht.1 (sub_nonneg.mpr ht.2) (add_sub_cancel'_right _ _) /-- If `x ∈ s` and `y ∈ interior s`, then the segment `(x, y]` is included in `interior s`. -/ lemma convex.add_smul_sub_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • (y - x) ∈ interior s := hs.add_smul_sub_mem_interior' (subset_closure hx) hy ht /-- If `x ∈ closure s` and `x + y ∈ interior s`, then `x + t y ∈ interior s` for `t ∈ (0, 1]`. -/ lemma convex.add_smul_mem_interior' {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : x + y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • y ∈ interior s := by simpa only [add_sub_cancel'] using hs.add_smul_sub_mem_interior' hx hy ht /-- If `x ∈ s` and `x + y ∈ interior s`, then `x + t y ∈ interior s` for `t ∈ (0, 1]`. -/ lemma convex.add_smul_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • y ∈ interior s := hs.add_smul_mem_interior' (subset_closure hx) hy ht /-- In a topological vector space, the interior of a convex set is convex. -/ protected lemma convex.interior {s : set E} (hs : convex 𝕜 s) : convex 𝕜 (interior s) := convex_iff_open_segment_subset.mpr $ λ x hx y hy, hs.open_segment_closure_interior_subset_interior (interior_subset_closure hx) hy /-- In a topological vector space, the closure of a convex set is convex. -/ protected lemma convex.closure {s : set E} (hs : convex 𝕜 s) : convex 𝕜 (closure s) := λ x hx y hy a b ha hb hab, let f : E → E → E := λ x' y', a • x' + b • y' in have hf : continuous (function.uncurry f), from (continuous_fst.const_smul _).add (continuous_snd.const_smul _), show f x y ∈ closure s, from map_mem_closure₂ hf hx hy (λ x' hx' y' hy', hs hx' hy' ha hb hab) open affine_map /-- A convex set `s` is strictly convex provided that for any two distinct points of `s \ interior s`, the line passing through these points has nonempty intersection with `interior s`. -/ protected lemma convex.strict_convex' {s : set E} (hs : convex 𝕜 s) (h : (s \ interior s).pairwise $ λ x y, ∃ c : 𝕜, line_map x y c ∈ interior s) : strict_convex 𝕜 s := begin refine strict_convex_iff_open_segment_subset.2 _, intros x hx y hy hne, by_cases hx' : x ∈ interior s, { exact hs.open_segment_interior_self_subset_interior hx' hy }, by_cases hy' : y ∈ interior s, { exact hs.open_segment_self_interior_subset_interior hx hy' }, rcases h ⟨hx, hx'⟩ ⟨hy, hy'⟩ hne with ⟨c, hc⟩, refine (open_segment_subset_union x y ⟨c, rfl⟩).trans (insert_subset.2 ⟨hc, union_subset _ _⟩), exacts [hs.open_segment_self_interior_subset_interior hx hc, hs.open_segment_interior_self_subset_interior hc hy] end /-- A convex set `s` is strictly convex provided that for any two distinct points `x`, `y` of `s \ interior s`, the segment with endpoints `x`, `y` has nonempty intersection with `interior s`. -/ protected lemma convex.strict_convex {s : set E} (hs : convex 𝕜 s) (h : (s \ interior s).pairwise $ λ x y, ([x -[𝕜] y] \ frontier s).nonempty) : strict_convex 𝕜 s := begin refine (hs.strict_convex' $ h.imp_on $ λ x hx y hy hne, _), simp only [segment_eq_image_line_map, ← self_diff_frontier], rintro ⟨_, ⟨⟨c, hc, rfl⟩, hcs⟩⟩, refine ⟨c, hs.segment_subset hx.1 hy.1 _, hcs⟩, exact (segment_eq_image_line_map 𝕜 x y).symm ▸ mem_image_of_mem _ hc end end has_continuous_const_smul section has_continuous_smul variables [add_comm_group E] [module ℝ E] [topological_space E] [topological_add_group E] [has_continuous_smul ℝ E] /-- Convex hull of a finite set is compact. -/ lemma set.finite.compact_convex_hull {s : set E} (hs : s.finite) : is_compact (convex_hull ℝ s) := begin rw [hs.convex_hull_eq_image], apply (is_compact_std_simplex _).image, haveI := hs.fintype, apply linear_map.continuous_on_pi end /-- Convex hull of a finite set is closed. -/ lemma set.finite.is_closed_convex_hull [t2_space E] {s : set E} (hs : s.finite) : is_closed (convex_hull ℝ s) := hs.compact_convex_hull.is_closed open affine_map /-- If we dilate the interior of a convex set about a point in its interior by a scale `t > 1`, the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.closure_subset_image_homothety_interior_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : closure s ⊆ homothety x t '' interior s := begin intros y hy, have hne : t ≠ 0, from (one_pos.trans ht).ne', refine ⟨homothety x t⁻¹ y, hs.open_segment_interior_closure_subset_interior hx hy _, (affine_equiv.homothety_units_mul_hom x (units.mk0 t hne)).apply_symm_apply y⟩, rw [open_segment_eq_image_line_map, ← inv_one, ← inv_Ioi (zero_lt_one' ℝ), ← image_inv, image_image, homothety_eq_line_map], exact mem_image_of_mem _ ht end /-- If we dilate a convex set about a point in its interior by a scale `t > 1`, the interior of the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.closure_subset_interior_image_homothety_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : closure s ⊆ interior (homothety x t '' s) := (hs.closure_subset_image_homothety_interior_of_one_lt hx t ht).trans $ (homothety_is_open_map x t (one_pos.trans ht).ne').image_interior_subset _ /-- If we dilate a convex set about a point in its interior by a scale `t > 1`, the interior of the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.subset_interior_image_homothety_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : s ⊆ interior (homothety x t '' s) := subset_closure.trans $ hs.closure_subset_interior_image_homothety_of_one_lt hx t ht /-- A nonempty convex set is path connected. -/ protected lemma convex.is_path_connected {s : set E} (hconv : convex ℝ s) (hne : s.nonempty) : is_path_connected s := begin refine is_path_connected_iff.mpr ⟨hne, _⟩, intros x x_in y y_in, have H := hconv.segment_subset x_in y_in, rw segment_eq_image_line_map at H, exact joined_in.of_line affine_map.line_map_continuous.continuous_on (line_map_apply_zero _ _) (line_map_apply_one _ _) H end /-- A nonempty convex set is connected. -/ protected lemma convex.is_connected {s : set E} (h : convex ℝ s) (hne : s.nonempty) : is_connected s := (h.is_path_connected hne).is_connected /-- A convex set is preconnected. -/ protected lemma convex.is_preconnected {s : set E} (h : convex ℝ s) : is_preconnected s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ is_preconnected_empty) (λ hne, (h.is_connected hne).is_preconnected) /-- Every topological vector space over ℝ is path connected. Not an instance, because it creates enormous TC subproblems (turn on `pp.all`). -/ protected lemma topological_add_group.path_connected : path_connected_space E := path_connected_space_iff_univ.mpr $ convex_univ.is_path_connected ⟨(0 : E), trivial⟩ end has_continuous_smul
ed3b4912ed130086f5857564747c0fcf30970d96
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/complex/circle.lean
5e5c94ccdf85709780b95ec773ce33d51abf6bd5
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,908
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.special_functions.exp import topology.continuous_function.basic /-! # The circle This file defines `circle` to be the metric sphere (`metric.sphere`) in `ℂ` centred at `0` of radius `1`. We equip it with the following structure: * a submonoid of `ℂ` * a group * a topological group We furthermore define `exp_map_circle` to be the natural map `λ t, exp (t * I)` from `ℝ` to `circle`, and show that this map is a group homomorphism. ## Implementation notes Because later (in `geometry.manifold.instances.sphere`) one wants to equip the circle with a smooth manifold structure borrowed from `metric.sphere`, the underlying set is `{z : ℂ | abs (z - 0) = 1}`. This prevents certain algebraic facts from working definitionally -- for example, the circle is not defeq to `{z : ℂ | abs z = 1}`, which is the kernel of `complex.abs` considered as a homomorphism from `ℂ` to `ℝ`, nor is it defeq to `{z : ℂ | norm_sq z = 1}`, which is the kernel of the homomorphism `complex.norm_sq` from `ℂ` to `ℝ`. -/ noncomputable theory open complex metric open_locale complex_conjugate /-- The unit circle in `ℂ`, here given the structure of a submonoid of `ℂ`. -/ def circle : submonoid ℂ := { carrier := sphere (0:ℂ) 1, one_mem' := by simp, mul_mem' := λ a b, begin simp only [norm_eq_abs, mem_sphere_zero_iff_norm], intros ha hb, simp [ha, hb], end } @[simp] lemma mem_circle_iff_abs {z : ℂ} : z ∈ circle ↔ abs z = 1 := mem_sphere_zero_iff_norm lemma circle_def : ↑circle = {z : ℂ | abs z = 1} := set.ext $ λ z, mem_circle_iff_abs @[simp] lemma abs_coe_circle (z : circle) : abs z = 1 := mem_circle_iff_abs.mp z.2 lemma mem_circle_iff_norm_sq {z : ℂ} : z ∈ circle ↔ norm_sq z = 1 := by rw [mem_circle_iff_abs, complex.abs, real.sqrt_eq_one] @[simp] lemma norm_sq_eq_of_mem_circle (z : circle) : norm_sq z = 1 := by simp [norm_sq_eq_abs] lemma ne_zero_of_mem_circle (z : circle) : (z:ℂ) ≠ 0 := ne_zero_of_mem_unit_sphere z instance : comm_group circle := { inv := λ z, ⟨conj (z : ℂ), by simp⟩, mul_left_inv := λ z, subtype.ext $ by { simp [has_inv.inv, ← norm_sq_eq_conj_mul_self, ← mul_self_abs] }, .. circle.to_comm_monoid } lemma coe_inv_circle_eq_conj (z : circle) : ↑(z⁻¹) = conj (z : ℂ) := rfl @[simp] lemma coe_inv_circle (z : circle) : ↑(z⁻¹) = (z : ℂ)⁻¹ := begin rw coe_inv_circle_eq_conj, apply eq_inv_of_mul_eq_one_right, rw [mul_comm, ← complex.norm_sq_eq_conj_mul_self], simp, end @[simp] lemma coe_div_circle (z w : circle) : ↑(z / w) = (z:ℂ) / w := show ↑(z * w⁻¹) = (z:ℂ) * w⁻¹, by simp /-- The elements of the circle embed into the units. -/ @[simps] def circle.to_units : circle →* units ℂ := { to_fun := λ x, units.mk0 x $ ne_zero_of_mem_circle _, map_one' := units.ext rfl, map_mul' := λ x y, units.ext rfl } instance : compact_space circle := metric.sphere.compact_space _ _ -- the following result could instead be deduced from the Lie group structure on the circle using -- `topological_group_of_lie_group`, but that seems a little awkward since one has to first provide -- and then forget the model space instance : topological_group circle := { continuous_mul := let h : continuous (λ x : circle, (x : ℂ)) := continuous_subtype_coe in continuous_induced_rng (continuous_mul.comp (h.prod_map h)), continuous_inv := continuous_induced_rng $ complex.conj_cle.continuous.comp continuous_subtype_coe } /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`. -/ def exp_map_circle : C(ℝ, circle) := { to_fun := λ t, ⟨exp (t * I), by simp [exp_mul_I, abs_cos_add_sin_mul_I]⟩ } @[simp] lemma exp_map_circle_apply (t : ℝ) : ↑(exp_map_circle t) = complex.exp (t * complex.I) := rfl @[simp] lemma exp_map_circle_zero : exp_map_circle 0 = 1 := subtype.ext $ by rw [exp_map_circle_apply, of_real_zero, zero_mul, exp_zero, submonoid.coe_one] @[simp] lemma exp_map_circle_add (x y : ℝ) : exp_map_circle (x + y) = exp_map_circle x * exp_map_circle y := subtype.ext $ by simp only [exp_map_circle_apply, submonoid.coe_mul, of_real_add, add_mul, complex.exp_add] /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`, considered as a homomorphism of groups. -/ @[simps] def exp_map_circle_hom : ℝ →+ (additive circle) := { to_fun := additive.of_mul ∘ exp_map_circle, map_zero' := exp_map_circle_zero, map_add' := exp_map_circle_add } @[simp] lemma exp_map_circle_sub (x y : ℝ) : exp_map_circle (x - y) = exp_map_circle x / exp_map_circle y := exp_map_circle_hom.map_sub x y @[simp] lemma exp_map_circle_neg (x : ℝ) : exp_map_circle (-x) = (exp_map_circle x)⁻¹ := exp_map_circle_hom.map_neg x
93ae41eced3dab42350626100456826e0fce22de
63abd62053d479eae5abf4951554e1064a4c45b4
/test/norm_cast.lean
b27b07eae174fe2f2bb3746422948839884f7127
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
4,182
lean
/- Tests for norm_cast -/ import tactic.norm_cast import data.complex.basic -- ℕ, ℤ, ℚ, ℝ, ℂ import data.real.ennreal constants (an bn cn dn : ℕ) (az bz cz dz : ℤ) (aq bq cq dq : ℚ) constants (ar br cr dr : ℝ) (ac bc cc dc : ℂ) example : (an : ℤ) = bn → an = bn := by {intro h, exact_mod_cast h} example : an = bn → (an : ℤ) = bn := by {intro h, exact_mod_cast h} example : az = bz ↔ (az : ℚ) = bz := by norm_cast example : (aq : ℝ) = br ↔ (aq : ℂ) = br := by norm_cast example : (an : ℚ) = bz ↔ (an : ℂ) = bz := by norm_cast example : (((an : ℤ) : ℚ) : ℝ) = bq ↔ ((an : ℚ) : ℂ) = (bq : ℝ) := by norm_cast example : (an : ℤ) < bn ↔ an < bn := by norm_cast example : (an : ℚ) < bz ↔ (an : ℝ) < bz := by norm_cast example : ((an : ℤ) : ℝ) < bq ↔ (an : ℚ) < bq := by norm_cast example : (an : ℤ) ≠ (bn : ℤ) ↔ an ≠ bn := by norm_cast -- zero and one cause special problems example : 0 < (bq : ℝ) ↔ 0 < bq := by norm_cast example : az > (1 : ℕ) ↔ az > 1 := by norm_cast example : az > (0 : ℕ) ↔ az > 0 := by norm_cast example : (an : ℤ) ≠ 0 ↔ an ≠ 0 := by norm_cast example : aq < (1 : ℕ) ↔ (aq : ℝ) < (1 : ℤ) := by norm_cast example : (an : ℤ) + bn = (an + bn : ℕ) := by norm_cast example : (an : ℂ) + bq = ((an + bq) : ℚ) := by norm_cast example : (((an : ℤ) : ℚ) : ℝ) + bn = (an + (bn : ℤ)) := by norm_cast example : (((((an : ℚ) : ℝ) * bq) + (cq : ℝ) ^ dn) : ℂ) = (an : ℂ) * (bq : ℝ) + cq ^ dn := by norm_cast example : ((an : ℤ) : ℝ) < bq ∧ (cr : ℂ) ^ 2 = dz ↔ (an : ℚ) < bq ∧ ((cr ^ 2) : ℂ) = dz := by norm_cast --testing numerals example : ((42 : ℕ) : ℤ) = 42 := by norm_cast example : ((42 : ℕ) : ℂ) = 42 := by norm_cast example : ((42 : ℤ) : ℚ) = 42 := by norm_cast example : ((42 : ℚ) : ℝ) = 42 := by norm_cast example (h : (an : ℝ) = 0) : an = 0 := by exact_mod_cast h example (h : (an : ℝ) = 42) : an = 42 := by exact_mod_cast h example (h : (an + 42) ≠ 42) : (an : ℝ) + 42 ≠ 42 := by exact_mod_cast h -- testing the heuristic example (h : bn ≤ an) : an - bn = 1 ↔ (an - bn : ℤ) = 1 := by norm_cast example (h : (cz : ℚ) = az / bz) : (cz : ℝ) = az / bz := by assumption_mod_cast namespace hidden def with_zero (α) := option α variables {α : Type*} instance : has_coe_t α (with_zero α) := ⟨some⟩ instance : has_zero (with_zero α) := ⟨none⟩ instance [has_one α]: has_one (with_zero α) := ⟨some 1⟩ instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a * b)), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..hidden.with_zero.has_zero } @[norm_cast] lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl @[norm_cast] lemma coe_inj {a b : α} : (a : with_zero α) = b ↔ a = b := option.some_inj @[norm_cast] lemma mul_coe {α : Type*} [has_mul α] (a b : α) : ((a * b : α) : with_zero α) = (a : with_zero α) * b := rfl example [has_mul α] [has_one α] (x y : α) (h : (x : with_zero α) * y = 1) : x*y = 1 := by exact_mod_cast h end hidden example (k : ℕ) {x y : ℕ} : (x * x + y * y : ℤ) - ↑((x * y + 1) * k) = ↑y * ↑y - ↑k * ↑x * ↑y + (↑x * ↑x - ↑k) := begin push_cast, ring end example (k : ℕ) {x y : ℕ} (h : ((x + y + k : ℕ) : ℤ) = 0) : x + y + k = 0 := begin push_cast at h, guard_hyp h : (x : ℤ) + y + k = 0, assumption_mod_cast end example (a b : ℕ) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast [int.add_zero] at h2, exact h2 end example {x : ℚ} : ((x + 42 : ℚ) : ℝ) = x + 42 := by push_cast namespace ennreal --TODO: debug lemma half_lt_self_bis {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a := begin lift a to nnreal using ht, have h : (2 : ennreal) = ((2 : nnreal) : ennreal), from rfl, have h' : (2 : nnreal) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end end ennreal
dd9172d6e2c7dc60c0948f3f001253fd43d7d514
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/quot.lean
8d39c0779b04902c7a56b4e131d1bb9749b7988e
[ "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
21,108
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 logic.relator /-! # Quotient types This module extends the core library's treatment of quotient types (`init.data.quot`). ## Tags quotient -/ variables {α : Sort*} {β : Sort*} namespace setoid lemma ext {α : Sort*} : ∀{s t : setoid α}, (∀a b, @setoid.r α s a b ↔ @setoid.r α t a b) → s = t | ⟨r, _⟩ ⟨p, _⟩ eq := have r = p, from funext $ assume a, funext $ assume b, propext $ eq a b, by subst this end setoid namespace quot variables {ra : α → α → Prop} {rb : β → β → Prop} {φ : quot ra → quot rb → Sort*} local notation `⟦`:max a `⟧` := quot.mk _ a instance [inhabited α] : inhabited (quot ra) := ⟨⟦default _⟧⟩ /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quot ra) (qb : quot rb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (ca : ∀ {b a₁ a₂}, ra a₁ a₂ → f a₁ b == f a₂ b) (cb : ∀ {a b₁ b₂}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb := quot.hrec_on qa (λ a, quot.hrec_on qb (f a) (λ b₁ b₂ pb, cb pb)) $ λ a₁ a₂ pa, quot.induction_on qb $ λ b, calc @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₁) (@cb _) == f a₁ b : by simp [heq_self_iff_true] ... == f a₂ b : ca pa ... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp [heq_self_iff_true] /-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)` to a map `quot ra → quot rb`. -/ protected def map (f : α → β) (h : (ra ⇒ rb) f f) : quot ra → quot rb := quot.lift (λ x, ⟦f x⟧) $ assume x y (h₁ : ra x y), quot.sound $ h h₁ /-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra → quot ra'`. -/ protected def map_right {ra' : α → α → Prop} (h : ∀a₁ a₂, ra a₁ a₂ → ra' a₁ a₂) : quot ra → quot ra' := quot.map id h /-- weaken the relation of a quotient -/ def factor {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : quot r → quot s := quot.lift (quot.mk s) (λ x y rxy, quot.sound (h x y rxy)) lemma factor_mk_eq {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : factor r s h ∘ quot.mk _ = quot.mk _ := rfl variables {γ : Sort*} {r : α → α → Prop} {s : β → β → Prop} /-- **Alias** of `quot.lift_beta`. -/ lemma lift_mk (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) (a : α) : quot.lift f h (quot.mk r a) = f a := quot.lift_beta f h a @[simp] lemma lift_on_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : quot.lift_on (quot.mk r a) f h = f a := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β`. -/ attribute [reducible, elab_as_eliminator] protected def lift₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (q₁ : quot r) (q₂ : quot s) : γ := quot.lift (λ a, quot.lift (f a) (hr a)) (λ a₁ a₂ ha, funext (λ q, quot.induction_on q (λ b, hs a₁ a₂ b ha))) q₁ q₂ @[simp] lemma lift₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (a : α) (b : β) : quot.lift₂ f hr hs (quot.mk r a) (quot.mk s b) = f a b := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` and applies it. -/ attribute [reducible, elab_as_eliminator] protected def lift_on₂ (p : quot r) (q : quot s) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : γ := quot.lift₂ f hr hs p q @[simp] lemma lift_on₂_mk (a : α) (b : β) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift_on₂ (quot.mk r a) (quot.mk s b) f hr hs = f a b := rfl variables {t : γ → γ → Prop} /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` wih values in a quotient of `γ`. -/ protected def map₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (q₁ : quot r) (q₂ : quot s) : quot t := quot.lift₂ (λ a b, quot.mk t $ f a b) (λ a b₁ b₂ hb, quot.sound (hr a b₁ b₂ hb)) (λ a₁ a₂ b ha, quot.sound (hs a₁ a₂ b ha)) q₁ q₂ @[simp] lemma map₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (a : α) (b : β) : quot.map₂ f hr hs (quot.mk r a) (quot.mk s b) = quot.mk t (f a b) := rfl attribute [elab_as_eliminator] protected lemma induction_on₂ {δ : quot r → quot s → Prop} (q₁ : quot r) (q₂ : quot s) (h : ∀ a b, δ (quot.mk r a) (quot.mk s b)) : δ q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, h a₁ a₂) q₂) q₁ attribute [elab_as_eliminator] protected lemma induction_on₃ {δ : quot r → quot s → quot t → Prop} (q₁ : quot r) (q₂ : quot s) (q₃ : quot t) (h : ∀ a b c, δ (quot.mk r a) (quot.mk s b) (quot.mk t c)) : δ q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, h a₁ a₂ a₃) q₃) q₂) q₁ end quot namespace quotient variables [sa : setoid α] [sb : setoid β] variables {φ : quotient sa → quotient sb → Sort*} instance [inhabited α] : inhabited (quotient sa) := ⟨⟦default _⟧⟩ /-- Induction on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quotient sa) (qb : quotient sb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quot.hrec_on₂ qa qb f (λ _ _ _ p, c _ _ _ _ p (setoid.refl _)) (λ _ _ _ p, c _ _ _ _ (setoid.refl _) p) /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient sa → quotient sb := quot.map f h @[simp] lemma map_mk (f : α → β) (h : ((≈) ⇒ (≈)) f f) (x : α) : quotient.map f h (⟦x⟧ : quotient sa) = (⟦f x⟧ : quotient sb) := rfl variables {γ : Sort*} [sc : setoid γ] /-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements to a function `f : quotient sa → quotient sb → quotient sc`. Useful to define binary operations on quotients. -/ protected def map₂ (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient sa → quotient sb → quotient sc := quotient.lift₂ (λ x y, ⟦f x y⟧) (λ x₁ y₁ x₂ y₂ h₁ h₂, quot.sound $ h h₁ h₂) end quotient lemma quot.eq {α : Type*} {r : α → α → Prop} {x y : α} : quot.mk r x = quot.mk r y ↔ eqv_gen r x y := ⟨quot.exact r, quot.eqv_gen_sound⟩ @[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := ⟨quotient.exact, quotient.sound⟩ theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} : (∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) := ⟨assume h x, h _, assume h a, a.induction_on h⟩ @[simp] lemma quotient.lift_mk [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift f h (quotient.mk x) = f x := rfl @[simp] lemma quotient.lift_on_mk [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift_on (quotient.mk x) f h = f x := rfl @[simp] theorem quotient.lift_on₂_mk {α : Sort*} {β : Sort*} [setoid α] (f : α → α → β) (h : ∀ (a₁ a₂ b₁ b₂ : α), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (x y : α) : quotient.lift_on₂ (quotient.mk x) (quotient.mk y) f h = f x y := rfl /-- `quot.mk r` is a surjective function. -/ lemma surjective_quot_mk (r : α → α → Prop) : function.surjective (quot.mk r) := quot.exists_rep /-- `quotient.mk` is a surjective function. -/ lemma surjective_quotient_mk (α : Sort*) [s : setoid α] : function.surjective (quotient.mk : α → quotient s) := quot.exists_rep /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α := classical.some (quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast @[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q := classical.some_spec (quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out @[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a := quotient.exact (quotient.out_eq _) instance pi_setoid {ι : Sort*} {α : ι → Sort*} [∀ i, setoid (α i)] : setoid (Π i, α i) := { r := λ a b, ∀ i, a i ≈ b i, iseqv := ⟨ λ a i, setoid.refl _, λ a b h i, setoid.symm (h _), λ a b c h₁ h₂ i, setoid.trans (h₁ _) (h₂ _)⟩ } /-- Given a function `f : Π i, quotient (S i)`, returns the class of functions `Π i, α i` sending each `i` to an element of the class `f i`. -/ noncomputable def quotient.choice {ι : Type*} {α : ι → Type*} [S : Π i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := ⟦λ i, (f i).out⟧ theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [Π i, setoid (α i)] (f : Π i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ := quotient.sound $ λ i, quotient.mk_out _ lemma nonempty_quotient_iff (s : setoid α) : nonempty (quotient s) ↔ nonempty α := ⟨assume ⟨a⟩, quotient.induction_on a nonempty.intro, assume ⟨a⟩, ⟨⟦a⟧⟩⟩ /-- `trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def {u} trunc (α : Sort u) : Sort u := @quot α (λ _ _, true) theorem true_equivalence : @equivalence α (λ _ _, true) := ⟨λ _, trivial, λ _ _ _, trivial, λ _ _ _ _ _, trivial⟩ namespace trunc /-- Constructor for `trunc α` -/ def mk (a : α) : trunc α := quot.mk _ a instance [inhabited α] : inhabited (trunc α) := ⟨mk (default _)⟩ /-- Any constant function lifts to a function out of the truncation -/ def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β := quot.lift f (λ a b _, c a b) theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind protected theorem lift_mk (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl /-- Lift a constant function on `q : trunc α`. -/ @[reducible, elab_as_eliminator] protected def lift_on (q : trunc α) (f : α → β) (c : ∀ a b : α, f a = f b) : β := lift f c q @[elab_as_eliminator] protected theorem induction_on {β : trunc α → Prop} (q : trunc α) (h : ∀ a, β (mk a)) : β q := ind h q theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q attribute [elab_as_eliminator] protected theorem induction_on₂ {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ := trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁) protected theorem eq (a b : trunc α) : a = b := trunc.induction_on₂ a b (λ x y, quot.sound trivial) instance : subsingleton (trunc α) := ⟨trunc.eq⟩ /-- The `bind` operator for the `trunc` monad. -/ def bind (q : trunc α) (f : α → trunc β) : trunc β := trunc.lift_on q f (λ a b, trunc.eq _ _) /-- A function `f : α → β` defines a function `map f : trunc α → trunc β`. -/ def map (f : α → β) (q : trunc α) : trunc β := bind q (trunc.mk ∘ f) instance : monad trunc := { pure := @trunc.mk, bind := @trunc.bind } instance : is_lawful_monad trunc := { id_map := λ α q, trunc.eq _ _, pure_bind := λ α β q f, rfl, bind_assoc := λ α β γ x f g, trunc.eq _ _ } variable {C : trunc α → Sort*} /-- Recursion/induction principle for `trunc`. -/ @[reducible, elab_as_eliminator] protected def rec (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) (q : trunc α) : C q := quot.rec f (λ a b _, h a b) q /-- A version of `trunc.rec` taking `q : trunc α` as the first argument. -/ @[reducible, elab_as_eliminator] protected def rec_on (q : trunc α) (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q := trunc.rec f h q /-- A version of `trunc.rec_on` assuming the codomain is a `subsingleton`. -/ @[reducible, elab_as_eliminator] protected def rec_on_subsingleton [∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q := trunc.rec f (λ a b, subsingleton.elim _ (f b)) q /-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/ noncomputable def out : trunc α → α := quot.out @[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _ protected theorem nonempty (q : trunc α) : nonempty α := nonempty_of_exists q.exists_rep end trunc namespace quotient variables {γ : Sort*} {φ : Sort*} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} /- Versions of quotient definitions and lemmas ending in `'` use unification instead of typeclass inference for inferring the `setoid` argument. This is useful when there are several different quotient relations on a type, for example quotient groups, rings and modules -/ /-- A version of `quotient.mk` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected def mk' (a : α) : quotient s₁ := quot.mk s₁.1 a /-- `quotient.mk'` is a surjective function. -/ lemma surjective_quotient_mk' : function.surjective (quotient.mk' : α → quotient s₁) := quot.exists_rep /-- A version of `quotient.lift_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator, reducible] protected def lift_on' (q : quotient s₁) (f : α → φ) (h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : φ := quotient.lift_on q f h @[simp] protected lemma lift_on'_mk' (f : α → φ) (h) (x : α) : quotient.lift_on' (@quotient.mk' _ s₁ x) f h = f x := rfl /-- A version of `quotient.lift_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator, reducible] protected def lift_on₂' (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ) (h : ∀ a₁ a₂ b₁ b₂, @setoid.r α s₁ a₁ b₁ → @setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ := quotient.lift_on₂ q₁ q₂ f h @[simp] protected lemma lift_on₂'_mk' (f : α → β → γ) (h) (a : α) (b : β) : quotient.lift_on₂' (@quotient.mk' _ s₁ a) (@quotient.mk' _ s₂ b) f h = f a b := rfl /-- A version of `quotient.ind` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma ind' {p : quotient s₁ → Prop} (h : ∀ a, p (quotient.mk' a)) (q : quotient s₁) : p q := quotient.ind h q /-- A version of `quotient.ind₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma ind₂' {p : quotient s₁ → quotient s₂ → Prop} (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) (q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ := quotient.ind₂ h q₁ q₂ /-- A version of `quotient.induction_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma induction_on' {p : quotient s₁ → Prop} (q : quotient s₁) (h : ∀ a, p (quotient.mk' a)) : p q := quotient.induction_on q h /-- A version of `quotient.induction_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₂' {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ := quotient.induction_on₂ q₁ q₂ h /-- A version of `quotient.induction_on₃` taking `{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₃' {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ a₁ a₂ a₃, p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ := quotient.induction_on₃ q₁ q₂ q₃ h /-- A version of `quotient.rec_on_subsingleton` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected def rec_on_subsingleton' {φ : quotient s₁ → Sort*} [h : ∀ a, subsingleton (φ ⟦a⟧)] (q : quotient s₁) (f : Π a, φ (quotient.mk' a)) : φ q := quotient.rec_on_subsingleton q f /-- Recursion on a `quotient` argument `a`, result type depends on `⟦a⟧`. -/ protected def hrec_on' {φ : quotient s₁ → Sort*} (qa : quotient s₁) (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) : φ qa := quot.hrec_on qa f c @[simp] lemma hrec_on'_mk' {φ : quotient s₁ → Sort*} (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) (x : α) : (quotient.mk' x).hrec_on' f c = f x := rfl /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂' {φ : quotient s₁ → quotient s₂ → Sort*} (qa : quotient s₁) (qb : quotient s₂) (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quotient.hrec_on₂ qa qb f c @[simp] lemma hrec_on₂'_mk' {φ : quotient s₁ → quotient s₂ → Sort*} (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) (x : α) (qb : quotient s₂) : (quotient.mk' x).hrec_on₂' qb f c = qb.hrec_on' (f x) (λ b₁ b₂, c _ _ _ _ (setoid.refl _)) := rfl /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map' (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient s₁ → quotient s₂ := quot.map f h @[simp] lemma map'_mk' (f : α → β) (h) (x : α) : (quotient.mk' x : quotient s₁).map' f h = (quotient.mk' (f x) : quotient s₂) := rfl /-- A version of `quotient.map₂` using curly braces and unification. -/ protected def map₂' (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient s₁ → quotient s₂ → quotient s₃ := quotient.map₂ f h @[simp] lemma map₂'_mk' (f : α → β → γ) (h) (x : α) : (quotient.mk' x : quotient s₁).map₂' f h = (quotient.map' (f x) (h (setoid.refl x)) : quotient s₂ → quotient s₃) := rfl lemma exact' {a b : α} : (quotient.mk' a : quotient s₁) = quotient.mk' b → @setoid.r _ s₁ a b := quotient.exact lemma sound' {a b : α} : @setoid.r _ s₁ a b → @quotient.mk' α s₁ a = quotient.mk' b := quotient.sound @[simp] protected lemma eq' {a b : α} : @quotient.mk' α s₁ a = quotient.mk' b ↔ @setoid.r _ s₁ a b := quotient.eq /-- A version of `quotient.out` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ noncomputable def out' (a : quotient s₁) : α := quotient.out a @[simp] theorem out_eq' (q : quotient s₁) : quotient.mk' q.out' = q := q.out_eq theorem mk_out' (a : α) : @setoid.r α s₁ (quotient.mk' a : quotient s₁).out' a := quotient.exact (quotient.out_eq _) end quotient
643ca2d4f08609cea7234e2766bccb585fb69506
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/urysohns_lemma.lean
fee103e9d2dd19c869cb1a706e8e8375196e94e2
[ "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
12,652
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.normed_space.add_torsor import linear_algebra.affine_space.ordered import topology.continuous_function.basic /-! # Urysohn's lemma In this file we prove Urysohn's lemma `exists_continuous_zero_one_of_closed`: for any two disjoint closed sets `s` and `t` in a normal topological space `X` there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. ## Implementation notes Most paper sources prove Urysohn's lemma using a family of open sets indexed by dyadic rational numbers on `[0, 1]`. There are many technical difficulties with formalizing this proof (e.g., one needs to formalize the "dyadic induction", then prove that the resulting family of open sets is monotone). So, we formalize a slightly different proof. Let `urysohns.CU` be the type of pairs `(C, U)` of a closed set `C`and an open set `U` such that `C ⊆ U`. Since `X` is a normal topological space, for each `c : CU X` there exists an open set `u` such that `c.C ⊆ u ∧ closure u ⊆ c.U`. We define `c.left` and `c.right` to be `(c.C, u)` and `(closure u, c.U)`, respectively. Then we define a family of functions `urysohns.CU.approx (c : urysohns.CU X) (n : ℕ) : X → ℝ` by recursion on `n`: * `c.approx 0` is the indicator of `c.Uᶜ`; * `c.approx (n + 1) x = (c.left.approx n x + c.right.approx n x) / 2`. For each `x` this is a monotone family of functions that are equal to zero on `c.C` and are equal to one outside of `c.U`. We also have `c.approx n x ∈ [0, 1]` for all `c`, `n`, and `x`. Let `urysohns.CU.lim c` be the supremum (or equivalently, the limit) of `c.approx n`. Then properties of `urysohns.CU.approx` immediately imply that * `c.lim x ∈ [0, 1]` for all `x`; * `c.lim` equals zero on `c.C` and equals one outside of `c.U`; * `c.lim x = (c.left.lim x + c.right.lim x) / 2`. In order to prove that `c.lim` is continuous at `x`, we prove by induction on `n : ℕ` that for `y` in a small neighborhood of `x` we have `|c.lim y - c.lim x| ≤ (3 / 4) ^ n`. Induction base follows from `c.lim x ∈ [0, 1]`, `c.lim y ∈ [0, 1]`. For the induction step, consider two cases: * `x ∈ c.left.U`; then for `y` in a small neighborhood of `x` we have `y ∈ c.left.U ⊆ c.right.C` (hence `c.right.lim x = c.right.lim y = 0`) and `|c.left.lim y - c.left.lim x| ≤ (3 / 4) ^ n`. Then `|c.lim y - c.lim x| = |c.left.lim y - c.left.lim x| / 2 ≤ (3 / 4) ^ n / 2 < (3 / 4) ^ (n + 1)`. * otherwise, `x ∉ c.left.right.C`; then for `y` in a small neighborhood of `x` we have `y ∉ c.left.right.C ⊇ c.left.left.U` (hence `c.left.left.lim x = c.left.left.lim y = 1`), `|c.left.right.lim y - c.left.right.lim x| ≤ (3 / 4) ^ n`, and `|c.right.lim y - c.right.lim x| ≤ (3 / 4) ^ n`. Combining these inequalities, the triangle inequality, and the recurrence formula for `c.lim`, we get `|c.lim x - c.lim y| ≤ (3 / 4) ^ (n + 1)`. The actual formalization uses `midpoint ℝ x y` instead of `(x + y) / 2` because we have more API lemmas about `midpoint`. ## Tags Urysohn's lemma, normal topological space -/ variables {X : Type*} [topological_space X] open set filter topological_space open_locale topological_space filter namespace urysohns /-- An auxiliary type for the proof of Urysohn's lemma: a pair of a closed set `C` and its open neighborhood `U`. -/ @[protect_proj] structure CU (X : Type*) [topological_space X] := (C U : set X) (closed_C : is_closed C) (open_U : is_open U) (subset : C ⊆ U) instance : inhabited (CU X) := ⟨⟨∅, univ, is_closed_empty, is_open_univ, empty_subset _⟩⟩ variable [normal_space X] namespace CU /-- Due to `normal_exists_closure_subset`, for each `c : CU X` there exists an open set `u` such chat `c.C ⊆ u` and `closure u ⊆ c.U`. `c.left` is the pair `(c.C, u)`. -/ @[simps C] def left (c : CU X) : CU X := { C := c.C, U := (normal_exists_closure_subset c.closed_C c.open_U c.subset).some, closed_C := c.closed_C, open_U := (normal_exists_closure_subset c.closed_C c.open_U c.subset).some_spec.1, subset := (normal_exists_closure_subset c.closed_C c.open_U c.subset).some_spec.2.1 } /-- Due to `normal_exists_closure_subset`, for each `c : CU X` there exists an open set `u` such chat `c.C ⊆ u` and `closure u ⊆ c.U`. `c.right` is the pair `(closure u, c.U)`. -/ @[simps U] def right (c : CU X) : CU X := { C := closure (normal_exists_closure_subset c.closed_C c.open_U c.subset).some, U := c.U, closed_C := is_closed_closure, open_U := c.open_U, subset := (normal_exists_closure_subset c.closed_C c.open_U c.subset).some_spec.2.2 } lemma left_U_subset_right_C (c : CU X) : c.left.U ⊆ c.right.C := subset_closure lemma left_U_subset (c : CU X) : c.left.U ⊆ c.U := subset.trans c.left_U_subset_right_C c.right.subset lemma subset_right_C (c : CU X) : c.C ⊆ c.right.C := subset.trans c.left.subset c.left_U_subset_right_C /-- `n`-th approximation to a continuous function `f : X → ℝ` such that `f = 0` on `c.C` and `f = 1` outside of `c.U`. -/ noncomputable def approx : ℕ → CU X → X → ℝ | 0 c x := indicator c.Uᶜ 1 x | (n + 1) c x := midpoint ℝ (approx n c.left x) (approx n c.right x) lemma approx_of_mem_C (c : CU X) (n : ℕ) {x : X} (hx : x ∈ c.C) : c.approx n x = 0 := begin induction n with n ihn generalizing c, { exact indicator_of_not_mem (λ hU, hU $ c.subset hx) _ }, { simp only [approx], rw [ihn, ihn, midpoint_self], exacts [c.subset_right_C hx, hx] } end lemma approx_of_nmem_U (c : CU X) (n : ℕ) {x : X} (hx : x ∉ c.U) : c.approx n x = 1 := begin induction n with n ihn generalizing c, { exact indicator_of_mem hx _ }, { simp only [approx], rw [ihn, ihn, midpoint_self], exacts [hx, λ hU, hx $ c.left_U_subset hU] } end lemma approx_nonneg (c : CU X) (n : ℕ) (x : X) : 0 ≤ c.approx n x := begin induction n with n ihn generalizing c, { exact indicator_nonneg (λ _ _, zero_le_one) _ }, { simp only [approx, midpoint_eq_smul_add, inv_of_eq_inv], refine mul_nonneg (inv_nonneg.2 zero_le_two) (add_nonneg _ _); apply ihn } end lemma approx_le_one (c : CU X) (n : ℕ) (x : X) : c.approx n x ≤ 1 := begin induction n with n ihn generalizing c, { exact indicator_apply_le' (λ _, le_rfl) (λ _, zero_le_one) }, { simp only [approx, midpoint_eq_smul_add, inv_of_eq_inv, smul_eq_mul, ← div_eq_inv_mul], refine iff.mpr (div_le_one zero_lt_two) (add_le_add _ _); apply ihn } end lemma bdd_above_range_approx (c : CU X) (x : X) : bdd_above (range $ λ n, c.approx n x) := ⟨1, λ y ⟨n, hn⟩, hn ▸ c.approx_le_one n x⟩ lemma approx_le_approx_of_U_sub_C {c₁ c₂ : CU X} (h : c₁.U ⊆ c₂.C) (n₁ n₂ : ℕ) (x : X) : c₂.approx n₂ x ≤ c₁.approx n₁ x := begin by_cases hx : x ∈ c₁.U, { calc approx n₂ c₂ x = 0 : approx_of_mem_C _ _ (h hx) ... ≤ approx n₁ c₁ x : approx_nonneg _ _ _ }, { calc approx n₂ c₂ x ≤ 1 : approx_le_one _ _ _ ... = approx n₁ c₁ x : (approx_of_nmem_U _ _ hx).symm } end lemma approx_mem_Icc_right_left (c : CU X) (n : ℕ) (x : X) : c.approx n x ∈ Icc (c.right.approx n x) (c.left.approx n x) := begin induction n with n ihn generalizing c, { exact ⟨le_rfl, indicator_le_indicator_of_subset (compl_subset_compl.2 c.left_U_subset) (λ _, zero_le_one) _⟩ }, { simp only [approx, mem_Icc], refine ⟨midpoint_le_midpoint _ (ihn _).1, midpoint_le_midpoint (ihn _).2 _⟩; apply approx_le_approx_of_U_sub_C, exacts [subset_closure, subset_closure] } end lemma approx_le_succ (c : CU X) (n : ℕ) (x : X) : c.approx n x ≤ c.approx (n + 1) x := begin induction n with n ihn generalizing c, { simp only [approx, right_U, right_le_midpoint], exact (approx_mem_Icc_right_left c 0 x).2 }, { rw [approx, approx], exact midpoint_le_midpoint (ihn _) (ihn _) } end lemma approx_mono (c : CU X) (x : X) : monotone (λ n, c.approx n x) := monotone_nat_of_le_succ $ λ n, c.approx_le_succ n x /-- A continuous function `f : X → ℝ` such that * `0 ≤ f x ≤ 1` for all `x`; * `f` equals zero on `c.C` and equals one outside of `c.U`; -/ protected noncomputable def lim (c : CU X) (x : X) : ℝ := ⨆ n, c.approx n x lemma tendsto_approx_at_top (c : CU X) (x : X) : tendsto (λ n, c.approx n x) at_top (𝓝 $ c.lim x) := tendsto_at_top_csupr (c.approx_mono x) ⟨1, λ x ⟨n, hn⟩, hn ▸ c.approx_le_one _ _⟩ lemma lim_of_mem_C (c : CU X) (x : X) (h : x ∈ c.C) : c.lim x = 0 := by simp only [CU.lim, approx_of_mem_C, h, csupr_const] lemma lim_of_nmem_U (c : CU X) (x : X) (h : x ∉ c.U) : c.lim x = 1 := by simp only [CU.lim, approx_of_nmem_U c _ h, csupr_const] lemma lim_eq_midpoint (c : CU X) (x : X) : c.lim x = midpoint ℝ (c.left.lim x) (c.right.lim x) := begin refine tendsto_nhds_unique (c.tendsto_approx_at_top x) ((tendsto_add_at_top_iff_nat 1).1 _), simp only [approx], exact (c.left.tendsto_approx_at_top x).midpoint (c.right.tendsto_approx_at_top x) end lemma approx_le_lim (c : CU X) (x : X) (n : ℕ) : c.approx n x ≤ c.lim x := le_csupr (c.bdd_above_range_approx x) _ lemma lim_nonneg (c : CU X) (x : X) : 0 ≤ c.lim x := (c.approx_nonneg 0 x).trans (c.approx_le_lim x 0) lemma lim_le_one (c : CU X) (x : X) : c.lim x ≤ 1 := csupr_le $ λ n, c.approx_le_one _ _ lemma lim_mem_Icc (c : CU X) (x : X) : c.lim x ∈ Icc (0 : ℝ) 1 := ⟨c.lim_nonneg x, c.lim_le_one x⟩ /-- Continuity of `urysohns.CU.lim`. See module docstring for a sketch of the proofs. -/ lemma continuous_lim (c : CU X) : continuous c.lim := begin obtain ⟨h0, h1234, h1⟩ : 0 < (2⁻¹ : ℝ) ∧ (2⁻¹ : ℝ) < 3 / 4 ∧ (3 / 4 : ℝ) < 1 := by norm_num, refine continuous_iff_continuous_at.2 (λ x, (metric.nhds_basis_closed_ball_pow (h0.trans h1234) h1).tendsto_right_iff.2 $ λ n _, _), simp only [metric.mem_closed_ball], induction n with n ihn generalizing c, { refine eventually_of_forall (λ y, _), rw pow_zero, exact real.dist_le_of_mem_Icc_01 (c.lim_mem_Icc _) (c.lim_mem_Icc _) }, { by_cases hxl : x ∈ c.left.U, { filter_upwards [is_open.mem_nhds c.left.open_U hxl, ihn c.left] with _ hyl hyd, rw [pow_succ, c.lim_eq_midpoint, c.lim_eq_midpoint, c.right.lim_of_mem_C _ (c.left_U_subset_right_C hyl), c.right.lim_of_mem_C _ (c.left_U_subset_right_C hxl)], refine (dist_midpoint_midpoint_le _ _ _ _).trans _, rw [dist_self, add_zero, div_eq_inv_mul], exact mul_le_mul h1234.le hyd dist_nonneg (h0.trans h1234).le }, { replace hxl : x ∈ c.left.right.Cᶜ, from compl_subset_compl.2 c.left.right.subset hxl, filter_upwards [is_open.mem_nhds (is_open_compl_iff.2 c.left.right.closed_C) hxl, ihn c.left.right, ihn c.right] with y hyl hydl hydr, replace hxl : x ∉ c.left.left.U, from compl_subset_compl.2 c.left.left_U_subset_right_C hxl, replace hyl : y ∉ c.left.left.U, from compl_subset_compl.2 c.left.left_U_subset_right_C hyl, simp only [pow_succ, c.lim_eq_midpoint, c.left.lim_eq_midpoint, c.left.left.lim_of_nmem_U _ hxl, c.left.left.lim_of_nmem_U _ hyl], refine (dist_midpoint_midpoint_le _ _ _ _).trans _, refine (div_le_div_of_le_of_nonneg (add_le_add_right (dist_midpoint_midpoint_le _ _ _ _) _) zero_le_two).trans _, rw [dist_self, zero_add], refine (div_le_div_of_le_of_nonneg (add_le_add (div_le_div_of_le_of_nonneg hydl zero_le_two) hydr) zero_le_two).trans_eq _, generalize : (3 / 4 : ℝ) ^ n = r, field_simp [(@zero_lt_two ℝ _ _).ne'], ring } } end end CU end urysohns variable [normal_space X] /-- Urysohns lemma: if `s` and `t` are two disjoint closed sets in a normal topological space `X`, then there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. -/ lemma exists_continuous_zero_one_of_closed {s t : set X} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) : ∃ f : C(X, ℝ), eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := begin -- The actual proof is in the code above. Here we just repack it into the expected format. set c : urysohns.CU X := ⟨s, tᶜ, hs, ht.is_open_compl, λ _, disjoint_left.1 hd⟩, exact ⟨⟨c.lim, c.continuous_lim⟩, c.lim_of_mem_C, λ x hx, c.lim_of_nmem_U _ (λ h, h hx), c.lim_mem_Icc⟩ end
04a0e7652a50d9c5c0e93d0c1ff66318e1bbf0a4
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/Cost.lean
583d5d167dab3581f21b7c2dda24e4768310ccd5
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
524
lean
-- Cost /- [Cost] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Efficient]. -/ import SystemModel.System inductive Cost (sys_type: SystemType): Prop | intro : (exists cost: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, cost c p s st) -> Cost
c1e9fb2df4c5d344a872d8e0d5940da70b9dff7f
367134ba5a65885e863bdc4507601606690974c1
/src/data/equiv/encodable/lattice.lean
144ce4e0a69290c47980137a42eec8792e8bbf0b
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
1,942
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ import data.equiv.encodable.basic import data.finset.basic import data.set.disjointed /-! # 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_decode2 [complete_lattice α] (f : β → α) : (⨆ (i : ℕ) (b ∈ decode2 β i), f b) = (⨆ b, f b) := by { rw [supr_comm], simp [mem_decode2] } lemma Union_decode2 (f : β → set α) : (⋃ (i : ℕ) (b ∈ decode2 β i), f b) = (⋃ b, f b) := supr_decode2 f @[elab_as_eliminator] lemma Union_decode2_cases {f : β → set α} {C : set α → Prop} (H0 : C ∅) (H1 : ∀ b, C (f b)) {n} : C (⋃ b ∈ decode2 β n, f b) := match decode2 β n with | none := by { simp, apply H0 } | (some b) := by { convert H1 b, simp [ext_iff] } end theorem Union_decode2_disjoint_on {f : β → set α} (hd : pairwise (disjoint on f)) : pairwise (disjoint on λ i, ⋃ b ∈ decode2 β i, f b) := begin rintro i j ij x ⟨h₁, h₂⟩, revert h₁ h₂, simp, intros b₁ e₁ h₁ b₂ e₂ h₂, refine hd _ _ _ ⟨h₁, h₂⟩, cases encodable.mem_decode2.1 e₁, cases encodable.mem_decode2.1 e₂, exact mt (congr_arg _) ij 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
a5d2b8533c04a89dd28b017b99b92afb1ede5805
1136b4d61007050cc632ede270de45a662f8dba4
/tests/lean/run/check_constants.lean
9c3a8ce7be33ae9261dabe1154f40112e413994c
[ "Apache-2.0" ]
permissive
zk744750315/lean
7fe895f16cc0ef1869238a01cae903bbd623b4a9
c17e5b913b2db687ab38f53285326b9dbb2b1b6e
refs/heads/master
1,618,208,425,413
1,521,520,544,000
1,521,520,936,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,359
lean
-- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py import smt system.io open tactic meta def script_check_id (n : name) : tactic unit := do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute") run_cmd script_check_id `absurd run_cmd script_check_id `acc.cases_on run_cmd script_check_id `acc.rec run_cmd script_check_id `add_comm_group run_cmd script_check_id `add_comm_semigroup run_cmd script_check_id `add_group run_cmd script_check_id `add_monoid run_cmd script_check_id `and run_cmd script_check_id `and.elim_left run_cmd script_check_id `and.elim_right run_cmd script_check_id `and.intro run_cmd script_check_id `and.rec run_cmd script_check_id `and.cases_on run_cmd script_check_id `auto_param run_cmd script_check_id `bit0 run_cmd script_check_id `bit1 run_cmd script_check_id `bin_tree.empty run_cmd script_check_id `bin_tree.leaf run_cmd script_check_id `bin_tree.node run_cmd script_check_id `bool run_cmd script_check_id `bool.ff run_cmd script_check_id `bool.tt run_cmd script_check_id `combinator.K run_cmd script_check_id `cast run_cmd script_check_id `cast_heq run_cmd script_check_id `char run_cmd script_check_id `char.mk run_cmd script_check_id `char.ne_of_vne run_cmd script_check_id `char.of_nat run_cmd script_check_id `char.of_nat_ne_of_ne run_cmd script_check_id `is_valid_char_range_1 run_cmd script_check_id `is_valid_char_range_2 run_cmd script_check_id `coe run_cmd script_check_id `coe_fn run_cmd script_check_id `coe_sort run_cmd script_check_id `coe_to_lift run_cmd script_check_id `congr run_cmd script_check_id `congr_arg run_cmd script_check_id `congr_fun run_cmd script_check_id `decidable run_cmd script_check_id `decidable.to_bool run_cmd script_check_id `distrib run_cmd script_check_id `dite run_cmd script_check_id `empty run_cmd script_check_id `Exists run_cmd script_check_id `eq run_cmd script_check_id `eq.cases_on run_cmd script_check_id `eq.drec run_cmd script_check_id `eq.mp run_cmd script_check_id `eq.mpr run_cmd script_check_id `eq.rec run_cmd script_check_id `eq.refl run_cmd script_check_id `eq.subst run_cmd script_check_id `eq.symm run_cmd script_check_id `eq.trans run_cmd script_check_id `eq_of_heq run_cmd script_check_id `eq_rec_heq run_cmd script_check_id `eq_true_intro run_cmd script_check_id `eq_false_intro run_cmd script_check_id `eq_self_iff_true run_cmd script_check_id `expr run_cmd script_check_id `expr.subst run_cmd script_check_id `format run_cmd script_check_id `false run_cmd script_check_id `false_of_true_iff_false run_cmd script_check_id `false_of_true_eq_false run_cmd script_check_id `true_eq_false_of_false run_cmd script_check_id `false.rec run_cmd script_check_id `field run_cmd script_check_id `fin.mk run_cmd script_check_id `fin.ne_of_vne run_cmd script_check_id `forall_congr run_cmd script_check_id `forall_congr_eq run_cmd script_check_id `forall_not_of_not_exists run_cmd script_check_id `funext run_cmd script_check_id `has_add run_cmd script_check_id `has_add.add run_cmd script_check_id `has_andthen.andthen run_cmd script_check_id `has_bind.and_then run_cmd script_check_id `has_bind.seq run_cmd script_check_id `has_div run_cmd script_check_id `has_div.div run_cmd script_check_id `has_emptyc.emptyc run_cmd script_check_id `has_mul run_cmd script_check_id `has_mul.mul run_cmd script_check_id `has_insert.insert run_cmd script_check_id `has_inv run_cmd script_check_id `has_inv.inv run_cmd script_check_id `has_le run_cmd script_check_id `has_le.le run_cmd script_check_id `has_lt run_cmd script_check_id `has_lt.lt run_cmd script_check_id `has_neg run_cmd script_check_id `has_neg.neg run_cmd script_check_id `has_one run_cmd script_check_id `has_one.one run_cmd script_check_id `has_orelse.orelse run_cmd script_check_id `has_sep.sep run_cmd script_check_id `has_sizeof run_cmd script_check_id `has_sizeof.mk run_cmd script_check_id `has_sub run_cmd script_check_id `has_sub.sub run_cmd script_check_id `has_to_format run_cmd script_check_id `has_repr run_cmd script_check_id `has_well_founded run_cmd script_check_id `has_well_founded.r run_cmd script_check_id `has_well_founded.wf run_cmd script_check_id `has_zero run_cmd script_check_id `has_zero.zero run_cmd script_check_id `has_coe_t run_cmd script_check_id `heq run_cmd script_check_id `heq.refl run_cmd script_check_id `heq.symm run_cmd script_check_id `heq.trans run_cmd script_check_id `heq_of_eq run_cmd script_check_id `hole_command run_cmd script_check_id `id run_cmd script_check_id `id_rhs run_cmd script_check_id `id_delta run_cmd script_check_id `if_neg run_cmd script_check_id `if_pos run_cmd script_check_id `iff run_cmd script_check_id `iff_false_intro run_cmd script_check_id `iff.intro run_cmd script_check_id `iff.mp run_cmd script_check_id `iff.mpr run_cmd script_check_id `iff.refl run_cmd script_check_id `iff.symm run_cmd script_check_id `iff.trans run_cmd script_check_id `iff_true_intro run_cmd script_check_id `imp_congr run_cmd script_check_id `imp_congr_eq run_cmd script_check_id `imp_congr_ctx run_cmd script_check_id `imp_congr_ctx_eq run_cmd script_check_id `implies run_cmd script_check_id `implies_of_if_neg run_cmd script_check_id `implies_of_if_pos run_cmd script_check_id `int run_cmd script_check_id `int.bit0_nonneg run_cmd script_check_id `int.bit1_nonneg run_cmd script_check_id `int.one_nonneg run_cmd script_check_id `int.zero_nonneg run_cmd script_check_id `int.bit0_pos run_cmd script_check_id `int.bit1_pos run_cmd script_check_id `int.one_pos run_cmd script_check_id `int.nat_abs_zero run_cmd script_check_id `int.nat_abs_one run_cmd script_check_id `int.nat_abs_bit0_step run_cmd script_check_id `int.nat_abs_bit1_nonneg_step run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case run_cmd script_check_id `int.ne_neg_of_ne run_cmd script_check_id `int.neg_ne_of_pos run_cmd script_check_id `int.ne_neg_of_pos run_cmd script_check_id `int.neg_ne_zero_of_ne run_cmd script_check_id `int.zero_ne_neg_of_ne run_cmd script_check_id `interactive.param_desc run_cmd script_check_id `interactive.parse run_cmd script_check_id `io_core run_cmd script_check_id `monad_io_impl run_cmd script_check_id `monad_io_terminal_impl run_cmd script_check_id `monad_io_file_system_impl run_cmd script_check_id `monad_io_environment_impl run_cmd script_check_id `monad_io_process_impl run_cmd script_check_id `monad_io_random_impl run_cmd script_check_id `io_rand_nat run_cmd script_check_id `io run_cmd script_check_id `is_associative run_cmd script_check_id `is_associative.assoc run_cmd script_check_id `is_commutative run_cmd script_check_id `is_commutative.comm run_cmd script_check_id `ite run_cmd script_check_id `lean.parser run_cmd script_check_id `lean.parser.pexpr run_cmd script_check_id `lean.parser.tk run_cmd script_check_id `left_distrib run_cmd script_check_id `left_comm run_cmd script_check_id `le_refl run_cmd script_check_id `linear_ordered_ring run_cmd script_check_id `linear_ordered_semiring run_cmd script_check_id `list run_cmd script_check_id `list.nil run_cmd script_check_id `list.cons run_cmd script_check_id `match_failed run_cmd script_check_id `monad run_cmd script_check_id `monad_fail run_cmd script_check_id `monoid run_cmd script_check_id `mul_one run_cmd script_check_id `mul_zero run_cmd script_check_id `mul_zero_class run_cmd script_check_id `name.anonymous run_cmd script_check_id `name.mk_numeral run_cmd script_check_id `name.mk_string run_cmd script_check_id `nat run_cmd script_check_id `nat.succ run_cmd script_check_id `nat.zero run_cmd script_check_id `nat.has_zero run_cmd script_check_id `nat.has_one run_cmd script_check_id `nat.has_add run_cmd script_check_id `nat.add run_cmd script_check_id `nat.cases_on run_cmd script_check_id `nat.bit0_ne run_cmd script_check_id `nat.bit0_ne_bit1 run_cmd script_check_id `nat.bit0_ne_zero run_cmd script_check_id `nat.bit0_ne_one run_cmd script_check_id `nat.bit1_ne run_cmd script_check_id `nat.bit1_ne_bit0 run_cmd script_check_id `nat.bit1_ne_zero run_cmd script_check_id `nat.bit1_ne_one run_cmd script_check_id `nat.zero_ne_one run_cmd script_check_id `nat.zero_ne_bit0 run_cmd script_check_id `nat.zero_ne_bit1 run_cmd script_check_id `nat.one_ne_zero run_cmd script_check_id `nat.one_ne_bit0 run_cmd script_check_id `nat.one_ne_bit1 run_cmd script_check_id `nat.bit0_lt run_cmd script_check_id `nat.bit1_lt run_cmd script_check_id `nat.bit0_lt_bit1 run_cmd script_check_id `nat.bit1_lt_bit0 run_cmd script_check_id `nat.zero_lt_one run_cmd script_check_id `nat.zero_lt_bit1 run_cmd script_check_id `nat.zero_lt_bit0 run_cmd script_check_id `nat.one_lt_bit0 run_cmd script_check_id `nat.one_lt_bit1 run_cmd script_check_id `nat.le_of_lt run_cmd script_check_id `nat.le_refl run_cmd script_check_id `ne run_cmd script_check_id `neq_of_not_iff run_cmd script_check_id `norm_num.add1 run_cmd script_check_id `norm_num.add1_bit0 run_cmd script_check_id `norm_num.add1_bit1_helper run_cmd script_check_id `norm_num.add1_one run_cmd script_check_id `norm_num.add1_zero run_cmd script_check_id `norm_num.add_div_helper run_cmd script_check_id `norm_num.bin_add_zero run_cmd script_check_id `norm_num.bin_zero_add run_cmd script_check_id `norm_num.bit0_add_bit0_helper run_cmd script_check_id `norm_num.bit0_add_bit1_helper run_cmd script_check_id `norm_num.bit0_add_one run_cmd script_check_id `norm_num.bit1_add_bit0_helper run_cmd script_check_id `norm_num.bit1_add_bit1_helper run_cmd script_check_id `norm_num.bit1_add_one_helper run_cmd script_check_id `norm_num.div_add_helper run_cmd script_check_id `norm_num.div_eq_div_helper run_cmd script_check_id `norm_num.div_helper run_cmd script_check_id `norm_num.div_mul_helper run_cmd script_check_id `norm_num.mk_cong run_cmd script_check_id `norm_num.mul_bit0_helper run_cmd script_check_id `norm_num.mul_bit1_helper run_cmd script_check_id `norm_num.mul_div_helper run_cmd script_check_id `norm_num.neg_add_neg_helper run_cmd script_check_id `norm_num.neg_add_pos_helper1 run_cmd script_check_id `norm_num.neg_add_pos_helper2 run_cmd script_check_id `norm_num.neg_mul_neg_helper run_cmd script_check_id `norm_num.neg_mul_pos_helper run_cmd script_check_id `norm_num.neg_neg_helper run_cmd script_check_id `norm_num.neg_zero_helper run_cmd script_check_id `norm_num.nonneg_bit0_helper run_cmd script_check_id `norm_num.nonneg_bit1_helper run_cmd script_check_id `norm_num.nonzero_of_div_helper run_cmd script_check_id `norm_num.nonzero_of_neg_helper run_cmd script_check_id `norm_num.nonzero_of_pos_helper run_cmd script_check_id `norm_num.one_add_bit0 run_cmd script_check_id `norm_num.one_add_bit1_helper run_cmd script_check_id `norm_num.one_add_one run_cmd script_check_id `norm_num.pos_add_neg_helper run_cmd script_check_id `norm_num.pos_bit0_helper run_cmd script_check_id `norm_num.pos_bit1_helper run_cmd script_check_id `norm_num.pos_mul_neg_helper run_cmd script_check_id `norm_num.sub_nat_zero_helper run_cmd script_check_id `norm_num.sub_nat_pos_helper run_cmd script_check_id `norm_num.subst_into_div run_cmd script_check_id `norm_num.subst_into_prod run_cmd script_check_id `norm_num.subst_into_subtr run_cmd script_check_id `norm_num.subst_into_sum run_cmd script_check_id `not run_cmd script_check_id `not_of_iff_false run_cmd script_check_id `not_of_eq_false run_cmd script_check_id `of_eq_true run_cmd script_check_id `of_iff_true run_cmd script_check_id `opt_param run_cmd script_check_id `or run_cmd script_check_id `out_param run_cmd script_check_id `punit run_cmd script_check_id `punit.star run_cmd script_check_id `prod.mk run_cmd script_check_id `pprod run_cmd script_check_id `pprod.mk run_cmd script_check_id `pprod.fst run_cmd script_check_id `pprod.snd run_cmd script_check_id `propext run_cmd script_check_id `to_pexpr run_cmd script_check_id `quot.mk run_cmd script_check_id `quot.lift run_cmd script_check_id `reflected run_cmd script_check_id `reflected.subst run_cmd script_check_id `repr run_cmd script_check_id `rfl run_cmd script_check_id `right_distrib run_cmd script_check_id `ring run_cmd script_check_id `scope_trace run_cmd script_check_id `set_of run_cmd script_check_id `semiring run_cmd script_check_id `psigma run_cmd script_check_id `psigma.cases_on run_cmd script_check_id `psigma.mk run_cmd script_check_id `psigma.fst run_cmd script_check_id `psigma.snd run_cmd script_check_id `singleton run_cmd script_check_id `sizeof run_cmd script_check_id `string run_cmd script_check_id `string.empty run_cmd script_check_id `string.str run_cmd script_check_id `string.empty_ne_str run_cmd script_check_id `string.str_ne_empty run_cmd script_check_id `string.str_ne_str_left run_cmd script_check_id `string.str_ne_str_right run_cmd script_check_id `subsingleton run_cmd script_check_id `subsingleton.elim run_cmd script_check_id `subsingleton.helim run_cmd script_check_id `subtype run_cmd script_check_id `subtype.mk run_cmd script_check_id `subtype.val run_cmd script_check_id `subtype.rec run_cmd script_check_id `psum run_cmd script_check_id `psum.cases_on run_cmd script_check_id `psum.inl run_cmd script_check_id `psum.inr run_cmd script_check_id `tactic run_cmd script_check_id `tactic.try run_cmd script_check_id `tactic.triv run_cmd script_check_id `tactic.mk_inj_eq run_cmd script_check_id `thunk run_cmd script_check_id `to_fmt run_cmd script_check_id `trans_rel_left run_cmd script_check_id `trans_rel_right run_cmd script_check_id `true run_cmd script_check_id `true.intro run_cmd script_check_id `unification_hint run_cmd script_check_id `unification_hint.mk run_cmd script_check_id `unit run_cmd script_check_id `unit.cases_on run_cmd script_check_id `unit.star run_cmd script_check_id `unsafe_monad_from_pure_bind run_cmd script_check_id `user_attribute run_cmd script_check_id `user_attribute.parse_reflect run_cmd script_check_id `vm_monitor run_cmd script_check_id `partial_order run_cmd script_check_id `well_founded.fix run_cmd script_check_id `well_founded.fix_eq run_cmd script_check_id `well_founded_tactics run_cmd script_check_id `well_founded_tactics.default run_cmd script_check_id `well_founded_tactics.rel_tac run_cmd script_check_id `well_founded_tactics.dec_tac run_cmd script_check_id `zero_le_one run_cmd script_check_id `zero_lt_one run_cmd script_check_id `zero_mul
848ac16cb1dad7f833d5c7b16c01bb4dc552bc17
94e33a31faa76775069b071adea97e86e218a8ee
/src/group_theory/coset.lean
63dd0d429a8e555228765a401db1c84f5fbe132c
[ "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
23,289
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import algebra.quotient import group_theory.group_action.basic import tactic.group /-! # Cosets This file develops the basic theory of left and right cosets. ## Main definitions * `left_coset a s`: the left coset `a * s` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `left_add_coset a s`. * `right_coset s a`: the right coset `s * a` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `right_add_coset s a`. * `quotient_group.quotient s`: the quotient type representing the left cosets with respect to a subgroup `s`, for an `add_group` this is `quotient_add_group.quotient s`. * `quotient_group.mk`: the canonical map from `α` to `α/s` for a subgroup `s` of `α`, for an `add_group` this is `quotient_add_group.mk`. * `subgroup.left_coset_equiv_subgroup`: the natural bijection between a left coset and the subgroup, for an `add_group` this is `add_subgroup.left_coset_equiv_add_subgroup`. ## Notation * `a *l s`: for `left_coset a s`. * `a +l s`: for `left_add_coset a s`. * `s *r a`: for `right_coset s a`. * `s +r a`: for `right_add_coset s a`. * `G ⧸ H` is the quotient of the (additive) group `G` by the (additive) subgroup `H` ## TODO Add `to_additive` to `preimage_mk_equiv_subgroup_times_set`. -/ open set function variable {α : Type*} /-- The left coset `a * s` for an element `a : α` and a subset `s : set α` -/ @[to_additive left_add_coset "The left coset `a+s` for an element `a : α` and a subset `s : set α`"] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s /-- The right coset `s * a` for an element `a : α` and a subset `s : set α` -/ @[to_additive right_add_coset "The right coset `s+a` for an element `a : α` and a subset `s : set α`"] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s localized "infix ` *l `:70 := left_coset" in coset localized "infix ` +l `:70 := left_add_coset" in coset localized "infix ` *r `:70 := right_coset" in coset localized "infix ` +r `:70 := right_add_coset" in coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS /-- Equality of two left cosets `a * s` and `b * s`. -/ @[to_additive left_add_coset_equivalence "Equality of two left cosets `a + s` and `b + s`."] def left_coset_equivalence (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equivalence_rel] lemma left_coset_equivalence_rel (s : set α) : equivalence (left_coset_equivalence s) := mk_equivalence (left_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) /-- Equality of two right cosets `s * a` and `s * b`. -/ @[to_additive right_add_coset_equivalence "Equality of two right cosets `s + a` and `s + b`."] def right_coset_equivalence (s : set α) (a b : α) := s *r a = s *r b @[to_additive right_add_coset_equivalence_rel] lemma right_coset_equivalence_rel (s : set α) : equivalence (right_coset_equivalence s) := mk_equivalence (right_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp, to_additive left_add_coset_assoc] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[simp, to_additive right_add_coset_assoc] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp, to_additive zero_left_add_coset] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] @[simp, to_additive right_add_coset_zero] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] end coset_monoid section coset_submonoid open submonoid variables [monoid α] (s : submonoid α) @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s : 1 ∈ s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a := suffices 1 * a ∈ (s : set α) *r a, by simpa, mem_right_coset a (one_mem s : 1 ∈ s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open subgroup variables [group α] (s : subgroup α) @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_left (s.inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : (s : set α) *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_right (s.inv_mem ha)] @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (N : s.normal) (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [N.mem_comm_iff] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets (h : ∀ g : α, g *l s = s *r g) : s.normal := ⟨assume a ha g, show g * a * g⁻¹ ∈ (s : set α), by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : s.normal ↔ ∀ g : α, g *l s = s *r g := ⟨@eq_cosets_of_normal _ _ s, normal_of_eq_cosets s⟩ @[to_additive left_add_coset_eq_iff] lemma left_coset_eq_iff {x y : α} : left_coset x s = left_coset y s ↔ x⁻¹ * y ∈ s := begin rw set.ext_iff, simp_rw [mem_left_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_left_inv, exact s.one_mem }, { intros h z, rw ←mul_inv_cancel_right x⁻¹ y, rw mul_assoc, exact s.mul_mem_cancel_left h }, end @[to_additive right_add_coset_eq_iff] lemma right_coset_eq_iff {x y : α} : right_coset ↑s x = right_coset s y ↔ y * x⁻¹ ∈ s := begin rw set.ext_iff, simp_rw [mem_right_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_right_inv, exact s.one_mem }, { intros h z, rw ←inv_mul_cancel_left y x⁻¹, rw ←mul_assoc, exact s.mul_mem_cancel_right h }, end end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group variables [group α] (s : subgroup α) /-- The equivalence relation corresponding to the partition of a group by left cosets of a subgroup.-/ @[to_additive "The equivalence relation corresponding to the partition of a group by left cosets of a subgroup."] def left_rel : setoid α := mul_action.orbit_rel s.opposite α variables {s} @[to_additive] lemma left_rel_apply {x y : α} : @setoid.r _ (left_rel s) x y ↔ (x⁻¹ * y ∈ s) := calc (∃ a : s.opposite, y * mul_opposite.unop a = x) ↔ ∃ a : s, y * a = x : s.opposite_equiv.symm.exists_congr_left ... ↔ ∃ a : s, x⁻¹ * y = a⁻¹ : by simp only [inv_mul_eq_iff_eq_mul, eq_mul_inv_iff_mul_eq] ... ↔ x⁻¹ * y ∈ s : by simp [set_like.exists] variables (s) @[to_additive] lemma left_rel_eq : @setoid.r _ (left_rel s) = λ x y, x⁻¹ * y ∈ s := funext₂ $ by { simp only [eq_iff_iff], apply left_rel_apply } lemma left_rel_r_eq_left_coset_equivalence : @setoid.r _ (quotient_group.left_rel s) = left_coset_equivalence s := by { ext, rw left_rel_eq, exact (left_coset_eq_iff s).symm } @[to_additive] instance left_rel_decidable [decidable_pred (∈ s)] : decidable_rel (left_rel s).r := λ x y, by { rw left_rel_eq, exact ‹decidable_pred (∈ s)› _ } /-- `α ⧸ s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `α ⧸ s` is a group -/ @[to_additive "`α ⧸ s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `α ⧸ s` is a group"] instance : has_quotient α (subgroup α) := ⟨λ s, quotient (left_rel s)⟩ /-- The equivalence relation corresponding to the partition of a group by right cosets of a subgroup. -/ @[to_additive "The equivalence relation corresponding to the partition of a group by right cosets of a subgroup."] def right_rel : setoid α := mul_action.orbit_rel s α variables {s} @[to_additive] lemma right_rel_apply {x y : α} : @setoid.r _ (right_rel s) x y ↔ (y * x⁻¹ ∈ s) := calc (∃ a : s, (a:α) * y = x) ↔ ∃ a : s, y * x⁻¹ = a⁻¹ : by simp only [mul_inv_eq_iff_eq_mul, eq_inv_mul_iff_mul_eq] ... ↔ y * x⁻¹ ∈ s : by simp [set_like.exists] variables (s) @[to_additive] lemma right_rel_eq : @setoid.r _ (right_rel s) = λ x y, y * x⁻¹ ∈ s := funext₂ $ by { simp only [eq_iff_iff], apply right_rel_apply } lemma right_rel_r_eq_right_coset_equivalence : @setoid.r _ (quotient_group.right_rel s) = right_coset_equivalence s := by { ext, rw right_rel_eq, exact (right_coset_eq_iff s).symm } @[to_additive] instance right_rel_decidable [decidable_pred (∈ s)] : decidable_rel (right_rel s).r := λ x y, by { rw right_rel_eq, exact ‹decidable_pred (∈ s)› _ } /-- Right cosets are in bijection with left cosets. -/ @[to_additive "Right cosets are in bijection with left cosets."] def quotient_right_rel_equiv_quotient_left_rel : quotient (quotient_group.right_rel s) ≃ α ⧸ s := { to_fun := quotient.map' (λ g, g⁻¹) (λ a b, by { rw [left_rel_apply, right_rel_apply], exact λ h, (congr_arg (∈ s) (by group)).mp (s.inv_mem h) }), inv_fun := quotient.map' (λ g, g⁻¹) (λ a b, by { rw [left_rel_apply, right_rel_apply], exact λ h, (congr_arg (∈ s) (by group)).mp (s.inv_mem h) }), left_inv := λ g, quotient.induction_on' g (λ g, quotient.sound' (by { simp only [inv_inv], exact quotient.exact' rfl })), right_inv := λ g, quotient.induction_on' g (λ g, quotient.sound' (by { simp only [inv_inv], exact quotient.exact' rfl })) } @[to_additive] instance fintype_quotient_right_rel [fintype (α ⧸ s)] : fintype (quotient (quotient_group.right_rel s)) := fintype.of_equiv (α ⧸ s) (quotient_group.quotient_right_rel_equiv_quotient_left_rel s).symm @[to_additive] lemma card_quotient_right_rel [fintype (α ⧸ s)] : fintype.card (quotient (quotient_group.right_rel s)) = fintype.card (α ⧸ s) := fintype.of_equiv_card (quotient_group.quotient_right_rel_equiv_quotient_left_rel s).symm end quotient_group namespace quotient_group variables [group α] {s : subgroup α} @[to_additive] instance fintype [fintype α] (s : subgroup α) [decidable_rel (left_rel s).r] : fintype (α ⧸ s) := quotient.fintype (left_rel s) /-- The canonical map from a group `α` to the quotient `α ⧸ s`. -/ @[to_additive "The canonical map from an `add_group` `α` to the quotient `α ⧸ s`."] abbreviation mk (a : α) : α ⧸ s := quotient.mk' a @[to_additive] lemma mk_surjective : function.surjective $ @mk _ _ s := quotient.surjective_quotient_mk' @[elab_as_eliminator, to_additive] lemma induction_on {C : α ⧸ s → Prop} (x : α ⧸ s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe_t α (α ⧸ s) := ⟨mk⟩ -- note [use has_coe_t] @[elab_as_eliminator, to_additive] lemma induction_on' {C : α ⧸ s → Prop} (x : α ⧸ s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[simp, to_additive] lemma quotient_lift_on_coe {β} (f : α → β) (h) (x : α) : quotient.lift_on' (x : α ⧸ s) f h = f x := rfl @[to_additive] lemma forall_coe {C : α ⧸ s → Prop} : (∀ x : α ⧸ s, C x) ↔ ∀ x : α, C x := ⟨λ hx x, hx _, quot.ind⟩ @[to_additive] instance (s : subgroup α) : inhabited (α ⧸ s) := ⟨((1 : α) : α ⧸ s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : α ⧸ s) = b ↔ a⁻¹ * b ∈ s := calc _ ↔ @setoid.r _ (left_rel s) a b : quotient.eq' ... ↔ _ : by rw left_rel_apply @[to_additive quotient_add_group.eq'] lemma eq' {a b : α} : (mk a : α ⧸ s) = mk b ↔ a⁻¹ * b ∈ s := quotient_group.eq @[to_additive quotient_add_group.out_eq'] lemma out_eq' (a : α ⧸ s) : mk a.out' = a := quotient.out_eq' a variables (s) /- It can be useful to write `obtain ⟨h, H⟩ := mk_out'_eq_mul ...`, and then `rw [H]` or `simp_rw [H]` or `simp only [H]`. In order for `simp_rw` and `simp only` to work, this lemma is stated in terms of an arbitrary `h : s`, rathern that the specific `h = g⁻¹ * (mk g).out'`. -/ @[to_additive quotient_add_group.mk_out'_eq_mul] lemma mk_out'_eq_mul (g : α) : ∃ h : s, (mk g : α ⧸ s).out' = g * h := ⟨⟨g⁻¹ * (mk g).out', eq'.mp (mk g).out_eq'.symm⟩, by rw [set_like.coe_mk, mul_inv_cancel_left]⟩ variables {s} @[to_additive quotient_add_group.mk_mul_of_mem] lemma mk_mul_of_mem (g₁ g₂ : α) (hg₂ : g₂ ∈ s) : (mk (g₁ * g₂) : α ⧸ s) = mk g₁ := by rwa [eq', mul_inv_rev, inv_mul_cancel_right, s.inv_mem_iff] @[to_additive] lemma eq_class_eq_left_coset (s : subgroup α) (g : α) : {x : α | (x : α ⧸ s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq, set_like.mem_coe] @[to_additive] lemma preimage_image_coe (N : subgroup α) (s : set α) : coe ⁻¹' ((coe : α → α ⧸ N) '' s) = ⋃ x : N, (λ y : α, y * x) ⁻¹' s := begin ext x, simp only [quotient_group.eq, set_like.exists, exists_prop, set.mem_preimage, set.mem_Union, set.mem_image, set_like.coe_mk, ← eq_inv_mul_iff_mul_eq], exact ⟨λ ⟨y, hs, hN⟩, ⟨_, N.inv_mem hN, by simpa using hs⟩, λ ⟨z, hz, hxz⟩, ⟨x*z, hxz, by simpa using hz⟩⟩, end end quotient_group namespace subgroup open quotient_group variables [group α] {s : subgroup α} /-- The natural bijection between a left coset `g * s` and `s`. -/ @[to_additive "The natural bijection between the cosets `g + s` and `s`."] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- The natural bijection between a right coset `s * g` and `s`. -/ @[to_additive "The natural bijection between the cosets `s + g` and `s`."] def right_coset_equiv_subgroup (g : α) : right_coset ↑s g ≃ s := ⟨λ x, ⟨x.1 * g⁻¹, (mem_right_coset_iff _).1 x.2⟩, λ x, ⟨x.1 * g, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- A (non-canonical) bijection between a group `α` and the product `(α/s) × s` -/ @[to_additive "A (non-canonical) bijection between an add_group `α` and the product `(α/s) × s`"] noncomputable def group_equiv_quotient_times_subgroup : α ≃ (α ⧸ s) × s := calc α ≃ Σ L : α ⧸ s, {x : α // (x : α ⧸ s) = L} : (equiv.sigma_fiber_equiv quotient_group.mk).symm ... ≃ Σ L : α ⧸ s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show _root_.subtype (λ x : α, quotient.mk' x = L) ≃ _root_.subtype (λ x : α, quotient.mk' x = quotient.mk' _), simp [-quotient.eq'], end) ... ≃ Σ L : α ⧸ s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ (α ⧸ s) × s : equiv.sigma_equiv_prod _ _ variables {t : subgroup α} /-- If `H ≤ K`, then `G/H ≃ G/K × K/H` constructively, using the provided right inverse of the quotient map `G → G/K`. The classical version is `quotient_equiv_prod_of_le`. -/ @[to_additive "If `H ≤ K`, then `G/H ≃ G/K × K/H` constructively, using the provided right inverse of the quotient map `G → G/K`. The classical version is `quotient_equiv_prod_of_le`.", simps] def quotient_equiv_prod_of_le' (h_le : s ≤ t) (f : α ⧸ t → α) (hf : function.right_inverse f quotient_group.mk) : α ⧸ s ≃ (α ⧸ t) × (t ⧸ s.subgroup_of t) := { to_fun := λ a, ⟨a.map' id (λ b c h, left_rel_apply.mpr (h_le (left_rel_apply.mp h))), a.map' (λ g : α, ⟨(f (quotient.mk' g))⁻¹ * g, left_rel_apply.mp (quotient.exact' (hf g))⟩) (λ b c h, by { rw left_rel_apply, change ((f b)⁻¹ * b)⁻¹ * ((f c)⁻¹ * c) ∈ s, have key : f b = f c := congr_arg f (quotient.sound' (left_rel_apply.mpr (h_le (left_rel_apply.mp h)))), rwa [key, mul_inv_rev, inv_inv, mul_assoc, mul_inv_cancel_left, ← left_rel_apply] })⟩, inv_fun := λ a, a.2.map' (λ b, f a.1 * b) (λ b c h, by { rw left_rel_apply at ⊢ h, change (f a.1 * b)⁻¹ * (f a.1 * c) ∈ s, rwa [mul_inv_rev, mul_assoc, inv_mul_cancel_left] }), left_inv := by { refine quotient.ind' (λ a, _), simp_rw [quotient.map'_mk', id.def, set_like.coe_mk, mul_inv_cancel_left] }, right_inv := by { refine prod.rec _, refine quotient.ind' (λ a, _), refine quotient.ind' (λ b, _), have key : quotient.mk' (f (quotient.mk' a) * b) = quotient.mk' a := (quotient_group.mk_mul_of_mem (f a) ↑b b.2).trans (hf a), simp_rw [quotient.map'_mk', id.def, key, inv_mul_cancel_left, subtype.coe_eta] } } /-- If `H ≤ K`, then `G/H ≃ G/K × K/H` nonconstructively. The constructive version is `quotient_equiv_prod_of_le'`. -/ @[to_additive "If `H ≤ K`, then `G/H ≃ G/K × K/H` nonconstructively. The constructive version is `quotient_equiv_prod_of_le'`.", simps] noncomputable def quotient_equiv_prod_of_le (h_le : s ≤ t) : α ⧸ s ≃ (α ⧸ t) × (t ⧸ s.subgroup_of t) := quotient_equiv_prod_of_le' h_le quotient.out' quotient.out_eq' /-- If `K ≤ L`, then there is an embedding `K ⧸ (H.subgroup_of K) ↪ L ⧸ (H.subgroup_of L)`. -/ @[to_additive "If `K ≤ L`, then there is an embedding `K ⧸ (H.add_subgroup_of K) ↪ L ⧸ (H.add_subgroup_of L)`."] def quotient_subgroup_of_embedding_of_le (H : subgroup α) {K L : subgroup α} (h : K ≤ L) : K ⧸ (H.subgroup_of K) ↪ L ⧸ (H.subgroup_of L) := { to_fun := quotient.map' (set.inclusion h) (λ a b, by { simp [left_rel_apply], exact id }), inj' := begin refine quotient.ind₂' (λ a b, _), refine λ h, (quotient.eq'.mpr ∘ left_rel_apply.mpr) _, have := left_rel_apply.mp (quotient.eq'.mp h), exact this, end } @[to_additive] lemma card_eq_card_quotient_mul_card_subgroup [fintype α] (s : subgroup α) [fintype s] [decidable_pred (λ a, a ∈ s)] : fintype.card α = fintype.card (α ⧸ s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (subgroup.group_equiv_quotient_times_subgroup) /-- **Lagrange's Theorem**: The order of a subgroup divides the order of its ambient group. -/ @[to_additive] lemma card_subgroup_dvd_card [fintype α] (s : subgroup α) [fintype s] : fintype.card s ∣ fintype.card α := by classical; simp [card_eq_card_quotient_mul_card_subgroup s, @dvd_mul_left ℕ] @[to_additive] lemma card_quotient_dvd_card [fintype α] (s : subgroup α) [decidable_pred (λ a, a ∈ s)] [fintype s] : fintype.card (α ⧸ s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s, @dvd_mul_right ℕ] open fintype variables {H : Type*} [group H] @[to_additive] lemma card_dvd_of_injective [fintype α] [fintype H] (f : α →* H) (hf : function.injective f) : card α ∣ card H := by classical; calc card α = card (f.range : subgroup H) : card_congr (equiv.of_injective f hf) ...∣ card H : card_subgroup_dvd_card _ @[to_additive] lemma card_dvd_of_le {H K : subgroup α} [fintype H] [fintype K] (hHK : H ≤ K) : card H ∣ card K := card_dvd_of_injective (inclusion hHK) (inclusion_injective hHK) @[to_additive] lemma card_comap_dvd_of_injective (K : subgroup H) [fintype K] (f : α →* H) [fintype (K.comap f)] (hf : function.injective f) : fintype.card (K.comap f) ∣ fintype.card K := by haveI : fintype ((K.comap f).map f) := fintype.of_equiv _ (equiv_map_of_injective _ _ hf).to_equiv; calc fintype.card (K.comap f) = fintype.card ((K.comap f).map f) : fintype.card_congr (equiv_map_of_injective _ _ hf).to_equiv ... ∣ fintype.card K : card_dvd_of_le (map_comap_le _ _) end subgroup namespace quotient_group variables [group α] -- FIXME -- why is there no `to_additive`? /-- If `s` is a subgroup of the group `α`, and `t` is a subset of `α/s`, then there is a (typically non-canonical) bijection between the preimage of `t` in `α` and the product `s × t`. -/ noncomputable def preimage_mk_equiv_subgroup_times_set (s : subgroup α) (t : set (α ⧸ s)) : quotient_group.mk ⁻¹' t ≃ s × t := have h : ∀ {x : α ⧸ s} {a : α}, x ∈ t → a ∈ s → (quotient.mk' (quotient.out' x * a) : α ⧸ s) = quotient.mk' (quotient.out' x) := λ x a hx ha, quotient.sound' $ by rwa [left_rel_apply, ← s.inv_mem_iff, mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul], { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a, left_rel_apply.mp (@quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _))⟩, ⟨quotient.mk' a, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t, by simp [h hx ha, hx]⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] } end quotient_group /-- We use the class `has_coe_t` instead of `has_coe` if the first argument is a variable, or if the second argument is a variable not occurring in the first. Using `has_coe` would cause looping of type-class inference. See <https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain> -/ library_note "use has_coe_t"
c4970275cf1e9efc3095831c3f824634f0ba7a67
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/nat/prime.lean
57775b325ca8a66dcb3500e20c8c05d2b66c819c
[ "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
26,916
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, Mario Carneiro -/ import algebra.associated import algebra.parity import data.int.dvd.basic import data.int.units import data.nat.factorial.basic import data.nat.gcd.basic import data.nat.sqrt import order.bounds.basic import tactic.by_contra /-! # Prime numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. ## Important declarations - `nat.prime`: the predicate that expresses that a natural number `p` is prime - `nat.primes`: the subtype of natural numbers that are prime - `nat.min_fac n`: the minimal prime factor of a natural number `n ≠ 1` - `nat.exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers. This also appears as `nat.not_bdd_above_set_of_prime` and `nat.infinite_set_of_prime` (the latter in `data.nat.prime_fin`). - `nat.prime_iff`: `nat.prime` coincides with the general definition of `prime` - `nat.irreducible_iff_prime`: a non-unit natural number is only divisible by `1` iff it is prime -/ open bool subtype open_locale nat namespace nat /-- `nat.prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ @[pp_nodot] def prime (p : ℕ) := _root_.irreducible p theorem _root_.irreducible_iff_nat_prime (a : ℕ) : irreducible a ↔ nat.prime a := iff.rfl theorem not_prime_zero : ¬ prime 0 | h := h.ne_zero rfl theorem not_prime_one : ¬ prime 1 | h := h.ne_one rfl theorem prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := irreducible.ne_zero h theorem prime.pos {p : ℕ} (pp : prime p) : 0 < p := nat.pos_of_ne_zero pp.ne_zero theorem prime.two_le : ∀ {p : ℕ}, prime p → 2 ≤ p | 0 h := (not_prime_zero h).elim | 1 h := (not_prime_one h).elim | (n+2) _ := le_add_self theorem prime.one_lt {p : ℕ} : prime p → 1 < p := prime.two_le instance prime.one_lt' (p : ℕ) [hp : _root_.fact p.prime] : _root_.fact (1 < p) := ⟨hp.1.one_lt⟩ lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 := hp.one_lt.ne' lemma prime.eq_one_or_self_of_dvd {p : ℕ} (pp : p.prime) (m : ℕ) (hm : m ∣ p) : m = 1 ∨ m = p := begin obtain ⟨n, hn⟩ := hm, have := pp.is_unit_or_is_unit hn, rw [nat.is_unit_iff, nat.is_unit_iff] at this, apply or.imp_right _ this, rintro rfl, rw [hn, mul_one] end theorem prime_def_lt'' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m ∣ p, m = 1 ∨ m = p := begin refine ⟨λ h, ⟨h.two_le, h.eq_one_or_self_of_dvd⟩, λ h, _⟩, have h1 := one_lt_two.trans_le h.1, refine ⟨mt nat.is_unit_iff.mp h1.ne', λ a b hab, _⟩, simp only [nat.is_unit_iff], apply or.imp_right _ (h.2 a _), { rintro rfl, rw [← mul_right_inj' (pos_of_gt h1).ne', ←hab, mul_one] }, { rw hab, exact dvd_mul_right _ _ } end theorem prime_def_lt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m < p, m ∣ p → m = 1 := prime_def_lt''.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (le_of_dvd (le_of_succ_le p2) d).lt_or_eq_dec.imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ nat.mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ theorem prime_of_coprime (n : ℕ) (h1 : 1 < n) (h : ∀ m < n, m ≠ 0 → n.coprime m) : prime n := begin refine prime_def_lt.mpr ⟨h1, λ m mlt mdvd, _⟩, have hm : m ≠ 0, { rintro rfl, rw zero_dvd_iff at mdvd, exact mlt.ne' mdvd }, exact (h m mlt hm).symm.eq_one_of_dvd mdvd, end section /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works in the kernel for small values. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ local attribute [instance] def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial lemma prime.five_le_of_ne_two_of_ne_three {p : ℕ} (hp : p.prime) (h_two : p ≠ 2) (h_three : p ≠ 3) : 5 ≤ p := begin by_contra' h, revert h_two h_three hp, dec_trivial! end end theorem prime.pred_pos {p : ℕ} (pp : prime p) : 0 < pred p := lt_pred_iff.2 pp.one_lt theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.eq_one_or_self_of_dvd m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_rfl)⟩ theorem dvd_prime_two_le {p m : ℕ} (pp : prime p) (H : 2 ≤ m) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime_dvd_prime_iff_eq {p q : ℕ} (pp : p.prime) (qp : q.prime) : p ∣ q ↔ p = q := dvd_prime_two_le qp (prime.two_le pp) theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 := pp.not_dvd_one theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_two_le h a1).1 (dvd_mul_right _ _) lemma not_prime_mul' {a b n : ℕ} (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ prime n := by { rw ← h, exact not_prime_mul h₁ h₂ } lemma prime_mul_iff {a b : ℕ} : nat.prime (a * b) ↔ (a.prime ∧ b = 1) ∨ (b.prime ∧ a = 1) := by simp only [iff_self, irreducible_mul_iff, ←irreducible_iff_nat_prime, nat.is_unit_iff] lemma prime.dvd_iff_eq {p a : ℕ} (hp : p.prime) (a1 : a ≠ 1) : a ∣ p ↔ p = a := begin refine ⟨_, by { rintro rfl, refl }⟩, -- rintro ⟨j, rfl⟩ does not work, due to `nat.prime` depending on the class `irreducible` rintro ⟨j, hj⟩, rw hj at hp ⊢, rcases prime_mul_iff.mp hp with ⟨h, rfl⟩ | ⟨h, rfl⟩, { exact mul_one _ }, { exact (a1 rfl).elim } end section min_fac lemma min_fac_lemma (n k : ℕ) (h : ¬ n < k * k) : sqrt n - k < sqrt n + 2 - k := (tsub_lt_tsub_iff_right $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial /-- If `n < k * k`, then `min_fac_aux n k = n`, if `k | n`, then `min_fac_aux n k = k`. Otherwise, `min_fac_aux n k = min_fac_aux n (k+2)` using well-founded recursion. If `n` is odd and `1 < n`, then then `min_fac_aux n 3` is the smallest prime factor of `n`. -/ def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := by simp | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := 2 ≤ k ∧ k ∣ n ∧ ∀ m, 2 ≤ m → m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : 2 ≤ n) : ∀ k i, k = 2*i+3 → (∀ m, 2 ≤ m → m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_rfl, λ m m2 d, le_of_eq ((dvd_prime_two_le pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := a _ le_rfl (dvd_of_mul_right_dvd d), rw e at this, exact absurd this dec_trivial } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_rfl, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := if n1 : n = 1 then by simp [n1] else (min_fac_has_prop n1).2.1 theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (d.trans fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, 2 ≤ m → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : 0 < min_fac n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : 0 < n) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem le_min_fac {m n : ℕ} : n = 1 ∨ m ≤ min_fac n ↔ ∀ p, prime p → p ∣ n → m ≤ p := ⟨λ h p pp d, h.elim (by rintro rfl; cases pp.not_dvd_one d) (λ h, le_trans h $ min_fac_le_of_dvd pp.two_le d), λ H, or_iff_not_imp_left.2 $ λ n1, H _ (min_fac_prime n1) (min_fac_dvd _)⟩ theorem le_min_fac' {m n : ℕ} : n = 1 ∨ m ≤ min_fac n ↔ ∀ p, 2 ≤ p → p ∣ n → m ≤ p := ⟨λ h p (pp:1<p) d, h.elim (by rintro rfl; cases not_le_of_lt pp (le_of_dvd dec_trivial d)) (λ h, le_trans h $ min_fac_le_of_dvd pp d), λ H, le_min_fac.2 (λ p pp d, H p pp.two_le d)⟩ theorem prime_def_min_fac {p : ℕ} : prime p ↔ 2 ≤ p ∧ min_fac p = p := ⟨λ pp, ⟨pp.two_le, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.one_lt in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ @[simp] lemma prime.min_fac_eq {p : ℕ} (hp : prime p) : min_fac p = p := (prime_def_min_fac.1 hp).2 /-- This instance is faster in the virtual machine than `decidable_prime_1`, but slower in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : 2 ≤ n) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm lemma min_fac_le_div {n : ℕ} (pos : 0 < n) (np : ¬ prime n) : min_fac n ≤ n / min_fac n := match min_fac_dvd n with | ⟨0, h0⟩ := absurd pos $ by rw [h0, mul_zero]; exact dec_trivial | ⟨1, h1⟩ := begin rw mul_one at h1, rw [prime_def_min_fac, not_and_distrib, ← h1, eq_self_iff_true, not_true, or_false, not_le] at np, rw [le_antisymm (le_of_lt_succ np) (succ_le_of_lt pos), min_fac_one, nat.div_one] end | ⟨(x+2), hx⟩ := begin conv_rhs { congr, rw hx }, rw [nat.mul_div_cancel_left _ (min_fac_pos _)], exact min_fac_le_of_dvd dec_trivial ⟨min_fac n, by rwa mul_comm⟩ end end /-- The square of the smallest prime factor of a composite number `n` is at most `n`. -/ lemma min_fac_sq_le_self {n : ℕ} (w : 0 < n) (h : ¬ prime n) : (min_fac n)^2 ≤ n := have t : (min_fac n) ≤ (n/min_fac n) := min_fac_le_div w h, calc (min_fac n)^2 = (min_fac n) * (min_fac n) : sq (min_fac n) ... ≤ (n/min_fac n) * (min_fac n) : nat.mul_le_mul_right (min_fac n) t ... ≤ n : div_mul_le_self n (min_fac n) @[simp] lemma min_fac_eq_one_iff {n : ℕ} : min_fac n = 1 ↔ n = 1 := begin split, { intro h, by_contradiction hn, have := min_fac_prime hn, rw h at this, exact not_prime_one this, }, { rintro rfl, refl, } end @[simp] lemma min_fac_eq_two_iff (n : ℕ) : min_fac n = 2 ↔ 2 ∣ n := begin split, { intro h, convert min_fac_dvd _, rw h, }, { intro h, have ub := min_fac_le_of_dvd (le_refl 2) h, have lb := min_fac_pos n, apply ub.eq_or_lt.resolve_right (λ h', _), have := le_antisymm (nat.succ_le_of_lt lb) (lt_succ_iff.mp h'), rw [eq_comm, nat.min_fac_eq_one_iff] at this, subst this, exact not_lt_of_le (le_of_dvd zero_lt_one h) one_lt_two } end end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).one_lt, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).two_le, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (hn : n ≠ 1) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime hn, min_fac_dvd _⟩ theorem dvd_of_forall_prime_mul_dvd {a b : ℕ} (hdvd : ∀ p : ℕ, p.prime → p ∣ a → p * a ∣ b) : a ∣ b := begin obtain rfl | ha := eq_or_ne a 1, { apply one_dvd }, obtain ⟨p, hp⟩ := exists_prime_and_dvd ha, exact trans (dvd_mul_left a p) (hdvd p hp.1 hp.2), end /-- Euclid's theorem on the **infinitude of primes**. Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/ theorem exists_infinite_primes (n : ℕ) : ∃ p, n ≤ p ∧ prime p := let p := min_fac (n! + 1) in have f1 : n! + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ factorial_pos _, have pp : prime p, from min_fac_prime f1, have np : n ≤ p, from le_of_not_ge $ λ h, have h₁ : p ∣ n!, from dvd_factorial (min_fac_pos _) h, have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _), pp.not_dvd_one h₂, ⟨p, np, pp⟩ /-- A version of `nat.exists_infinite_primes` using the `bdd_above` predicate. -/ lemma not_bdd_above_set_of_prime : ¬ bdd_above {p | prime p} := begin rw not_bdd_above_iff, intro n, obtain ⟨p, hi, hp⟩ := exists_infinite_primes n.succ, exact ⟨p, hp, hi⟩, end lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := p.mod_two_eq_zero_or_one.imp_left (λ h, ((hp.eq_one_or_self_of_dvd 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm) lemma prime.eq_two_or_odd' {p : ℕ} (hp : prime p) : p = 2 ∨ odd p := or.imp_right (λ h, ⟨p / 2, (div_add_mod p 2).symm.trans (congr_arg _ h)⟩) hp.eq_two_or_odd lemma prime.even_iff {p : ℕ} (hp : prime p) : even p ↔ p = 2 := by rw [even_iff_two_dvd, prime_dvd_prime_iff_eq prime_two hp, eq_comm] lemma prime.odd_of_ne_two {p : ℕ} (hp : p.prime) (h_two : p ≠ 2) : odd p := hp.eq_two_or_odd'.resolve_left h_two /-- A prime `p` satisfies `p % 2 = 1` if and only if `p ≠ 2`. -/ lemma prime.mod_two_eq_one_iff_ne_two {p : ℕ} [fact p.prime] : p % 2 = 1 ↔ p ≠ 2 := begin refine ⟨λ h hf, _, (nat.prime.eq_two_or_odd $ fact.out p.prime).resolve_left⟩, rw hf at h, simpa using h, end theorem coprime_of_dvd {m n : ℕ} (H : ∀ k, prime k → k ∣ m → ¬ k ∣ n) : coprime m n := begin rw [coprime_iff_gcd_eq_one], by_contra g2, obtain ⟨p, hp, hpdvd⟩ := exists_prime_and_dvd g2, apply H p hp; apply dvd_trans hpdvd, { exact gcd_dvd_left _ _ }, { exact gcd_dvd_right _ _ } end theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, prime k → k ∣ m → k ∣ n → k ∣ 1) : coprime m n := coprime_of_dvd $ λk kp km kn, not_le_of_gt kp.one_lt $ le_of_dvd zero_lt_one $ H k kp km kn theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).one_lt theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((prime_dvd_prime_iff_eq m2 pp).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.not_coprime_iff_dvd {m n : ℕ} : ¬ coprime m n ↔ ∃p, prime p ∧ p ∣ m ∧ p ∣ n := begin apply iff.intro, { intro h, exact ⟨min_fac (gcd m n), min_fac_prime h, ((min_fac_dvd (gcd m n)).trans (gcd_dvd_left m n)), ((min_fac_dvd (gcd m n)).trans (gcd_dvd_right m n))⟩ }, { intro h, cases h with p hp, apply nat.not_coprime_of_dvd_of_dvd (prime.one_lt hp.1) hp.2.1 hp.2.2 } end theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h : p ∣ m, h.mul_right _) (λ h : p ∣ n, h.mul_left _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime_iff {p : ℕ} : p.prime ↔ _root_.prime p := ⟨λ h, ⟨h.ne_zero, h.not_unit, λ a b, h.dvd_mul.mp⟩, prime.irreducible⟩ alias prime_iff ↔ prime.prime _root_.prime.nat_prime attribute [protected, nolint dup_namespace] prime.prime theorem irreducible_iff_prime {p : ℕ} : irreducible p ↔ _root_.prime p := prime_iff theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := begin induction n with n IH, { exact pp.not_dvd_one.elim h }, { rw pow_succ at h, exact (pp.dvd_mul.1 h).elim id IH } end lemma prime.pow_not_prime {x n : ℕ} (hn : 2 ≤ n) : ¬ (x ^ n).prime := λ hp, (hp.eq_one_or_self_of_dvd x $ dvd_trans ⟨x, sq _⟩ (pow_dvd_pow _ hn)).elim (λ hx1, hp.ne_one $ hx1.symm ▸ one_pow _) (λ hxn, lt_irrefl x $ calc x = x ^ 1 : (pow_one _).symm ... < x ^ n : nat.pow_right_strict_mono (hxn.symm ▸ hp.two_le) hn ... = x : hxn.symm) lemma prime.pow_not_prime' {x : ℕ} : ∀ {n : ℕ}, n ≠ 1 → ¬ (x ^ n).prime | 0 := λ _, not_prime_one | 1 := λ h, (h rfl).elim | (n+2) := λ _, prime.pow_not_prime le_add_self lemma prime.eq_one_of_pow {x n : ℕ} (h : (x ^ n).prime) : n = 1 := not_imp_not.mp prime.pow_not_prime' h lemma prime.pow_eq_iff {p a k : ℕ} (hp : p.prime) : a ^ k = p ↔ a = p ∧ k = 1 := begin refine ⟨λ h, _, λ h, by rw [h.1, h.2, pow_one]⟩, rw ←h at hp, rw [←h, hp.eq_one_of_pow, eq_self_iff_true, and_true, pow_one], end lemma pow_min_fac {n k : ℕ} (hk : k ≠ 0) : (n^k).min_fac = n.min_fac := begin rcases eq_or_ne n 1 with rfl | hn, { simp }, have hnk : n ^ k ≠ 1 := λ hk', hn ((pow_eq_one_iff hk).1 hk'), apply (min_fac_le_of_dvd (min_fac_prime hn).two_le ((min_fac_dvd n).pow hk)).antisymm, apply min_fac_le_of_dvd (min_fac_prime hnk).two_le ((min_fac_prime hnk).dvd_of_dvd_pow (min_fac_dvd _)), end lemma prime.pow_min_fac {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) : (p^k).min_fac = p := by rw [pow_min_fac hk, hp.min_fac_eq] lemma prime.mul_eq_prime_sq_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ 2 ↔ x = p ∧ y = p := ⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [sq], begin -- Could be `wlog := hp.dvd_mul.1 pdvdxy using x y`, but that imports more than we want. suffices : ∀ (x' y' : ℕ), x' ≠ 1 → y' ≠ 1 → x' * y' = p ^ 2 → p ∣ x' → x' = p ∧ y' = p, { obtain hx|hy := hp.dvd_mul.1 pdvdxy; [skip, rw and_comm]; [skip, rw mul_comm at h pdvdxy]; apply this; assumption }, clear_dependent x y, rintros x y hx hy h ⟨a, ha⟩, have hap : a ∣ p, from ⟨y, by rwa [ha, sq, mul_assoc, mul_right_inj' hp.ne_zero, eq_comm] at h⟩, exact ((nat.dvd_prime hp).1 hap).elim (λ _, by clear_aux_decl; simp [*, sq, mul_right_inj' hp.ne_zero] at * {contextual := tt}) (λ _, by clear_aux_decl; simp [*, sq, mul_comm, mul_assoc, mul_right_inj' hp.ne_zero, nat.mul_right_eq_self_iff hp.pos] at * {contextual := tt}) end, λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (sq _).symm⟩ lemma prime.dvd_factorial : ∀ {n p : ℕ} (hp : prime p), p ∣ n! ↔ p ≤ n | 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos) | (n+1) p hp := begin rw [factorial_succ, hp.dvd_mul, prime.dvd_factorial hp], exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ) (λ h, or.inl $ by rw h)⟩ end theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_two_le pq pp.two_le theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em lemma coprime_of_lt_prime {n p} (n_pos : 0 < n) (hlt : n < p) (pp : prime p) : coprime p n := (coprime_or_dvd_of_prime pp n).resolve_right $ λ h, lt_le_antisymm hlt (le_of_dvd n_pos h) lemma eq_or_coprime_of_le_prime {n p} (n_pos : 0 < n) (hle : n ≤ p) (pp : prime p) : p = n ∨ coprime p n := hle.eq_or_lt.imp eq.symm (λ h, coprime_of_lt_prime n_pos h pp) theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := by simp_rw [dvd_prime_pow (prime_iff.mp pp) m, associated_eq_eq] lemma prime.dvd_mul_of_dvd_ne {p1 p2 n : ℕ} (h_neq : p1 ≠ p2) (pp1 : prime p1) (pp2 : prime p2) (h1 : p1 ∣ n) (h2 : p2 ∣ n) : (p1 * p2 ∣ n) := coprime.mul_dvd_of_dvd_of_dvd ((coprime_primes pp1 pp2).mpr h_neq) h1 h2 /-- If `p` is prime, and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)` then `a = p^(k+1)`. -/ lemma eq_prime_pow_of_dvd_least_prime_pow {a p k : ℕ} (pp : prime p) (h₁ : ¬(a ∣ p^k)) (h₂ : a ∣ p^(k+1)) : a = p^(k+1) := begin obtain ⟨l, ⟨h, rfl⟩⟩ := (dvd_prime_pow pp).1 h₂, congr, exact le_antisymm h (not_le.1 ((not_congr (pow_dvd_pow_iff_le_right (prime.one_lt pp))).1 h₁)), end lemma ne_one_iff_exists_prime_dvd : ∀ {n}, n ≠ 1 ↔ ∃ p : ℕ, p.prime ∧ p ∣ n | 0 := by simpa using (Exists.intro 2 nat.prime_two) | 1 := by simp [nat.not_prime_one] | (n+2) := let a := n+2 in let ha : a ≠ 1 := nat.succ_succ_ne_one n in begin simp only [true_iff, ne.def, not_false_iff, ha], exact ⟨a.min_fac, nat.min_fac_prime ha, a.min_fac_dvd⟩, end lemma eq_one_iff_not_exists_prime_dvd {n : ℕ} : n = 1 ↔ ∀ p : ℕ, p.prime → ¬p ∣ n := by simpa using not_iff_not.mpr ne_one_iff_exists_prime_dvd lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) : p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n := have hpd : p^(k+l)*p ∣ m*n, by rwa pow_succ' at hpmn, have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd, have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [pow_add] using hpd2, have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div_comm hpm hpn] using hpd3, have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4, suffices p^k*p ∣ m ∨ p^l*p ∣ n, by rwa [pow_succ', pow_succ'], hpd5.elim (assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this) (assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this) lemma prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt int.is_unit_iff_nat_abs_eq.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ /-- The type of prime numbers -/ def primes := {p : ℕ // p.prime} namespace primes instance : has_repr nat.primes := ⟨λ p, repr p.val⟩ instance inhabited_primes : inhabited primes := ⟨⟨2, prime_two⟩⟩ instance coe_nat : has_coe nat.primes ℕ := ⟨subtype.val⟩ theorem coe_nat_injective : function.injective (coe : nat.primes → ℕ) := subtype.coe_injective theorem coe_nat_inj (p q : nat.primes) : (p : ℕ) = (q : ℕ) ↔ p = q := subtype.ext_iff.symm end primes instance monoid.prime_pow {α : Type*} [monoid α] : has_pow α primes := ⟨λ x p, x^(p : ℕ)⟩ end nat namespace nat instance fact_prime_two : fact (prime 2) := ⟨prime_two⟩ instance fact_prime_three : fact (prime 3) := ⟨prime_three⟩ end nat namespace int lemma prime_two : prime (2 : ℤ) := nat.prime_iff_prime_int.mp nat.prime_two lemma prime_three : prime (3 : ℤ) := nat.prime_iff_prime_int.mp nat.prime_three end int assert_not_exists multiset
362b65343bcdc6a1d7944c626478fdd89bec4d69
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/analysis/measure_theory/integration.lean
9b3e1a0dc5c14afb2487c599b3b39b2aadce5d49
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
29,136
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl Lebesgue integral on `ennreal`. We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. -/ import algebra.pi_instances analysis.measure_theory.measure_space analysis.measure_theory.borel_space noncomputable theory open lattice set filter local attribute [instance] classical.prop_decidable lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : monotone f) (h : tendsto f at_top (nhds a)) : supr f = a := le_antisymm (supr_le $ assume i, le_of_not_gt $ assume hi, have {n | i ≤ n} ∈ (at_top : filter ℕ).sets, from mem_at_top _, let ⟨n, h₁, h₂⟩ := inhabited_of_mem_sets at_top_ne_bot (inter_mem_sets this ((tendsto_orderable.1 h).2 _ hi)) in not_lt_of_ge (hf h₁) h₂) (le_of_not_gt $ assume ha, let ⟨n, hn⟩ := inhabited_of_mem_sets at_top_ne_bot ((tendsto_orderable.1 h).1 _ ha) in not_lt_of_ge (le_supr _ _) hn) namespace measure_theory variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (measurable_sn : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ @[extensionality] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := by cases f; cases g; congr; exact funext H protected def range (f : α →ₛ β) := f.finite.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ ∃ a, f a = b := finite.mem_to_finset def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_subset (set.finite_singleton b) $ by rintro _ ⟨a, rfl⟩; simp⟩ @[simp] theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl lemma range_const (α) [measure_space α] [ne : nonempty α] (b : β) : (const α b).range = {b} := begin ext b', simp [mem_range], exact ⟨assume ⟨_, h⟩, h.symm, assume h, ne.elim $ λa, ⟨a, h.symm⟩⟩ end lemma is_measurable_cut (p : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | p a b}) : is_measurable {a | p a (f a)} := begin rw (_ : {a | p a (f a)} = ⋃ b ∈ set.range f, {a | p a b} ∩ f ⁻¹' {b}), { exact is_measurable.bUnion (countable_finite f.finite) (λ b _, is_measurable.inter (h b) (f.measurable_sn _)) }, ext a, simp, exact ⟨λ h, ⟨_, ⟨a, rfl⟩, h, rfl⟩, λ ⟨_, ⟨a', rfl⟩, h', e⟩, e.symm ▸ h'⟩ end theorem preimage_measurable (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, by simp [is_measurable.const]) theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, preimage_measurable f s def ite {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨λ a, if a ∈ s then f a else g a, λ x, by letI : measurable_space β := ⊤; exact measurable.if hs f.measurable g.measurable _ trivial, finite_subset (finite_union f.finite g.finite) begin rintro _ ⟨a, rfl⟩, by_cases a ∈ s; simp [h], exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] end⟩ @[simp] theorem ite_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : ite hs f g a = if a ∈ s then f a else g a := rfl def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, is_measurable_cut (λa b, g b a ∈ ({c} : set γ)) f (λ b, (g b).measurable_sn c), finite_subset (finite_bUnion f.finite (λ b, (g b).finite)) $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨_, ⟨a, rfl⟩, _, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl def restrict [has_zero β] (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then ite hs f (const α 0) else const α 0 @[simp] theorem restrict_apply [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by unfold_coes; simp [restrict, hs]; apply ite_apply hs theorem restrict_preimage [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by ext a; dsimp; rw [restrict_apply]; by_cases a ∈ s; simp [h, hs, ht] def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) @[simp] theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := begin ext c, simp [mem_range], split, { rintros ⟨a, rfl⟩, exact ⟨f a, ⟨_, rfl⟩, rfl⟩ }, { rintros ⟨_, ⟨a, rfl⟩, rfl⟩, exact ⟨_, rfl⟩ } end def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp] lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl instance [add_monoid β] : add_monoid (α →ₛ β) := { add := (+), zero := 0, add_assoc := assume f g h, ext (assume a, add_assoc _ _ _), zero_add := assume f, ext (assume a, zero_add _), add_zero := assume f, ext (assume a, add_zero _) } instance [semiring β] [add_monoid β] : has_scalar β (α →ₛ β) := ⟨λb f, f.map (λa, b * a)⟩ instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice.lattice, .. simple_func.lattice.order_bot, .. simple_func.lattice.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section approx section variables [topological_space β] [semilattice_sup_bot β] [has_zero β] def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α(i k)) {a:α | i k ≤ f a}) lemma approx_apply [ordered_topology β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : _root_.measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf.preimage $ is_measurable_of_is_closed $ is_closed_ge' _) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h end lemma supr_approx_apply [topological_space β] [complete_lattice β] [ordered_topology β] [has_zero β] (i : ℕ → β) (f : α → β) (a : α) (hf : _root_.measurable f) (h_zero : (0 : β) = ⊥): (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox def ennreal_rat_embed (n : ℕ) : ennreal := nnreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) (hq : 0 ≤ q) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : _root_.measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q hq], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end end eapprox end measurable section measure variables [measure_space α] def integral (f : α →ₛ ennreal) : ennreal := f.range.sum (λ x, x * volume (f ⁻¹' {x})) -- TODO: slow simp proofs lemma map_integral (g : β → ennreal) (f : α →ₛ β) : (f.map g).integral = f.range.sum (λ x, g x * volume (f ⁻¹' {x})) := begin simp only [integral, coe_map, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, let s' := f.range.filter (λb, g b = g (f a)), have : g ∘ ⇑f ⁻¹' {g (f a)} = (⋃b∈s', ⇑f ⁻¹' {b}), { ext a', simp, split, { assume eq, exact ⟨⟨_, rfl⟩, eq⟩ }, { rintros ⟨_, eq⟩, exact eq } }, calc g (f a) * volume (g ∘ ⇑f ⁻¹' {g (f a)}) = g (f a) * volume (⋃b∈s', ⇑f ⁻¹' {b}) : by rw [this] ... = g (f a) * s'.sum (λb, volume (f ⁻¹' {b})) : begin rw [volume_bUnion_finset], { simp [pairwise_on, (on)], rintros b a₀ rfl eq₀ b a₁ rfl eq₁ ne a ⟨h₁, h₂⟩, simp at h₁ h₂, rw [← h₁, h₂] at ne, exact ne rfl }, exact assume a ha, preimage_measurable _ _ end ... = s'.sum (λb, g (f a) * volume (f ⁻¹' {b})) : by rw [finset.mul_sum] ... = s'.sum (λb, g b * volume (f ⁻¹' {b})) : finset.sum_congr rfl $ by simp {contextual := tt} end lemma zero_integral : (0 : α →ₛ ennreal).integral = 0 := begin refine (finset.sum_eq_zero_iff_of_nonneg $ assume _ _, zero_le _).2 _, assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, exact zero_mul _ end lemma add_integral (f g : α →ₛ ennreal) : (f + g).integral = f.integral + g.integral := calc (f + g).integral = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x}) + x.2 * volume (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_integral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x})) + (pair f g).range.sum (λx, x.2 * volume (pair f g ⁻¹' {x})) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).integral + ((pair f g).map prod.snd).integral : by rw [map_integral, map_integral] ... = integral f + integral g : rfl lemma const_mul_integral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).integral = x * f.integral := calc (f.map (λa, x * a)).integral = f.range.sum (λr, x * r * volume (f ⁻¹' {r})) : by rw [map_integral] ... = f.range.sum (λr, x * (r * volume (f ⁻¹' {r}))) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.integral : finset.mul_sum.symm lemma mem_restrict_range [has_zero β] {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (∃a∈s, f a = r) := begin simp only [mem_range, restrict_apply, hs], split, { rintros ⟨a, ha⟩, split_ifs at ha, { exact or.inr ⟨a, h, ha⟩ }, { exact or.inl ⟨ha.symm, assume eq, h $ eq.symm ▸ trivial⟩ } }, { rintros (⟨rfl, h⟩ | ⟨a, ha, rfl⟩), { have : ¬ ∀a, a ∈ s := assume this, h $ eq_univ_of_forall this, rcases not_forall.1 this with ⟨a, ha⟩, refine ⟨a, _⟩, rw [if_neg ha] }, { refine ⟨a, _⟩, rw [if_pos ha] } } end lemma restrict_preimage' {r : ennreal} {s : set α} (f : α →ₛ ennreal) (hs : is_measurable s) (hr : r ≠ 0): (restrict f s) ⁻¹' {r} = (f ⁻¹' {r} ∩ s) := begin ext a, by_cases a ∈ s; simp [hs, h, hr.symm] end lemma restrict_integral (f : α →ₛ ennreal) (s : set α) (hs : is_measurable s) : (restrict f s).integral = f.range.sum (λr, r * volume (f ⁻¹' {r} ∩ s)) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { assume r hr, rcases (mem_restrict_range hs).1 hr with ⟨rfl, h⟩ | ⟨a, ha, rfl⟩, { simp }, { assume _, exact mem_range.2 ⟨a, rfl⟩ } }, { assume a b _ _ _ _ h, exact h }, { assume r hr, by_cases r0 : r = 0, { simp [r0] }, assume h0, rcases mem_range.1 hr with ⟨a, rfl⟩, have : f ⁻¹' {f a} ∩ s ≠ ∅, { assume h, simpa [h] using h0 }, rcases ne_empty_iff_exists_mem.1 this with ⟨a', eq', ha'⟩, refine ⟨_, (mem_restrict_range hs).2 (or.inr ⟨a', ha', _⟩), _, rfl⟩, { simpa using eq' }, { rwa [restrict_preimage' _ hs r0] } }, { assume r hr ne, by_cases r = 0, { simp [h] }, rw [restrict_preimage' _ hs h] } end lemma restrict_const_integral (c : ennreal) (s : set α) (hs : is_measurable s) : (restrict (const α c) s).integral = c * volume s := have (@const α ennreal _ c) ⁻¹' {c} = univ, begin refine eq_univ_of_forall (assume a, _), simp, end, calc (restrict (const α c) s).integral = c * volume ((const α c) ⁻¹' {c} ∩ s) : begin rw [restrict_integral (const α c) s hs], refine finset.sum_eq_single c _ _, { assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, contradiction }, { by_cases nonempty α, { assume ne, rcases h with ⟨a⟩, exfalso, exact ne (mem_range.2 ⟨a, rfl⟩) }, { assume empty, have : (@const α ennreal _ c) ⁻¹' {c} ∩ s = ∅, { ext a, exfalso, exact h ⟨a⟩ }, simp only [this, volume_empty, mul_zero] } } end ... = c * volume s : by rw [this, univ_inter] lemma integral_sup_le (f g : α →ₛ ennreal) : f.integral ⊔ g.integral ≤ (f ⊔ g).integral := calc f.integral ⊔ g.integral = ((pair f g).map prod.fst).integral ⊔ ((pair f g).map prod.snd).integral : rfl ... ≤ (pair f g).range.sum (λx, (x.1 ⊔ x.2) * volume (pair f g ⁻¹' {x})) : begin rw [map_integral, map_integral], refine sup_le _ _; refine finset.sum_le_sum' (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).integral : by rw [sup_eq_map₂, map_integral] lemma integral_le_integral (f g : α →ₛ ennreal) (h : f ≤ g) : f.integral ≤ g.integral := calc f.integral ≤ f.integral ⊔ g.integral : le_sup_left ... ≤ (f ⊔ g).integral : integral_sup_le _ _ ... = g.integral : by rw [sup_of_le_right h] lemma integral_congr (f g : α →ₛ ennreal) (h : {a | f a = g a} ∈ (@measure_space.μ α _).a_e.sets) : f.integral = g.integral := show ((pair f g).map prod.fst).integral = ((pair f g).map prod.snd).integral, from begin rw [map_integral, map_integral], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine volume_mono_null (assume a' ha', _) h, simp at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp [this] } end end measure end simple_func section lintegral open simple_func variable [measure_space α] /-- The lower Lebesgue integral -/ def lintegral (f : α → ennreal) : ennreal := ⨆ (s : α →ₛ ennreal) (hf : f ≥ s), s.integral notation `∫⁻` binders `, ` r:(scoped f, lintegral f) := r theorem simple_func.lintegral_eq_integral (f : α →ₛ ennreal) : (∫⁻ a, f a) = f.integral := le_antisymm (supr_le $ assume s, supr_le $ assume hs, integral_le_integral _ _ hs) (le_supr_of_le f $ le_supr_of_le (le_refl f) $ le_refl _) lemma lintegral_le_lintegral (f g : α → ennreal) (h : f ≤ g) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := supr_le_supr $ assume s, supr_le $ assume hs, le_supr_of_le (le_trans hs h) (le_refl _) lemma lintegral_eq_nnreal (f : α → ennreal) : (∫⁻ a, f a) = (⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map (coe : nnreal → ennreal)), (s.map (coe : nnreal → ennreal)).integral) := begin let c : nnreal → ennreal := coe, refine le_antisymm (supr_le $ assume s, supr_le $ assume hs, _) (supr_le $ assume s, supr_le $ assume hs, le_supr_of_le (s.map c) $ le_supr _ hs), by_cases {a | s a ≠ ⊤} ∈ ((@measure_space.μ α _).a_e).sets, { have : f ≥ (s.map ennreal.to_nnreal).map c := le_trans (assume a, ennreal.coe_to_nnreal_le_self) hs, refine le_supr_of_le (s.map ennreal.to_nnreal) (le_supr_of_le this (le_of_eq $ integral_congr _ _ _)), exact filter.mem_sets_of_superset h (assume a ha, (ennreal.coe_to_nnreal ha).symm) }, { have h_vol_s : volume {a : α | s a = ⊤} ≠ 0, { simp [measure.a_e, set.compl_set_of] at h, assumption }, let n : ℕ → (α →ₛ nnreal) := λn, restrict (const α (n : nnreal)) (s ⁻¹' {⊤}), have n_le_s : ∀i, (n i).map c ≤ s, { assume i a, dsimp [n, c], rw [restrict_apply _ (s.preimage_measurable _)], split_ifs with ha, { simp at ha, exact ha.symm ▸ le_top }, { exact zero_le _ } }, have approx_s : ∀ (i : ℕ), ↑i * volume {a : α | s a = ⊤} ≤ integral (map c (n i)), { assume i, have : {a : α | s a = ⊤} = s ⁻¹' {⊤}, { ext a, simp }, rw [this, ← restrict_const_integral _ _ (s.preimage_measurable _)], { refine integral_le_integral _ _ (assume a, le_of_eq _), simp [n, c, restrict_apply, s.preimage_measurable], split_ifs; simp [ennreal.coe_nat] }, }, calc s.integral ≤ ⊤ : le_top ... = (⨆i:ℕ, (i : ennreal) * volume {a | s a = ⊤}) : by rw [← ennreal.supr_mul, ennreal.supr_coe_nat, ennreal.top_mul, if_neg h_vol_s] ... ≤ (⨆i, ((n i).map c).integral) : supr_le_supr approx_s ... ≤ ⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map c), (s.map c).integral : have ∀i, ((n i).map c : α → ennreal) ≤ f := assume i, le_trans (n_le_s i) hs, (supr_le $ assume i, le_supr_of_le (n i) (le_supr (λh, ((n i).map c).integral) (this i))) } end /-- Monotone convergence theorem -- somtimes called Beppo-Levi convergence -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let c : nnreal → ennreal := coe in let F (a:α) := ⨆n, f n a in have hF : measurable F := measurable.supr hf, show (∫⁻ a, F a) = (⨆n, ∫⁻ a, f n a), begin refine le_antisymm _ _, { rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union_left, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * integral (s.map c) = (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r})) : by rw [← const_mul_integral, integral, eq_rs] ... ≤ (rs.map c).range.sum (λr, r * volume (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ (rs.map c).range.sum (λr, (⨆n, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}))) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [volume, measure_Union_eq_supr_nat _ (mono x), ennreal.mul_supr], { assume i, refine is_measurable.inter ((rs.map c).preimage_measurable _) _, refine (hf i).preimage _, exact is_measurable_of_is_closed (is_closed_ge' _) } end) ... ≤ ⨆n, (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (volume_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).integral) : begin refine supr_le_supr (assume n, _), rw [restrict_integral _ _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2, ext a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_integral], refine lintegral_le_lintegral _ _ (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end }, { exact supr_le (assume n, lintegral_le_lintegral _ _ $ assume a, le_supr _ n) } end lemma lintegral_eq_supr_eapprox_integral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a) = (⨆n, (eapprox f n).integral) := calc (∫⁻ a, f a) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).integral) : by congr; ext n; rw [(eapprox f n).lintegral_eq_integral] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a) = (∫⁻ a, f a) + (∫⁻ a, g a) := calc (∫⁻ a, f a + g a) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a)) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a)) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).integral + (eapprox g n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_integral, ← simple_func.lintegral_eq_integral], refl }, { assume n, exact measurable_add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add' (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).integral) + (⨆n, (eapprox g n).integral) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.integral_le_integral _ _ (monotone_eapprox _ h) } ... = (∫⁻ a, f a) + (∫⁻ a, g a) : by rw [lintegral_eq_supr_eapprox_integral hf, lintegral_eq_supr_eapprox_integral hg] @[simp] lemma lintegral_zero : (∫⁻ a:α, 0) = 0 := show (∫⁻ a:α, (0 : α →ₛ ennreal) a) = 0, by rw [simple_func.lintegral_eq_integral, zero_integral] lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a) = r * (∫⁻ a, f a) := calc (∫⁻ a, r * f a) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a)) : by congr; funext a; rw [← supr_eapprox_apply f hf, ennreal.mul_supr]; refl ... = (⨆n, r * (eapprox f n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_integral, ← simple_func.lintegral_eq_integral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_integral hf] lemma lintegral_supr_const (r : ennreal) {s : set α} (hs : is_measurable s) : (∫⁻ a, ⨆(h : a ∈ s), r) = r * volume s := begin rw [← restrict_const_integral r s hs, ← (restrict (const α r) s).lintegral_eq_integral], congr; ext a; by_cases a ∈ s; simp [h, hs], end end lintegral /- namespace measure def integral [measurable_space α] (m : measure α) (f : α → ennreal) : ennreal := @lintegral α { μ := m } f def measure.with_density [measurable_space α] (m : measure α) (f : α → ennreal) : measure α := if measurable f then measure.of_measurable (λs hs, m.integral (λa, ⨆(h : a ∈ s), f a)) _ _ else m end measure -/ end measure_theory
59c453e3b60ce9d18e2f74e835d22b2147f912e8
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/group_theory/free_group.lean
08b1a4186c42581c8b9931c8268e48dc3b1d4264
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
30,910
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Free groups as a quotient over the reduction relation `a * x * x⁻¹ * b = a * b`. First we introduce the one step reduction relation `free_group.red.step`: w * x * x⁻¹ * v ~> w * v its reflexive transitive closure: `free_group.red.trans` and proof that its join is an equivalence relation. Then we introduce `free_group α` as a quotient over `free_group.red.step`. -/ import data.fintype.basic import deprecated.subgroup open relation universes u v w variables {α : Type u} local attribute [simp] list.append_eq_has_append namespace free_group variables {L L₁ L₂ L₃ L₄ : list (α × bool)} /-- Reduction step: `w * x * x⁻¹ * v ~> w * v` -/ inductive red.step : list (α × bool) → list (α × bool) → Prop | bnot {L₁ L₂ x b} : red.step (L₁ ++ (x, b) :: (x, bnot b) :: L₂) (L₁ ++ L₂) attribute [simp] red.step.bnot /-- Reflexive-transitive closure of red.step -/ def red : list (α × bool) → list (α × bool) → Prop := refl_trans_gen red.step @[refl] lemma red.refl : red L L := refl_trans_gen.refl @[trans] lemma red.trans : red L₁ L₂ → red L₂ L₃ → red L₁ L₃ := refl_trans_gen.trans namespace red /-- Predicate asserting that word `w₁` can be reduced to `w₂` in one step, i.e. there are words `w₃ w₄` and letter `x` such that `w₁ = w₃xx⁻¹w₄` and `w₂ = w₃w₄` -/ theorem step.length : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.length + 2 = L₁.length | _ _ (@red.step.bnot _ L1 L2 x b) := by rw [list.length_append, list.length_append]; refl @[simp] lemma step.bnot_rev {x b} : step (L₁ ++ (x, bnot b) :: (x, b) :: L₂) (L₁ ++ L₂) := by cases b; from step.bnot @[simp] lemma step.cons_bnot {x b} : red.step ((x, b) :: (x, bnot b) :: L) L := @step.bnot _ [] _ _ _ @[simp] lemma step.cons_bnot_rev {x b} : red.step ((x, bnot b) :: (x, b) :: L) L := @red.step.bnot_rev _ [] _ _ _ theorem step.append_left : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₂ L₃ → step (L₁ ++ L₂) (L₁ ++ L₃) | _ _ _ red.step.bnot := by rw [← list.append_assoc, ← list.append_assoc]; constructor theorem step.cons {x} (H : red.step L₁ L₂) : red.step (x :: L₁) (x :: L₂) := @step.append_left _ [x] _ _ H theorem step.append_right : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₁ L₂ → step (L₁ ++ L₃) (L₂ ++ L₃) | _ _ _ red.step.bnot := by simp lemma not_step_nil : ¬ step [] L := begin generalize h' : [] = L', assume h, cases h with L₁ L₂, simp [list.nil_eq_append_iff] at h', contradiction end lemma step.cons_left_iff {a : α} {b : bool} : step ((a, b) :: L₁) L₂ ↔ (∃L, step L₁ L ∧ L₂ = (a, b) :: L) ∨ (L₁ = (a, bnot b)::L₂) := begin split, { generalize hL : ((a, b) :: L₁ : list _) = L, assume h, rcases h with ⟨_ | ⟨p, s'⟩, e, a', b'⟩, { simp at hL, simp [*] }, { simp at hL, rcases hL with ⟨rfl, rfl⟩, refine or.inl ⟨s' ++ e, step.bnot, _⟩, simp } }, { assume h, rcases h with ⟨L, h, rfl⟩ | rfl, { exact step.cons h }, { exact step.cons_bnot } } end lemma not_step_singleton : ∀ {p : α × bool}, ¬ step [p] L | (a, b) := by simp [step.cons_left_iff, not_step_nil] lemma step.cons_cons_iff : ∀{p : α × bool}, step (p :: L₁) (p :: L₂) ↔ step L₁ L₂ := by simp [step.cons_left_iff, iff_def, or_imp_distrib] {contextual := tt} lemma step.append_left_iff : ∀L, step (L ++ L₁) (L ++ L₂) ↔ step L₁ L₂ | [] := by simp | (p :: l) := by simp [step.append_left_iff l, step.cons_cons_iff] private theorem step.diamond_aux : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)} {x1 b1 x2 b2}, L₁ ++ (x1, b1) :: (x1, bnot b1) :: L₂ = L₃ ++ (x2, b2) :: (x2, bnot b2) :: L₄ → L₁ ++ L₂ = L₃ ++ L₄ ∨ ∃ L₅, red.step (L₁ ++ L₂) L₅ ∧ red.step (L₃ ++ L₄) L₅ | [] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ [(x3,b3)] _ _ _ _ _ H := by injections; subst_vars; simp | [(x3,b3)] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ ((x3,b3)::(x4,b4)::tl) _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.bnot, red.step.cons_bnot⟩ | ((x3,b3)::(x4,b4)::tl) _ [] _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.cons_bnot, red.step.bnot⟩ | ((x3,b3)::tl) _ ((x4,b4)::tl2) _ _ _ _ _ H := let ⟨H1, H2⟩ := list.cons.inj H in match step.diamond_aux H2 with | or.inl H3 := or.inl $ by simp [H1, H3] | or.inr ⟨L₅, H3, H4⟩ := or.inr ⟨_, step.cons H3, by simpa [H1] using step.cons H4⟩ end theorem step.diamond : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)}, red.step L₁ L₃ → red.step L₂ L₄ → L₁ = L₂ → L₃ = L₄ ∨ ∃ L₅, red.step L₃ L₅ ∧ red.step L₄ L₅ | _ _ _ _ red.step.bnot red.step.bnot H := step.diamond_aux H lemma step.to_red : step L₁ L₂ → red L₁ L₂ := refl_trans_gen.single /-- Church-Rosser theorem for word reduction: If `w1 w2 w3` are words such that `w1` reduces to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4` respectively. -/ theorem church_rosser : red L₁ L₂ → red L₁ L₃ → join red L₂ L₃ := relation.church_rosser (assume a b c hab hac, match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, hcd.to_red⟩ end) lemma cons_cons {p} : red L₁ L₂ → red (p :: L₁) (p :: L₂) := refl_trans_gen_lift (list.cons p) (assume a b, step.cons) lemma cons_cons_iff (p) : red (p :: L₁) (p :: L₂) ↔ red L₁ L₂ := iff.intro begin generalize eq₁ : (p :: L₁ : list _) = LL₁, generalize eq₂ : (p :: L₂ : list _) = LL₂, assume h, induction h using relation.refl_trans_gen.head_induction_on with L₁ L₂ h₁₂ h ih generalizing L₁ L₂, { subst_vars, cases eq₂, constructor }, { subst_vars, cases p with a b, rw [step.cons_left_iff] at h₁₂, rcases h₁₂ with ⟨L, h₁₂, rfl⟩ | rfl, { exact (ih rfl rfl).head h₁₂ }, { exact (cons_cons h).tail step.cons_bnot_rev } } end cons_cons lemma append_append_left_iff : ∀L, red (L ++ L₁) (L ++ L₂) ↔ red L₁ L₂ | [] := iff.rfl | (p :: L) := by simp [append_append_left_iff L, cons_cons_iff] lemma append_append (h₁ : red L₁ L₃) (h₂ : red L₂ L₄) : red (L₁ ++ L₂) (L₃ ++ L₄) := (refl_trans_gen_lift (λL, L ++ L₂) (assume a b, step.append_right) h₁).trans ((append_append_left_iff _).2 h₂) lemma to_append_iff : red L (L₁ ++ L₂) ↔ (∃L₃ L₄, L = L₃ ++ L₄ ∧ red L₃ L₁ ∧ red L₄ L₂) := iff.intro begin generalize eq : L₁ ++ L₂ = L₁₂, assume h, induction h with L' L₁₂ hLL' h ih generalizing L₁ L₂, { exact ⟨_, _, eq.symm, by refl, by refl⟩ }, { cases h with s e a b, rcases list.append_eq_append_iff.1 eq with ⟨s', rfl, rfl⟩ | ⟨e', rfl, rfl⟩, { have : L₁ ++ (s' ++ ((a, b) :: (a, bnot b) :: e)) = (L₁ ++ s') ++ ((a, b) :: (a, bnot b) :: e), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁, h₂.tail step.bnot⟩ }, { have : (s ++ ((a, b) :: (a, bnot b) :: e')) ++ L₂ = s ++ ((a, b) :: (a, bnot b) :: (e' ++ L₂)), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁.tail step.bnot, h₂⟩ }, } end (assume ⟨L₃, L₄, eq, h₃, h₄⟩, eq.symm ▸ append_append h₃ h₄) /-- The empty word `[]` only reduces to itself. -/ theorem nil_iff : red [] L ↔ L = [] := refl_trans_gen_iff_eq (assume l, red.not_step_nil) /-- A letter only reduces to itself. -/ theorem singleton_iff {x} : red [x] L₁ ↔ L₁ = [x] := refl_trans_gen_iff_eq (assume l, not_step_singleton) /-- If `x` is a letter and `w` is a word such that `xw` reduces to the empty word, then `w` reduces to `x⁻¹` -/ theorem cons_nil_iff_singleton {x b} : red ((x, b) :: L) [] ↔ red L [(x, bnot b)] := iff.intro (assume h, have h₁ : red ((x, bnot b) :: (x, b) :: L) [(x, bnot b)], from cons_cons h, have h₂ : red ((x, bnot b) :: (x, b) :: L) L, from refl_trans_gen.single step.cons_bnot_rev, let ⟨L', h₁, h₂⟩ := church_rosser h₁ h₂ in by rw [singleton_iff] at h₁; subst L'; assumption) (assume h, (cons_cons h).tail step.cons_bnot) theorem red_iff_irreducible {x1 b1 x2 b2} (h : (x1, b1) ≠ (x2, b2)) : red [(x1, bnot b1), (x2, b2)] L ↔ L = [(x1, bnot b1), (x2, b2)] := begin apply refl_trans_gen_iff_eq, generalize eq : [(x1, bnot b1), (x2, b2)] = L', assume L h', cases h', simp [list.cons_eq_append_iff, list.nil_eq_append_iff] at eq, rcases eq with ⟨rfl, ⟨rfl, rfl⟩, ⟨rfl, rfl⟩, rfl⟩, subst_vars, simp at h, contradiction end /-- If `x` and `y` are distinct letters and `w₁ w₂` are words such that `xw₁` reduces to `yw₂`, then `w₁` reduces to `x⁻¹yw₂`. -/ theorem inv_of_red_of_ne {x1 b1 x2 b2} (H1 : (x1, b1) ≠ (x2, b2)) (H2 : red ((x1, b1) :: L₁) ((x2, b2) :: L₂)) : red L₁ ((x1, bnot b1) :: (x2, b2) :: L₂) := begin have : red ((x1, b1) :: L₁) ([(x2, b2)] ++ L₂), from H2, rcases to_append_iff.1 this with ⟨_ | ⟨p, L₃⟩, L₄, eq, h₁, h₂⟩, { simp [nil_iff] at h₁, contradiction }, { cases eq, show red (L₃ ++ L₄) ([(x1, bnot b1), (x2, b2)] ++ L₂), apply append_append _ h₂, have h₁ : red ((x1, bnot b1) :: (x1, b1) :: L₃) [(x1, bnot b1), (x2, b2)], { exact cons_cons h₁ }, have h₂ : red ((x1, bnot b1) :: (x1, b1) :: L₃) L₃, { exact step.cons_bnot_rev.to_red }, rcases church_rosser h₁ h₂ with ⟨L', h₁, h₂⟩, rw [red_iff_irreducible H1] at h₁, rwa [h₁] at h₂ } end theorem step.sublist (H : red.step L₁ L₂) : L₂ <+ L₁ := by cases H; simp; constructor; constructor; refl /-- If `w₁ w₂` are words such that `w₁` reduces to `w₂`, then `w₂` is a sublist of `w₁`. -/ theorem sublist : red L₁ L₂ → L₂ <+ L₁ := refl_trans_gen_of_transitive_reflexive (λl, list.sublist.refl l) (λa b c hab hbc, list.sublist.trans hbc hab) (λa b, red.step.sublist) theorem sizeof_of_step : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.sizeof < L₁.sizeof | _ _ (@step.bnot _ L1 L2 x b) := begin induction L1 with hd tl ih, case list.nil { dsimp [list.sizeof], have H : 1 + sizeof (x, b) + (1 + sizeof (x, bnot b) + list.sizeof L2) = (list.sizeof L2 + 1) + (sizeof (x, b) + sizeof (x, bnot b) + 1), { ac_refl }, rw H, exact nat.le_add_right _ _ }, case list.cons { dsimp [list.sizeof], exact nat.add_lt_add_left ih _ } end theorem length (h : red L₁ L₂) : ∃ n, L₁.length = L₂.length + 2 * n := begin induction h with L₂ L₃ h₁₂ h₂₃ ih, { exact ⟨0, rfl⟩ }, { rcases ih with ⟨n, eq⟩, existsi (1 + n), simp [mul_add, eq, (step.length h₂₃).symm, add_assoc] } end theorem antisymm (h₁₂ : red L₁ L₂) : red L₂ L₁ → L₁ = L₂ := match L₁, h₁₂.cases_head with | _, or.inl rfl := assume h, rfl | L₁, or.inr ⟨L₃, h₁₃, h₃₂⟩ := assume h₂₁, let ⟨n, eq⟩ := length (h₃₂.trans h₂₁) in have list.length L₃ + 0 = list.length L₃ + (2 * n + 2), by simpa [(step.length h₁₃).symm, add_comm, add_assoc] using eq, (nat.no_confusion $ nat.add_left_cancel this) end end red theorem equivalence_join_red : equivalence (join (@red α)) := equivalence_join_refl_trans_gen $ assume a b c hab hac, (match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, refl_trans_gen.single hcd⟩ end) theorem join_red_of_step (h : red.step L₁ L₂) : join red L₁ L₂ := join_of_single reflexive_refl_trans_gen h.to_red theorem eqv_gen_step_iff_join_red : eqv_gen red.step L₁ L₂ ↔ join red L₁ L₂ := iff.intro (assume h, have eqv_gen (join red) L₁ L₂ := eqv_gen_mono (assume a b, join_red_of_step) h, (eqv_gen_iff_of_equivalence $ equivalence_join_red).1 this) (join_of_equivalence (eqv_gen.is_equivalence _) $ assume a b, refl_trans_gen_of_equivalence (eqv_gen.is_equivalence _) eqv_gen.rel) end free_group /-- The free group over a type, i.e. the words formed by the elements of the type and their formal inverses, quotient by one step reduction. -/ def free_group (α : Type u) : Type u := quot $ @free_group.red.step α namespace free_group variables {α} {L L₁ L₂ L₃ L₄ : list (α × bool)} def mk (L) : free_group α := quot.mk red.step L @[simp] lemma quot_mk_eq_mk : quot.mk red.step L = mk L := rfl @[simp] lemma quot_lift_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift f H (mk L) = f L := rfl @[simp] lemma quot_lift_on_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift_on (mk L) f H = f L := rfl instance : has_one (free_group α) := ⟨mk []⟩ lemma one_eq_mk : (1 : free_group α) = mk [] := rfl instance : inhabited (free_group α) := ⟨1⟩ instance : has_mul (free_group α) := ⟨λ x y, quot.lift_on x (λ L₁, quot.lift_on y (λ L₂, mk $ L₁ ++ L₂) (λ L₂ L₃ H, quot.sound $ red.step.append_left H)) (λ L₁ L₂ H, quot.induction_on y $ λ L₃, quot.sound $ red.step.append_right H)⟩ @[simp] lemma mul_mk : mk L₁ * mk L₂ = mk (L₁ ++ L₂) := rfl instance : has_inv (free_group α) := ⟨λx, quot.lift_on x (λ L, mk (L.map $ λ x : α × bool, (x.1, bnot x.2)).reverse) (assume a b h, quot.sound $ by cases h; simp)⟩ @[simp] lemma inv_mk : (mk L)⁻¹ = mk (L.map $ λ x : α × bool, (x.1, bnot x.2)).reverse := rfl instance : group (free_group α) := { mul := (*), one := 1, inv := has_inv.inv, mul_assoc := by rintros ⟨L₁⟩ ⟨L₂⟩ ⟨L₃⟩; simp, one_mul := by rintros ⟨L⟩; refl, mul_one := by rintros ⟨L⟩; simp [one_eq_mk], mul_left_inv := by rintros ⟨L⟩; exact (list.rec_on L rfl $ λ ⟨x, b⟩ tl ih, eq.trans (quot.sound $ by simp [one_eq_mk]) ih) } /-- `of x` is the canonical injection from the type to the free group over that type by sending each element to the equivalence class of the letter that is the element. -/ def of (x : α) : free_group α := mk [(x, tt)] theorem red.exact : mk L₁ = mk L₂ ↔ join red L₁ L₂ := calc (mk L₁ = mk L₂) ↔ eqv_gen red.step L₁ L₂ : iff.intro (quot.exact _) quot.eqv_gen_sound ... ↔ join red L₁ L₂ : eqv_gen_step_iff_join_red /-- The canonical injection from the type to the free group is an injection. -/ theorem of.inj {x y : α} (H : of x = of y) : x = y := let ⟨L₁, hx, hy⟩ := red.exact.1 H in by simp [red.singleton_iff] at hx hy; cc section to_group variables {β : Type v} [group β] (f : α → β) {x y : free_group α} def to_group.aux : list (α × bool) → β := λ L, list.prod $ L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹ theorem red.step.to_group {f : α → β} (H : red.step L₁ L₂) : to_group.aux f L₁ = to_group.aux f L₂ := by cases H with _ _ _ b; cases b; simp [to_group.aux] /-- If `β` is a group, then any function from `α` to `β` extends uniquely to a group homomorphism from the free group over `α` to `β` -/ def to_group : free_group α → β := quot.lift (to_group.aux f) $ λ L₁ L₂ H, red.step.to_group H variable {f} @[simp] lemma to_group.mk : to_group f (mk L) = list.prod (L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹) := rfl @[simp] lemma to_group.of {x} : to_group f (of x) = f x := one_mul _ instance to_group.is_group_hom : is_group_hom (to_group f) := { map_mul := by rintros ⟨L₁⟩ ⟨L₂⟩; simp } @[simp] lemma to_group.mul : to_group f (x * y) = to_group f x * to_group f y := is_mul_hom.map_mul _ _ _ @[simp] lemma to_group.one : to_group f 1 = 1 := is_group_hom.map_one _ @[simp] lemma to_group.inv : to_group f x⁻¹ = (to_group f x)⁻¹ := is_group_hom.map_inv _ _ theorem to_group.unique (g : free_group α → β) [is_group_hom g] (hg : ∀ x, g (of x) = f x) : ∀{x}, g x = to_group f x := by rintros ⟨L⟩; exact list.rec_on L (is_group_hom.map_one g) (λ ⟨x, b⟩ t (ih : g (mk t) = _), bool.rec_on b (show g ((of x)⁻¹ * mk t) = to_group f (mk ((x, ff) :: t)), by simp [is_mul_hom.map_mul g, is_group_hom.map_inv g, hg, ih, to_group, to_group.aux]) (show g (of x * mk t) = to_group f (mk ((x, tt) :: t)), by simp [is_mul_hom.map_mul g, is_group_hom.map_inv g, hg, ih, to_group, to_group.aux])) theorem to_group.of_eq (x : free_group α) : to_group of x = x := eq.symm $ to_group.unique id (λ x, rfl) theorem to_group.range_subset {s : set β} [is_subgroup s] (H : set.range f ⊆ s) : set.range (to_group f) ⊆ s := by rintros _ ⟨⟨L⟩, rfl⟩; exact list.rec_on L is_submonoid.one_mem (λ ⟨x, b⟩ tl ih, bool.rec_on b (by simp at ih ⊢; from is_submonoid.mul_mem (is_subgroup.inv_mem $ H ⟨x, rfl⟩) ih) (by simp at ih ⊢; from is_submonoid.mul_mem (H ⟨x, rfl⟩) ih)) theorem to_group.range_eq_closure : set.range (to_group f) = group.closure (set.range f) := set.subset.antisymm (to_group.range_subset group.subset_closure) (group.closure_subset $ λ y ⟨x, hx⟩, ⟨of x, by simpa⟩) end to_group section map variables {β : Type v} (f : α → β) {x y : free_group α} def map.aux (L : list (α × bool)) : list (β × bool) := L.map $ λ x, (f x.1, x.2) /-- Any function from `α` to `β` extends uniquely to a group homomorphism from the free group ver `α` to the free group over `β`. -/ def map (x : free_group α) : free_group β := x.lift_on (λ L, mk $ map.aux f L) $ λ L₁ L₂ H, quot.sound $ by cases H; simp [map.aux] instance map.is_group_hom : is_group_hom (map f) := { map_mul := by rintros ⟨L₁⟩ ⟨L₂⟩; simp [map, map.aux] } variable {f} @[simp] lemma map.mk : map f (mk L) = mk (L.map (λ x, (f x.1, x.2))) := rfl @[simp] lemma map.id : map id x = x := have H1 : (λ (x : α × bool), x) = id := rfl, by rcases x with ⟨L⟩; simp [H1] @[simp] lemma map.id' : map (λ z, z) x = x := map.id theorem map.comp {γ : Type w} {f : α → β} {g : β → γ} {x} : map g (map f x) = map (g ∘ f) x := by rcases x with ⟨L⟩; simp @[simp] lemma map.of {x} : map f (of x) = of (f x) := rfl @[simp] lemma map.mul : map f (x * y) = map f x * map f y := is_mul_hom.map_mul _ x y @[simp] lemma map.one : map f 1 = 1 := is_group_hom.map_one _ @[simp] lemma map.inv : map f x⁻¹ = (map f x)⁻¹ := is_group_hom.map_inv _ x theorem map.unique (g : free_group α → free_group β) [is_group_hom g] (hg : ∀ x, g (of x) = of (f x)) : ∀{x}, g x = map f x := by rintros ⟨L⟩; exact list.rec_on L (is_group_hom.map_one g) (λ ⟨x, b⟩ t (ih : g (mk t) = map f (mk t)), bool.rec_on b (show g ((of x)⁻¹ * mk t) = map f ((of x)⁻¹ * mk t), by simp [is_mul_hom.map_mul g, is_group_hom.map_inv g, hg, ih]) (show g (of x * mk t) = map f (of x * mk t), by simp [is_mul_hom.map_mul g, hg, ih])) /-- Equivalent types give rise to equivalent free groups. -/ def free_group_congr {α β} (e : α ≃ β) : free_group α ≃ free_group β := ⟨map e, map e.symm, λ x, by simp [function.comp, map.comp], λ x, by simp [function.comp, map.comp]⟩ theorem map_eq_to_group : map f x = to_group (of ∘ f) x := eq.symm $ map.unique _ $ λ x, by simp end map section prod variables [group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the multiplicative version of `sum`. -/ def prod : α := to_group id x variables {x y} @[simp] lemma prod_mk : prod (mk L) = list.prod (L.map $ λ x, cond x.2 x.1 x.1⁻¹) := rfl @[simp] lemma prod.of {x : α} : prod (of x) = x := to_group.of instance prod.is_group_hom : is_group_hom (@prod α _) := to_group.is_group_hom @[simp] lemma prod.mul : prod (x * y) = prod x * prod y := to_group.mul @[simp] lemma prod.one : prod (1:free_group α) = 1 := to_group.one @[simp] lemma prod.inv : prod x⁻¹ = (prod x)⁻¹ := to_group.inv lemma prod.unique (g : free_group α → α) [is_group_hom g] (hg : ∀ x, g (of x) = x) {x} : g x = prod x := to_group.unique g hg end prod theorem to_group_eq_prod_map {β : Type v} [group β] {f : α → β} {x} : to_group f x = prod (map f x) := have is_group_hom (prod ∘ map f) := is_group_hom.comp _ _, by exactI (eq.symm $ to_group.unique (prod ∘ map f) $ λ _, by simp) section sum variables [add_group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the additive version of `prod`. -/ def sum : α := @prod (multiplicative _) _ x variables {x y} @[simp] lemma sum_mk : sum (mk L) = list.sum (L.map $ λ x, cond x.2 x.1 (-x.1)) := rfl @[simp] lemma sum.of {x : α} : sum (of x) = x := prod.of instance sum.is_group_hom : is_group_hom (@sum α _) := prod.is_group_hom @[simp] lemma sum.mul : sum (x * y) = sum x + sum y := prod.mul @[simp] lemma sum.one : sum (1:free_group α) = 0 := prod.one @[simp] lemma sum.inv : sum x⁻¹ = -sum x := prod.inv end sum def free_group_empty_equiv_unit : free_group empty ≃ unit := { to_fun := λ _, (), inv_fun := λ _, 1, left_inv := by rintros ⟨_ | ⟨⟨⟨⟩, _⟩, _⟩⟩; refl, right_inv := λ ⟨⟩, rfl } def free_group_unit_equiv_int : free_group unit ≃ int := { to_fun := λ x, sum $ map (λ _, 1) x, inv_fun := λ x, of () ^ x, left_inv := by rintros ⟨L⟩; exact list.rec_on L rfl (λ ⟨⟨⟩, b⟩ tl ih, by cases b; simp [gpow_add] at ih ⊢; rw ih; refl), right_inv := λ x, int.induction_on x (by simp) (λ i ih, by simp at ih; simp [gpow_add, ih]) (λ i ih, by simp at ih; simp [gpow_add, ih, sub_eq_add_neg]) } section category variables {β : Type u} instance : monad free_group.{u} := { pure := λ α, of, map := λ α β, map, bind := λ α β x f, to_group f x } @[elab_as_eliminator] protected theorem induction_on {C : free_group α → Prop} (z : free_group α) (C1 : C 1) (Cp : ∀ x, C $ pure x) (Ci : ∀ x, C (pure x) → C (pure x)⁻¹) (Cm : ∀ x y, C x → C y → C (x * y)) : C z := quot.induction_on z $ λ L, list.rec_on L C1 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cm _ _ (Ci _ $ Cp x) ih) (Cm _ _ (Cp x) ih) @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_group α) = pure (f x) := map.of @[simp] lemma map_one (f : α → β) : f <$> (1 : free_group α) = 1 := map.one @[simp] lemma map_mul (f : α → β) (x y : free_group α) : f <$> (x * y) = f <$> x * f <$> y := map.mul @[simp] lemma map_inv (f : α → β) (x : free_group α) : f <$> (x⁻¹) = (f <$> x)⁻¹ := map.inv @[simp] lemma pure_bind (f : α → free_group β) (x) : pure x >>= f = f x := to_group.of @[simp] lemma one_bind (f : α → free_group β) : 1 >>= f = 1 := @@to_group.one _ f @[simp] lemma mul_bind (f : α → free_group β) (x y : free_group α) : x * y >>= f = (x >>= f) * (y >>= f) := to_group.mul @[simp] lemma inv_bind (f : α → free_group β) (x : free_group α) : x⁻¹ >>= f = (x >>= f)⁻¹ := to_group.inv instance : is_lawful_monad free_group.{u} := { id_map := λ α x, free_group.induction_on x (map_one id) (λ x, map_pure id x) (λ x ih, by rw [map_inv, ih]) (λ x y ihx ihy, by rw [map_mul, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_group.induction_on x (by iterate 3 { rw one_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw inv_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw mul_bind }; rw [ihx, ihy]), bind_pure_comp_eq_map := λ α β f x, free_group.induction_on x (by rw [one_bind, map_one]) (λ x, by rw [pure_bind, map_pure]) (λ x ih, by rw [inv_bind, map_inv, ih]) (λ x y ihx ihy, by rw [mul_bind, map_mul, ihx, ihy]) } end category section reduce variable [decidable_eq α] /-- The maximal reduction of a word. It is computable iff `α` has decidable equality. -/ def reduce (L : list (α × bool)) : list (α × bool) := list.rec_on L [] $ λ hd1 tl1 ih, list.cases_on ih [hd1] $ λ hd2 tl2, if hd1.1 = hd2.1 ∧ hd1.2 = bnot hd2.2 then tl2 else hd1 :: hd2 :: tl2 @[simp] lemma reduce.cons (x) : reduce (x :: L) = list.cases_on (reduce L) [x] (λ hd tl, if x.1 = hd.1 ∧ x.2 = bnot hd.2 then tl else x :: hd :: tl) := rfl /-- The first theorem that characterises the function `reduce`: a word reduces to its maximal reduction. -/ theorem reduce.red : red L (reduce L) := begin induction L with hd1 tl1 ih, case list.nil { constructor }, case list.cons { dsimp, revert ih, generalize htl : reduce tl1 = TL, intro ih, cases TL with hd2 tl2, case list.nil { exact red.cons_cons ih }, case list.cons { dsimp, by_cases h : hd1.fst = hd2.fst ∧ hd1.snd = bnot (hd2.snd), { rw [if_pos h], transitivity, { exact red.cons_cons ih }, { cases hd1, cases hd2, cases h, dsimp at *, subst_vars, exact red.step.cons_bnot_rev.to_red } }, { rw [if_neg h], exact red.cons_cons ih } } } end theorem reduce.not {p : Prop} : ∀ {L₁ L₂ L₃ : list (α × bool)} {x b}, reduce L₁ = L₂ ++ (x, b) :: (x, bnot b) :: L₃ → p | [] L2 L3 _ _ := λ h, by cases L2; injections | ((x,b)::L1) L2 L3 x' b' := begin dsimp, cases r : reduce L1, { dsimp, intro h, have := congr_arg list.length h, simp [-add_comm] at this, exact absurd this dec_trivial }, cases hd with y c, by_cases x = y ∧ b = bnot c; simp [h]; intro H, { rw H at r, exact @reduce.not L1 ((y,c)::L2) L3 x' b' r }, rcases L2 with _|⟨a, L2⟩, { injections, subst_vars, simp at h, cc }, { refine @reduce.not L1 L2 L3 x' b' _, injection H with _ H, rw [r, H], refl } end /-- The second theorem that characterises the function `reduce`: the maximal reduction of a word only reduces to itself. -/ theorem reduce.min (H : red (reduce L₁) L₂) : reduce L₁ = L₂ := begin induction H with L1 L' L2 H1 H2 ih, { refl }, { cases H1 with L4 L5 x b, exact reduce.not H2 } end /-- `reduce` is idempotent, i.e. the maximal reduction of the maximal reduction of a word is the maximal reduction of the word. -/ theorem reduce.idem : reduce (reduce L) = reduce L := eq.symm $ reduce.min reduce.red theorem reduce.step.eq (H : red.step L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (reduce.red.head H) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If a word reduces to another word, then they have a common maximal reduction. -/ theorem reduce.eq_of_red (H : red L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (red.trans H reduce.red) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If two words correspond to the same element in the free group, then they have a common maximal reduction. This is the proof that the function that sends an element of the free group to its maximal reduction is well-defined. -/ theorem reduce.sound (H : mk L₁ = mk L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, H13, H23⟩ := red.exact.1 H in (reduce.eq_of_red H13).trans (reduce.eq_of_red H23).symm /-- If two words have a common maximal reduction, then they correspond to the same element in the free group. -/ theorem reduce.exact (H : reduce L₁ = reduce L₂) : mk L₁ = mk L₂ := red.exact.2 ⟨reduce L₂, H ▸ reduce.red, reduce.red⟩ /-- A word and its maximal reduction correspond to the same element of the free group. -/ theorem reduce.self : mk (reduce L) = mk L := reduce.exact reduce.idem /-- If words `w₁ w₂` are such that `w₁` reduces to `w₂`, then `w₂` reduces to the maximal reduction of `w₁`. -/ theorem reduce.rev (H : red L₁ L₂) : red L₂ (reduce L₁) := (reduce.eq_of_red H).symm ▸ reduce.red /-- The function that sends an element of the free group to its maximal reduction. -/ def to_word : free_group α → list (α × bool) := quot.lift reduce $ λ L₁ L₂ H, reduce.step.eq H lemma to_word.mk : ∀{x : free_group α}, mk (to_word x) = x := by rintros ⟨L⟩; exact reduce.self lemma to_word.inj : ∀(x y : free_group α), to_word x = to_word y → x = y := by rintros ⟨L₁⟩ ⟨L₂⟩; exact reduce.exact /-- Constructive Church-Rosser theorem (compare `church_rosser`). -/ def reduce.church_rosser (H12 : red L₁ L₂) (H13 : red L₁ L₃) : { L₄ // red L₂ L₄ ∧ red L₃ L₄ } := ⟨reduce L₁, reduce.rev H12, reduce.rev H13⟩ instance : decidable_eq (free_group α) := function.injective.decidable_eq to_word.inj instance red.decidable_rel : decidable_rel (@red α) | [] [] := is_true red.refl | [] (hd2::tl2) := is_false $ λ H, list.no_confusion (red.nil_iff.1 H) | ((x,b)::tl) [] := match red.decidable_rel tl [(x, bnot b)] with | is_true H := is_true $ red.trans (red.cons_cons H) $ (@red.step.bnot _ [] [] _ _).to_red | is_false H := is_false $ λ H2, H $ red.cons_nil_iff_singleton.1 H2 end | ((x1,b1)::tl1) ((x2,b2)::tl2) := if h : (x1, b1) = (x2, b2) then match red.decidable_rel tl1 tl2 with | is_true H := is_true $ h ▸ red.cons_cons H | is_false H := is_false $ λ H2, H $ h ▸ (red.cons_cons_iff _).1 $ H2 end else match red.decidable_rel tl1 ((x1,bnot b1)::(x2,b2)::tl2) with | is_true H := is_true $ (red.cons_cons H).tail red.step.cons_bnot | is_false H := is_false $ λ H2, H $ red.inv_of_red_of_ne h H2 end /-- A list containing every word that `w₁` reduces to. -/ def red.enum (L₁ : list (α × bool)) : list (list (α × bool)) := list.filter (λ L₂, red L₁ L₂) (list.sublists L₁) theorem red.enum.sound (H : L₂ ∈ red.enum L₁) : red L₁ L₂ := list.of_mem_filter H theorem red.enum.complete (H : red L₁ L₂) : L₂ ∈ red.enum L₁ := list.mem_filter_of_mem (list.mem_sublists.2 $ red.sublist H) H instance : fintype { L₂ // red L₁ L₂ } := fintype.subtype (list.to_finset $ red.enum L₁) $ λ L₂, ⟨λ H, red.enum.sound $ list.mem_to_finset.1 H, λ H, list.mem_to_finset.2 $ red.enum.complete H⟩ end reduce end free_group
addf5a7fa190cda3dcefc2e3da48afa0f044e130
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/category_theory/preadditive/biproducts.lean
f414182f78e8b4db50c4dfd7ae08f7c576413827
[ "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
11,601
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 category_theory.limits.shapes.biproducts import category_theory.preadditive import tactic.abel /-! # Basic facts about morphisms between biproducts in preadditive categories. * In any category (with zero morphisms), if `biprod.map f g` is an isomorphism, then both `f` and `g` are isomorphisms. The remaining lemmas hold in any preadditive category. * If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. * As a corollary of the previous two facts, if we have an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, we can construct an isomorphism `X₂ ≅ Y₂`. * If `f : W ⊞ X ⟶ Y ⊞ Z` is an isomorphism, either `𝟙 W = 0`, or at least one of the component maps `W ⟶ Y` and `W ⟶ Z` is nonzero. * If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, then every column (corresponding to a nonzero summand in the domain) has some nonzero matrix entry. -/ open category_theory open category_theory.preadditive open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] section variables [has_zero_morphisms.{v} C] [has_binary_biproducts.{v} C] /-- If ``` (f 0) (0 g) ``` is invertible, then `f` is invertible. -/ def is_iso_left_of_is_iso_biprod_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso f := { inv := biprod.inl ≫ inv (biprod.map f g) ≫ biprod.fst, hom_inv_id' := begin have t := congr_arg (λ p : W ⊞ X ⟶ W ⊞ X, biprod.inl ≫ p ≫ biprod.fst) (is_iso.hom_inv_id (biprod.map f g)), simp only [category.id_comp, category.assoc, biprod.inl_map_assoc] at t, simp [t], end, inv_hom_id' := begin have t := congr_arg (λ p : Y ⊞ Z ⟶ Y ⊞ Z, biprod.inl ≫ p ≫ biprod.fst) (is_iso.inv_hom_id (biprod.map f g)), simp only [category.id_comp, category.assoc, biprod.map_fst] at t, simp only [category.assoc], simp [t], end } /-- If ``` (f 0) (0 g) ``` is invertible, then `g` is invertible. -/ def is_iso_right_of_is_iso_biprod_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso g := begin letI : is_iso (biprod.map g f) := by { rw [←biprod.braiding_map_braiding], apply_instance, }, exact is_iso_left_of_is_iso_biprod_map g f, end end section variables [preadditive.{v} C] [has_binary_biproducts.{v} C] variables {X₁ X₂ Y₁ Y₂ : C} variables (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) /-- The "matrix" morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` with specified components. -/ def biprod.of_components : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂ := biprod.fst ≫ f₁₁ ≫ biprod.inl + biprod.fst ≫ f₁₂ ≫ biprod.inr + biprod.snd ≫ f₂₁ ≫ biprod.inl + biprod.snd ≫ f₂₂ ≫ biprod.inr @[simp] lemma biprod.inl_of_components : biprod.inl ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₁₁ ≫ biprod.inl + f₁₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.inr_of_components : biprod.inr ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₂₁ ≫ biprod.inl + f₂₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.of_components_fst : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.fst = biprod.fst ≫ f₁₁ + biprod.snd ≫ f₂₁ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_snd : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.snd = biprod.fst ≫ f₁₂ + biprod.snd ≫ f₂₂ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_eq (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) : biprod.of_components (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd) = f := begin ext; simp, end @[simp] lemma biprod.of_components_comp {X₁ X₂ Y₁ Y₂ Z₁ Z₂ : C} (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) (g₁₁ : Y₁ ⟶ Z₁) (g₁₂ : Y₁ ⟶ Z₂) (g₂₁ : Y₂ ⟶ Z₁) (g₂₂ : Y₂ ⟶ Z₂) : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.of_components g₁₁ g₁₂ g₂₁ g₂₂ = biprod.of_components (f₁₁ ≫ g₁₁ + f₁₂ ≫ g₂₁) (f₁₁ ≫ g₁₂ + f₁₂ ≫ g₂₂) (f₂₁ ≫ g₁₁ + f₂₂ ≫ g₂₁) (f₂₁ ≫ g₁₂ + f₂₂ ≫ g₂₂) := begin dsimp [biprod.of_components], apply biprod.hom_ext; apply biprod.hom_ext'; simp only [add_comp, comp_add, add_comp_assoc, add_zero, zero_add, biprod.inl_fst, biprod.inl_snd, biprod.inr_fst, biprod.inr_snd, biprod.inl_fst_assoc, biprod.inl_snd_assoc, biprod.inr_fst_assoc, biprod.inr_snd_assoc, has_zero_morphisms.comp_zero, has_zero_morphisms.zero_comp, has_zero_morphisms.zero_comp_assoc, category.comp_id, category.assoc], end /-- The unipotent upper triangular matrix ``` (1 r) (0 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_upper {X₁ X₂ : C} (r : X₁ ⟶ X₂) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) r 0 (𝟙 _), inv := biprod.of_components (𝟙 _) (-r) 0 (𝟙 _), } /-- The unipotent lower triangular matrix ``` (1 0) (r 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_lower {X₁ X₂ : C} (r : X₂ ⟶ X₁) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) 0 r (𝟙 _), inv := biprod.of_components (𝟙 _) 0 (-r) (𝟙 _), } /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. (This is the version of `biprod.gaussian` written in terms of components.) -/ def biprod.gaussian' [is_iso f₁₁] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂) ≫ R.hom = biprod.map f₁₁ g₂₂ := ⟨biprod.unipotent_lower (-(f₂₁ ≫ inv f₁₁)), biprod.unipotent_upper (-(inv f₁₁ ≫ f₁₂)), f₂₂ - f₂₁ ≫ (inv f₁₁) ≫ f₁₂, by ext; simp; abel⟩ /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. -/ def biprod.gaussian (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f ≫ biprod.fst)] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ f ≫ R.hom = biprod.map (biprod.inl ≫ f ≫ biprod.fst) g₂₂ := begin let := biprod.gaussian' (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd), simpa [biprod.of_components_eq], end /-- If `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` via a two-by-two matrix whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim' [is_iso f₁₁] [is_iso (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂)] : X₂ ≅ Y₂ := begin obtain ⟨L, R, g, w⟩ := biprod.gaussian' f₁₁ f₁₂ f₂₁ f₂₂, letI : is_iso (biprod.map f₁₁ g) := by { rw ←w, apply_instance, }, letI : is_iso g := (is_iso_right_of_is_iso_biprod_map f₁₁ g), exact as_iso g, end /-- If `f` is an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim (f : X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f.hom ≫ biprod.fst)] : X₂ ≅ Y₂ := begin letI : is_iso (biprod.of_components (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd)) := by { simp only [biprod.of_components_eq], apply_instance, }, exact biprod.iso_elim' (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd) end lemma biprod.column_nonzero_of_iso {W X Y Z : C} (f : W ⊞ X ⟶ Y ⊞ Z) [is_iso f] : 𝟙 W = 0 ∨ biprod.inl ≫ f ≫ biprod.fst ≠ 0 ∨ biprod.inl ≫ f ≫ biprod.snd ≠ 0 := begin classical, by_contradiction, rw [not_or_distrib, not_or_distrib, classical.not_not, classical.not_not] at a, rcases a with ⟨nz, a₁, a₂⟩, set x := biprod.inl ≫ f ≫ inv f ≫ biprod.fst, have h₁ : x = 𝟙 W, by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biprod.total], conv_lhs { slice 2 3, rw [comp_add], }, simp only [category.assoc], rw [comp_add_assoc, add_comp], conv_lhs { congr, skip, slice 1 3, rw a₂, }, simp only [has_zero_morphisms.zero_comp, add_zero], conv_lhs { slice 1 3, rw a₁, }, simp only [has_zero_morphisms.zero_comp], }, exact nz (h₁.symm.trans h₀), end end variables [preadditive.{v} C] lemma biproduct.column_nonzero_of_iso' {σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ] {S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T] (s : σ) (f : ⨁ S ⟶ ⨁ T) [is_iso f] : (∀ t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t = 0) → 𝟙 (S s) = 0 := begin intro z, set x := biproduct.ι S s ≫ f ≫ inv f ≫ biproduct.π S s, have h₁ : x = 𝟙 (S s), by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biproduct.total], simp only [comp_sum_assoc], conv_lhs { congr, apply_congr, skip, simp only [reassoc_of z], }, simp, }, exact h₁.symm.trans h₀, end /-- If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, and `s` is a non-trivial summand of the source, then there is some `t` in the target so that the `s, t` matrix entry of `f` is nonzero. -/ def biproduct.column_nonzero_of_iso {σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ] {S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T] (s : σ) (nz : 𝟙 (S s) ≠ 0) [∀ t, decidable_eq (S s ⟶ T t)] (f : ⨁ S ⟶ ⨁ T) [is_iso f] : trunc (Σ' t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t ≠ 0) := begin apply trunc_sigma_of_exists, -- Do this before we run `classical`, so we get the right `decidable_eq` instances. have t := biproduct.column_nonzero_of_iso'.{v} s f, classical, by_contradiction, simp only [classical.not_exists_not] at a, exact nz (t a) end end category_theory
5c3b544d1aaa93549adf4c060e7a865efc54c383
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/PreDefinition/MkInhabitant.lean
42f7e38014b1d1443e9945d8002ef444cec0f955
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,437
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder namespace Lean.Elab open Meta private def mkInhabitant? (type : Expr) : MetaM (Option Expr) := do try pure $ some (← mkArbitrary type) catch _ => pure none private def findAssumption? (xs : Array Expr) (type : Expr) : MetaM (Option Expr) := do xs.findM? fun x => do isDefEq (← inferType x) type private def mkFnInhabitant? (xs : Array Expr) (type : Expr) : MetaM (Option Expr) := let rec loop | 0, type => mkInhabitant? type | i+1, type => do let x := xs[i] let type ← mkForallFVars #[x] type; match (← mkInhabitant? type) with | none => loop i type | some val => pure $ some (← mkLambdaFVars xs[0:i] val) loop xs.size type /- TODO: add a global IO.Ref to let users customize/extend this procedure -/ def mkInhabitantFor (declName : Name) (xs : Array Expr) (type : Expr) : MetaM Expr := do match (← mkInhabitant? type) with | some val => mkLambdaFVars xs val | none => match (← findAssumption? xs type) with | some x => mkLambdaFVars xs x | none => match (← mkFnInhabitant? xs type) with | some val => pure val | none => throwError "failed to compile partial definition '{declName}', failed to show that type is inhabited" end Lean.Elab
12aa98927d6c93f2d0d311d43de0fb98d019f890
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/algebra/module.lean
6bf0741958dcd47ce58b1aa3b2efa7cc1583be83
[ "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
15,490
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. ## Implemetation notes Throughout the `linear_map` section implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `linear_map`. When they can be inferred from the type it is faster to use this method than to use type class inference -/ 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 {rα : ring α} {gβ : add_comm_group β} {gγ : add_comm_group γ} {gδ : add_comm_group δ} variables {mβ : module α β} {mγ : module α γ} {mδ : module α δ} variables (f g : β →ₗ[α] γ) include α mβ mγ instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : β → γ) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : β →ₗ[α] γ) : β → γ) = f := rfl 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 := 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 include mδ 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 omit mγ mδ variables [rα] [gβ] [mβ] 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_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_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]) }
1aad4ec2fbf8a0069adc5d81839184e1cbfe3300
4fa118f6209450d4e8d058790e2967337811b2b5
/src/sheaves/sheaf_of_rings.lean
acab23414355813f0b320946a799b41efe79dad4
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
988
lean
/- Sheaf of rings. https://stacks.math.columbia.edu/tag/0071 Author: Ramon Fernandez Mir -/ import sheaves.sheaf import sheaves.presheaf_of_rings universes u -- A sheaf of rings is essentially a sheaf of types because we assume that the -- category of commutative rings has limits (proved later). This is tag 0073. structure sheaf_of_rings (α : Type u) [T : topological_space α] := (F : presheaf_of_rings α) (locality : locality F.to_presheaf) (gluing : gluing F.to_presheaf) section sheaf_of_rings instance sheaf_of_rings.to_presheaf_of_rings {α : Type u} [topological_space α] : has_coe (sheaf_of_rings α) (presheaf_of_rings α) := ⟨λ S, S.F⟩ instance sheaf_of_rings.to_presheaf {α : Type u} [topological_space α] : has_coe (sheaf_of_rings α) (presheaf α) := ⟨λ S, S.F.to_presheaf⟩ def is_sheaf_of_rings {α : Type u} [topological_space α] (F : presheaf_of_rings α) := locality F.to_presheaf ∧ gluing F.to_presheaf end sheaf_of_rings
807d11c36e9c3b4b5b609e198e8d8522fe6cd519
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/geometry/euclidean/monge_point.lean
f53ccdd8a0b24f811dd0991ee7e0127d9e2b07db
[]
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
25,520
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.geometry.euclidean.circumcenter import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Monge point and orthocenter This file defines the orthocenter of a triangle, via its n-dimensional generalization, the Monge point of a simplex. ## Main definitions * `monge_point` is the Monge point of a simplex, defined in terms of its position on the Euler line and then shown to be the point of concurrence of the Monge planes. * `monge_plane` is a Monge plane of an (n+2)-simplex, which is the (n+1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an n-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). * `altitude` is the line that passes through a vertex of a simplex and is orthogonal to the opposite face. * `orthocenter` is defined, for the case of a triangle, to be the same as its Monge point, then shown to be the point of concurrence of the altitudes. * `orthocentric_system` is a predicate on sets of points that says whether they are four points, one of which is the orthocenter of the other three (in which case various other properties hold, including that each is the orthocenter of the other three). ## References * https://en.wikipedia.org/wiki/Altitude_(triangle) * https://en.wikipedia.org/wiki/Monge_point * https://en.wikipedia.org/wiki/Orthocentric_system * Małgorzata Buba-Brzozowa, [The Monge Point and the 3(n+1) Point Sphere of an n-Simplex](https://pdfs.semanticscholar.org/6f8b/0f623459c76dac2e49255737f8f0f4725d16.pdf) -/ namespace affine namespace simplex /-- The Monge point of a simplex (in 2 or more dimensions) is a generalization of the orthocenter of a triangle. It is defined to be the intersection of the Monge planes, where a Monge plane is the (n-1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an (n-2)-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). The circumcenter O, centroid G and Monge point M are collinear in that order on the Euler line, with OG : GM = (n-1) : 2. Here, we use that ratio to define the Monge point (so resulting in a point that equals the centroid in 0 or 1 dimensions), and then show in subsequent lemmas that the point so defined lies in the Monge planes and is their unique point of intersection. -/ def monge_point {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P n) : P := (↑(n + 1) / ↑(n - 1)) • (finset.centroid ℝ finset.univ (points s) -ᵥ circumcenter s) +ᵥ circumcenter s /-- The position of the Monge point in relation to the circumcenter and centroid. -/ theorem monge_point_eq_smul_vsub_vadd_circumcenter {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P n) : monge_point s = (↑(n + 1) / ↑(n - 1)) • (finset.centroid ℝ finset.univ (points s) -ᵥ circumcenter s) +ᵥ circumcenter s := rfl /-- The Monge point lies in the affine span. -/ theorem monge_point_mem_affine_span {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P n) : monge_point s ∈ affine_span ℝ (set.range (points s)) := affine_subspace.smul_vsub_vadd_mem (affine_span ℝ (set.range (points s))) (↑(n + 1) / ↑(n - 1)) (centroid_mem_affine_span_of_card_eq_add_one ℝ (points s) (finset.card_fin (n + 1))) (circumcenter_mem_affine_span s) (circumcenter_mem_affine_span s) /-- Two simplices with the same points have the same Monge point. -/ theorem monge_point_eq_of_range_eq {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} {s₁ : simplex ℝ P n} {s₂ : simplex ℝ P n} (h : set.range (points s₁) = set.range (points s₂)) : monge_point s₁ = monge_point s₂ := sorry /-- The weights for the Monge point of an (n+2)-simplex, in terms of `points_with_circumcenter`. -/ def monge_point_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index (n + bit0 1) → ℝ := sorry /-- `monge_point_weights_with_circumcenter` sums to 1. -/ @[simp] theorem sum_monge_point_weights_with_circumcenter (n : ℕ) : (finset.sum finset.univ fun (i : points_with_circumcenter_index (n + bit0 1)) => monge_point_weights_with_circumcenter n i) = 1 := sorry /-- The Monge point of an (n+2)-simplex, in terms of `points_with_circumcenter`. -/ theorem monge_point_eq_affine_combination_of_points_with_circumcenter {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + bit0 1)) : monge_point s = coe_fn (finset.affine_combination finset.univ (points_with_circumcenter s)) (monge_point_weights_with_circumcenter n) := sorry /-- The weights for the Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, in terms of `points_with_circumcenter`. This definition is only valid when `i₁ ≠ i₂`. -/ def monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} (i₁ : fin (n + bit1 1)) (i₂ : fin (n + bit1 1)) : points_with_circumcenter_index (n + bit0 1) → ℝ := sorry /-- `monge_point_vsub_face_centroid_weights_with_circumcenter` is the result of subtracting `centroid_weights_with_circumcenter` from `monge_point_weights_with_circumcenter`. -/ theorem monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub {n : ℕ} {i₁ : fin (n + bit1 1)} {i₂ : fin (n + bit1 1)} (h : i₁ ≠ i₂) : monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ = monge_point_weights_with_circumcenter n - centroid_weights_with_circumcenter (insert i₁ (singleton i₂)ᶜ) := sorry /-- `monge_point_vsub_face_centroid_weights_with_circumcenter` sums to 0. -/ @[simp] theorem sum_monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} {i₁ : fin (n + bit1 1)} {i₂ : fin (n + bit1 1)} (h : i₁ ≠ i₂) : (finset.sum finset.univ fun (i : points_with_circumcenter_index (n + bit0 1)) => monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ i) = 0 := sorry /-- The Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, in terms of `points_with_circumcenter`. -/ theorem monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + bit0 1)) {i₁ : fin (n + bit1 1)} {i₂ : fin (n + bit1 1)} (h : i₁ ≠ i₂) : monge_point s -ᵥ finset.centroid ℝ (insert i₁ (singleton i₂)ᶜ) (points s) = coe_fn (finset.weighted_vsub finset.univ (points_with_circumcenter s)) (monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂) := sorry /-- The Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, is orthogonal to the difference of the two vertices not in that face. -/ theorem inner_monge_point_vsub_face_centroid_vsub {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + bit0 1)) {i₁ : fin (n + bit1 1)} {i₂ : fin (n + bit1 1)} (h : i₁ ≠ i₂) : inner (monge_point s -ᵥ finset.centroid ℝ (insert i₁ (singleton i₂)ᶜ) (points s)) (points s i₁ -ᵥ points s i₂) = 0 := sorry /-- A Monge plane of an (n+2)-simplex is the (n+1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an n-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). This definition is only intended to be used when `i₁ ≠ i₂`. -/ def monge_plane {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + bit0 1)) (i₁ : fin (n + bit1 1)) (i₂ : fin (n + bit1 1)) : affine_subspace ℝ P := affine_subspace.mk' (finset.centroid ℝ (insert i₁ (singleton i₂)ᶜ) (points s)) (submodule.span ℝ (singleton (points s i₁ -ᵥ points s i₂))ᗮ) ⊓ affine_span ℝ (set.range (points s)) /-- The definition of a Monge plane. -/ theorem monge_plane_def {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + bit0 1)) (i₁ : fin (n + bit1 1)) (i₂ : fin (n + bit1 1)) : monge_plane s i₁ i₂ = affine_subspace.mk' (finset.centroid ℝ (insert i₁ (singleton i₂)ᶜ) (points s)) (submodule.span ℝ (singleton (points s i₁ -ᵥ points s i₂))ᗮ) ⊓ affine_span ℝ (set.range (points s)) := rfl /-- The Monge plane associated with vertices `i₁` and `i₂` equals that associated with `i₂` and `i₁`. -/ theorem monge_plane_comm {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + bit0 1)) (i₁ : fin (n + bit1 1)) (i₂ : fin (n + bit1 1)) : monge_plane s i₁ i₂ = monge_plane s i₂ i₁ := sorry /-- The Monge point lies in the Monge planes. -/ theorem monge_point_mem_monge_plane {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + bit0 1)) {i₁ : fin (n + bit1 1)} {i₂ : fin (n + bit1 1)} (h : i₁ ≠ i₂) : monge_point s ∈ monge_plane s i₁ i₂ := sorry -- This doesn't actually need the `i₁ ≠ i₂` hypothesis, but it's -- convenient for the proof and `monge_plane` isn't intended to be -- useful without that hypothesis. /-- The direction of a Monge plane. -/ theorem direction_monge_plane {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + bit0 1)) {i₁ : fin (n + bit1 1)} {i₂ : fin (n + bit1 1)} (h : i₁ ≠ i₂) : affine_subspace.direction (monge_plane s i₁ i₂) = submodule.span ℝ (singleton (points s i₁ -ᵥ points s i₂))ᗮ ⊓ vector_span ℝ (set.range (points s)) := sorry /-- The Monge point is the only point in all the Monge planes from any one vertex. -/ theorem eq_monge_point_of_forall_mem_monge_plane {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} {s : simplex ℝ P (n + bit0 1)} {i₁ : fin (n + bit1 1)} {p : P} (h : ∀ (i₂ : fin (n + bit1 1)), i₁ ≠ i₂ → p ∈ monge_plane s i₁ i₂) : p = monge_point s := sorry /-- An altitude of a simplex is the line that passes through a vertex and is orthogonal to the opposite face. -/ def altitude {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + bit0 1)) : affine_subspace ℝ P := affine_subspace.mk' (points s i) (affine_subspace.direction (affine_span ℝ (points s '' ↑(finset.erase finset.univ i)))ᗮ) ⊓ affine_span ℝ (set.range (points s)) /-- The definition of an altitude. -/ theorem altitude_def {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + bit0 1)) : altitude s i = affine_subspace.mk' (points s i) (affine_subspace.direction (affine_span ℝ (points s '' ↑(finset.erase finset.univ i)))ᗮ) ⊓ affine_span ℝ (set.range (points s)) := rfl /-- A vertex lies in the corresponding altitude. -/ theorem mem_altitude {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + bit0 1)) : points s i ∈ altitude s i := sorry /-- The direction of an altitude. -/ theorem direction_altitude {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + bit0 1)) : affine_subspace.direction (altitude s i) = vector_span ℝ (points s '' ↑(finset.erase finset.univ i))ᗮ ⊓ vector_span ℝ (set.range (points s)) := sorry /-- The vector span of the opposite face lies in the direction orthogonal to an altitude. -/ theorem vector_span_le_altitude_direction_orthogonal {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + bit0 1)) : vector_span ℝ (points s '' ↑(finset.erase finset.univ i)) ≤ (affine_subspace.direction (altitude s i)ᗮ) := sorry /-- An altitude is finite-dimensional. -/ protected instance finite_dimensional_direction_altitude {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + bit0 1)) : finite_dimensional ℝ ↥(affine_subspace.direction (altitude s i)) := eq.mpr (id (Eq._oldrec (Eq.refl (finite_dimensional ℝ ↥(affine_subspace.direction (altitude s i)))) (direction_altitude s i))) (submodule.finite_dimensional_inf_right (vector_span ℝ (points s '' ↑(finset.erase finset.univ i))ᗮ) (vector_span ℝ (set.range (points s)))) /-- An altitude is one-dimensional (i.e., a line). -/ @[simp] theorem findim_direction_altitude {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + bit0 1)) : finite_dimensional.findim ℝ ↥(affine_subspace.direction (altitude s i)) = 1 := sorry /-- A line through a vertex is the altitude through that vertex if and only if it is orthogonal to the opposite face. -/ theorem affine_span_insert_singleton_eq_altitude_iff {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + bit0 1)) (p : P) : affine_span ℝ (insert p (singleton (points s i))) = altitude s i ↔ p ≠ points s i ∧ p ∈ affine_span ℝ (set.range (points s)) ∧ p -ᵥ points s i ∈ (affine_subspace.direction (affine_span ℝ (points s '' ↑(finset.erase finset.univ i)))ᗮ) := sorry end simplex namespace triangle /-- The orthocenter of a triangle is the intersection of its altitudes. It is defined here as the 2-dimensional case of the Monge point. -/ def orthocenter {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) : P := simplex.monge_point t /-- The orthocenter equals the Monge point. -/ theorem orthocenter_eq_monge_point {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) : orthocenter t = simplex.monge_point t := rfl /-- The position of the orthocenter in relation to the circumcenter and centroid. -/ theorem orthocenter_eq_smul_vsub_vadd_circumcenter {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) : orthocenter t = bit1 1 • (finset.centroid ℝ finset.univ (simplex.points t) -ᵥ simplex.circumcenter t) +ᵥ simplex.circumcenter t := sorry /-- The orthocenter lies in the affine span. -/ theorem orthocenter_mem_affine_span {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) : orthocenter t ∈ affine_span ℝ (set.range (simplex.points t)) := simplex.monge_point_mem_affine_span t /-- Two triangles with the same points have the same orthocenter. -/ theorem orthocenter_eq_of_range_eq {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {t₁ : triangle ℝ P} {t₂ : triangle ℝ P} (h : set.range (simplex.points t₁) = set.range (simplex.points t₂)) : orthocenter t₁ = orthocenter t₂ := simplex.monge_point_eq_of_range_eq h /-- In the case of a triangle, altitudes are the same thing as Monge planes. -/ theorem altitude_eq_monge_plane {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) {i₁ : fin (bit1 1)} {i₂ : fin (bit1 1)} {i₃ : fin (bit1 1)} (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : simplex.altitude t i₁ = simplex.monge_plane t i₂ i₃ := sorry /-- The orthocenter lies in the altitudes. -/ theorem orthocenter_mem_altitude {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) {i₁ : fin (bit1 1)} : orthocenter t ∈ simplex.altitude t i₁ := sorry /-- The orthocenter is the only point lying in any two of the altitudes. -/ theorem eq_orthocenter_of_forall_mem_altitude {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {t : triangle ℝ P} {i₁ : fin (bit1 1)} {i₂ : fin (bit1 1)} {p : P} (h₁₂ : i₁ ≠ i₂) (h₁ : p ∈ simplex.altitude t i₁) (h₂ : p ∈ simplex.altitude t i₂) : p = orthocenter t := sorry /-- The distance from the orthocenter to the reflection of the circumcenter in a side equals the circumradius. -/ theorem dist_orthocenter_reflection_circumcenter {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) {i₁ : fin (bit1 1)} {i₂ : fin (bit1 1)} (h : i₁ ≠ i₂) : dist (orthocenter t) (coe_fn (euclidean_geometry.reflection (affine_span ℝ (simplex.points t '' insert i₁ (singleton i₂)))) (simplex.circumcenter t)) = simplex.circumradius t := sorry /-- The distance from the orthocenter to the reflection of the circumcenter in a side equals the circumradius, variant using a `finset`. -/ theorem dist_orthocenter_reflection_circumcenter_finset {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) {i₁ : fin (bit1 1)} {i₂ : fin (bit1 1)} (h : i₁ ≠ i₂) : dist (orthocenter t) (coe_fn (euclidean_geometry.reflection (affine_span ℝ (simplex.points t '' ↑(insert i₁ (singleton i₂))))) (simplex.circumcenter t)) = simplex.circumradius t := sorry /-- The affine span of the orthocenter and a vertex is contained in the altitude. -/ theorem affine_span_orthocenter_point_le_altitude {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (t : triangle ℝ P) (i : fin (bit1 1)) : affine_span ℝ (insert (orthocenter t) (singleton (simplex.points t i))) ≤ simplex.altitude t i := sorry /-- Suppose we are given a triangle `t₁`, and replace one of its vertices by its orthocenter, yielding triangle `t₂` (with vertices not necessarily listed in the same order). Then an altitude of `t₂` from a vertex that was not replaced is the corresponding side of `t₁`. -/ theorem altitude_replace_orthocenter_eq_affine_span {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {t₁ : triangle ℝ P} {t₂ : triangle ℝ P} {i₁ : fin (bit1 1)} {i₂ : fin (bit1 1)} {i₃ : fin (bit1 1)} {j₁ : fin (bit1 1)} {j₂ : fin (bit1 1)} {j₃ : fin (bit1 1)} (hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃) (hj₂₃ : j₂ ≠ j₃) (h₁ : simplex.points t₂ j₁ = orthocenter t₁) (h₂ : simplex.points t₂ j₂ = simplex.points t₁ i₂) (h₃ : simplex.points t₂ j₃ = simplex.points t₁ i₃) : simplex.altitude t₂ j₂ = affine_span ℝ (insert (simplex.points t₁ i₁) (singleton (simplex.points t₁ i₂))) := sorry /-- Suppose we are given a triangle `t₁`, and replace one of its vertices by its orthocenter, yielding triangle `t₂` (with vertices not necessarily listed in the same order). Then the orthocenter of `t₂` is the vertex of `t₁` that was replaced. -/ theorem orthocenter_replace_orthocenter_eq_point {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {t₁ : triangle ℝ P} {t₂ : triangle ℝ P} {i₁ : fin (bit1 1)} {i₂ : fin (bit1 1)} {i₃ : fin (bit1 1)} {j₁ : fin (bit1 1)} {j₂ : fin (bit1 1)} {j₃ : fin (bit1 1)} (hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃) (hj₂₃ : j₂ ≠ j₃) (h₁ : simplex.points t₂ j₁ = orthocenter t₁) (h₂ : simplex.points t₂ j₂ = simplex.points t₁ i₂) (h₃ : simplex.points t₂ j₃ = simplex.points t₁ i₃) : orthocenter t₂ = simplex.points t₁ i₁ := sorry end triangle end affine namespace euclidean_geometry /-- Four points form an orthocentric system if they consist of the vertices of a triangle and its orthocenter. -/ def orthocentric_system {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : set P) := ∃ (t : affine.triangle ℝ P), ¬affine.triangle.orthocenter t ∈ set.range (affine.simplex.points t) ∧ s = insert (affine.triangle.orthocenter t) (set.range (affine.simplex.points t)) /-- This is an auxiliary lemma giving information about the relation of two triangles in an orthocentric system; it abstracts some reasoning, with no geometric content, that is common to some other lemmas. Suppose the orthocentric system is generated by triangle `t`, and we are given three points `p` in the orthocentric system. Then either we can find indices `i₁`, `i₂` and `i₃` for `p` such that `p i₁` is the orthocenter of `t` and `p i₂` and `p i₃` are points `j₂` and `j₃` of `t`, or `p` has the same points as `t`. -/ theorem exists_of_range_subset_orthocentric_system {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {t : affine.triangle ℝ P} (ho : ¬affine.triangle.orthocenter t ∈ set.range (affine.simplex.points t)) {p : fin (bit1 1) → P} (hps : set.range p ⊆ insert (affine.triangle.orthocenter t) (set.range (affine.simplex.points t))) (hpi : function.injective p) : (∃ (i₁ : fin (bit1 1)), ∃ (i₂ : fin (bit1 1)), ∃ (i₃ : fin (bit1 1)), ∃ (j₂ : fin (bit1 1)), ∃ (j₃ : fin (bit1 1)), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ (∀ (i : fin (bit1 1)), i = i₁ ∨ i = i₂ ∨ i = i₃) ∧ p i₁ = affine.triangle.orthocenter t ∧ j₂ ≠ j₃ ∧ affine.simplex.points t j₂ = p i₂ ∧ affine.simplex.points t j₃ = p i₃) ∨ set.range p = set.range (affine.simplex.points t) := sorry /-- For any three points in an orthocentric system generated by triangle `t`, there is a point in the subspace spanned by the triangle from which the distance of all those three points equals the circumradius. -/ theorem exists_dist_eq_circumradius_of_subset_insert_orthocenter {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {t : affine.triangle ℝ P} (ho : ¬affine.triangle.orthocenter t ∈ set.range (affine.simplex.points t)) {p : fin (bit1 1) → P} (hps : set.range p ⊆ insert (affine.triangle.orthocenter t) (set.range (affine.simplex.points t))) (hpi : function.injective p) : ∃ (c : P), ∃ (H : c ∈ affine_span ℝ (set.range (affine.simplex.points t))), ∀ (p₁ : P), p₁ ∈ set.range p → dist p₁ c = affine.simplex.circumradius t := sorry /-- Any three points in an orthocentric system are affinely independent. -/ theorem orthocentric_system.affine_independent {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : set P} (ho : orthocentric_system s) {p : fin (bit1 1) → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := sorry /-- Any three points in an orthocentric system span the same subspace as the whole orthocentric system. -/ theorem affine_span_of_orthocentric_system {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : set P} (ho : orthocentric_system s) {p : fin (bit1 1) → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_span ℝ (set.range p) = affine_span ℝ s := sorry /-- All triangles in an orthocentric system have the same circumradius. -/ theorem orthocentric_system.exists_circumradius_eq {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : set P} (ho : orthocentric_system s) : ∃ (r : ℝ), ∀ (t : affine.triangle ℝ P), set.range (affine.simplex.points t) ⊆ s → affine.simplex.circumradius t = r := sorry /-- Given any triangle in an orthocentric system, the fourth point is its orthocenter. -/ theorem orthocentric_system.eq_insert_orthocenter {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : set P} (ho : orthocentric_system s) {t : affine.triangle ℝ P} (ht : set.range (affine.simplex.points t) ⊆ s) : s = insert (affine.triangle.orthocenter t) (set.range (affine.simplex.points t)) := sorry
bb8d7eaf372de3f6451f6318cd7d357443a32a0d
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/dlist/basic.lean
80ad4f332badcc9acf41ae9bb31b3ccd853bf78b
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
388
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.dlist /-- Concatenates a list of difference lists to form a single difference list. Similar to `list.join`. -/ def dlist.join {α : Type*} : list (dlist α) → dlist α | [] := dlist.empty | (x :: xs) := x ++ dlist.join xs
9d1a43bf71c134368850b7bd361d00115c3daa17
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/sheaves/forget_auto.lean
fe5400e9542bf77e162bc83f6dbbd86fd60c2c7d
[]
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,488
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.sheaves.sheaf import Mathlib.category_theory.limits.preserves.shapes.products import Mathlib.category_theory.limits.types import Mathlib.PostPort universes u₁ v u₂ namespace Mathlib /-! # Checking the sheaf condition on the underlying presheaf of types. If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. ## References * https://stacks.math.columbia.edu/tag/0073 -/ namespace Top namespace presheaf namespace sheaf_condition /-- When `G` preserves limits, the sheaf condition diagram for `F` composed with `G` is naturally isomorphic to the sheaf condition diagram for `F ⋙ G`. -/ def diagram_comp_preserves_limits {C : Type u₁} [category_theory.category C] [category_theory.limits.has_limits C] {D : Type u₂} [category_theory.category D] [category_theory.limits.has_limits D] (G : C ⥤ D) [category_theory.limits.preserves_limits G] {X : Top} (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) : sheaf_condition_equalizer_products.diagram F U ⋙ G ≅ sheaf_condition_equalizer_products.diagram (F ⋙ G) U := category_theory.nat_iso.of_components (fun (X_1 : category_theory.limits.walking_parallel_pair) => category_theory.limits.walking_parallel_pair.cases_on X_1 (category_theory.limits.preserves_product.iso G fun (i : ι) => category_theory.functor.obj F (opposite.op (U i))) (category_theory.limits.preserves_product.iso G fun (p : ι × ι) => category_theory.functor.obj F (opposite.op (U (prod.fst p) ⊓ U (prod.snd p))))) sorry /-- When `G` preserves limits, the image under `G` of the sheaf condition fork for `F` is the sheaf condition fork for `F ⋙ G`, postcomposed with the inverse of the natural isomorphism `diagram_comp_preserves_limits`. -/ def map_cone_fork {C : Type u₁} [category_theory.category C] [category_theory.limits.has_limits C] {D : Type u₂} [category_theory.category D] [category_theory.limits.has_limits D] (G : C ⥤ D) [category_theory.limits.preserves_limits G] {X : Top} (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) : category_theory.functor.map_cone G (sheaf_condition_equalizer_products.fork F U) ≅ category_theory.functor.obj (category_theory.limits.cones.postcompose (category_theory.iso.inv (diagram_comp_preserves_limits G F U))) (sheaf_condition_equalizer_products.fork (F ⋙ G) U) := category_theory.limits.cones.ext (category_theory.iso.refl (category_theory.limits.cone.X (category_theory.functor.map_cone G (sheaf_condition_equalizer_products.fork F U)))) sorry end sheaf_condition /-- If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. Another useful example is the forgetful functor `TopCommRing ⥤ Top`. See https://stacks.math.columbia.edu/tag/0073. In fact we prove a stronger version with arbitrary complete target category. -/ def sheaf_condition_equiv_sheaf_condition_comp {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (G : C ⥤ D) [category_theory.reflects_isomorphisms G] [category_theory.limits.has_limits C] [category_theory.limits.has_limits D] [category_theory.limits.preserves_limits G] {X : Top} (F : presheaf C X) : sheaf_condition F ≃ sheaf_condition (F ⋙ G) := sorry end Mathlib
3e3cb877fd07982dc50567cd7e1c13b7f9eb3371
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/smap.lean
40f511657eb556530b0ab38b33c27d1f7b8e046e
[ "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
657
lean
import init.lean.smap abbrev Map : Type := Lean.SMap Nat Bool (λ a b, a < b) @[extern "lean_smap_foreach_test"] constant foreachTest : Map → Nat := default _ def test1 (n₁ n₂ : Nat) : IO Unit := let m : Map := {} in let m := n₁.fold (λ i (m : Map), m.insert i (i % 2 == 0)) m in let m := m.switch in let m := n₂.fold (λ i (m : Map), m.insert (i+n₁) (i % 3 == 0)) m in do IO.println (foreachTest m), n₁.mfor $ λ i, IO.println (i, (m.find i)), n₂.mfor $ λ i, IO.println (i+n₁, (m.find (i+n₁))), IO.println (m.foldStage2 (λ kvs k v, (k, v)::kvs) []) def main (xs : List String) : IO Unit := test1 xs.head.toNat xs.tail.head.toNat
1d1ef8edde98d72f4e668b96ea56aa5939da34a2
c39706ea6783f804f4403b8f001320a502de6f5a
/fabstract/Green_B_and_Tao_T_ArithmeticProgressionsInPrimes/fabstract.lean
ecfbcce0ff1672cb1422f388f4857139a30024d4
[ "CC-BY-4.0" ]
permissive
semorrison/formalabstracts
bb888dc605e789f4ef1d83635f3b8b9540dd0157
e547f5939875ac6677b01ec6086d40992fa92629
refs/heads/master
1,609,531,064,153
1,501,856,066,000
1,501,856,066,000
98,728,403
0
0
null
1,501,327,991,000
1,501,327,991,000
null
UTF-8
Lean
false
false
824
lean
import meta_data namespace Green_B_and_Tao_T_ArithmeticProgressionsInPrimes def prime (n : nat) : Prop := n > 1 ∧ (∀ m < n, (m = 0) ∨ (m = 1) ∨ (n % m ≠ 0)) -- A statement of Green & Tao's theorem about arithmetic progressions in primes axiom arithmetic_progressions_in_primes : ∀ n k : nat, ∃ m ≥ n, ∃ r ≥ 1, ∀ i < k, prime (m + i * r) -- They also prove various stronger statements; this is an important and easy to state consequence. definition fabstract : meta_data := { description := "The primes contain arbitrarily long arithmetic progressions", authors := [ {name := "Ben Green"}, {name := "Terry Tao"} ], primary := cite.DOI "10.4007/annals.2008.167.481", results := [result.Proof arithmetic_progressions_in_primes] } end Green_B_and_Tao_T_ArithmeticProgressionsInPrimes
9a4f12d093b49b198625c43aa27f2c96e2f28d15
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Util/OptionIO.lean
e1ba2d74baf1496706ee6358d428b806ea75334e
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,625
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ namespace Lake /-- Conceptually identical to `OptionT BaseIO`, but practically more efficient. -/ def OptionIO := EIO PUnit instance : Monad OptionIO := inferInstanceAs (Monad (EIO PUnit)) instance : MonadLift BaseIO OptionIO := inferInstanceAs (MonadLift BaseIO (EIO PUnit)) namespace OptionIO @[inline] def mk (x : EIO PUnit α) : OptionIO α := x @[inline] def toBaseIO (self : OptionIO α) : BaseIO (Option α) := fun s => match self s with | EStateM.Result.ok a s => EStateM.Result.ok (some a) s | EStateM.Result.error _ s => EStateM.Result.ok none s @[inline] def toEIO (self : OptionIO α) : EIO PUnit α := self @[inline] def toIO (f : Unit → IO.Error) (self : OptionIO α) : IO α := self.toEIO.toIO f @[inline] def catchFailure (f : Unit → BaseIO α) (self : OptionIO α) : BaseIO α := self.toEIO.catchExceptions f @[inline] protected def failure : OptionIO α := mk <| throw () @[inline] protected def orElse (self : OptionIO α) (f : Unit → OptionIO α) : OptionIO α := mk <| tryCatch self.toEIO f instance : Alternative OptionIO where failure := OptionIO.failure orElse := OptionIO.orElse @[always_inline] instance OptionIO.finally : MonadFinally OptionIO where tryFinally' := fun x h => do match (← x.toBaseIO) with | some a => h (some a) <&> ((a, ·)) | none => h none *> failure def asTask (self : OptionIO α) (prio := Task.Priority.dedicated) : BaseIO (Task (Option α)) := self.toBaseIO.asTask prio
88b9f484c7d15be14e33af40e8b5987e45d190c4
2fbe653e4bc441efde5e5d250566e65538709888
/src/data/set/lattice.lean
05f6fdb541b9ab74fc8a15720dc02393e2f37f37
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
34,849
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit? -/ import logic.basic data.set.basic data.equiv.basic import order.complete_boolean_algebra category.basic import tactic.finish data.sigma.basic order.galois_connection open function tactic set lattice auto universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {ι' : Sort y} namespace set instance lattice_set : complete_lattice (set α) := { le := (⊆), lt := (⊂), sup := (∪), inf := (∩), top := univ, bot := ∅, Sup := λs, {a | ∃ t ∈ s, a ∈ t }, Inf := λs, {a | ∀ t ∈ s, a ∈ t }, le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := assume s t t_in a h, h _ t_in, .. (infer_instance : complete_lattice (α → Prop)) } instance : distrib_lattice (set α) := { le_sup_inf := λ s t u x, or_and_distrib_left.2, ..set.lattice_set } lemma monotone_image {f : α → β} : monotone (image f) := assume s t, assume h : s ⊆ t, image_subset _ h theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∩ g x) := assume b₁ b₂ h, inter_subset_inter (hf h) (hg h) theorem monotone_union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∪ g x) := assume b₁ b₂ h, union_subset_union (hf h) (hg h) theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) := assume a a' h b, hp b h section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := assume a b, image_subset_iff def kern_image (f : α → β) (s : set α) : set β := {y | ∀x, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := assume a b, ⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, assume h x (hx : f x ∈ a), h hx x rfl⟩ end galois_connection /- union and intersection over a family of sets indexed by a type -/ /-- Indexed union of a family of sets -/ @[reducible] def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ @[reducible] def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate ∃i, ... ∧ i = t ∧ ... @[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i := ⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ set.lattice_set _ _ h theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) := ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) := mem_Inter.2 theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := -- TODO: should be simpler when sets' order is based on lattices @le_infi (set β) _ set.lattice_set _ _ h theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := set.subset.trans (set.Inter_subset s i) h lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ (⋂ i, t i) := set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i) lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi theorem Union_const [inhabited ι] (s : set β) : (⋃ i:ι, s) = s := ext $ by simp theorem Inter_const [inhabited ι] (s : set β) : (⋂ i:ι, s) = s := ext $ by simp @[simp] -- complete_boolean_algebra theorem compl_Union (s : ι → set β) : - (⋃ i, s i) = (⋂ i, - s i) := ext (by simp) -- classical -- complete_boolean_algebra theorem compl_Inter (s : ι → set β) : -(⋂ i, s i) = (⋃ i, - s i) := ext (λ x, by simp [classical.not_forall]) -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = - (⋂ i, - s i) := by simp [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = - (⋃ i, -s i) := by simp [compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := ext $ by simp [forall_and_distrib] theorem union_Union [inhabited ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := by rw [Union_union_distrib, Union_const] theorem Union_union [inhabited ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := by rw [Union_union_distrib, Union_const] theorem inter_Inter [inhabited ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := by rw [Inter_inter_distrib, Inter_const] theorem Inter_inter [inhabited ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := by rw [Inter_inter_distrib, Inter_const] -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := ext $ assume x, by simp [classical.forall_or_distrib_left] theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [inhabited ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl /- bounded unions and intersections -/ theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := by simp; exact ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := by simp; assumption theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) : (⋃ x ∈ s, u x) ⊆ t := show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices from supr_le $ assume x, supr_le (h x) theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) : t ⊆ (⋂ x ∈ s, u x) := subset_Inter $ assume x, subset_Inter $ h x theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := show u x ≤ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := show (⨅x ∈ s, t x) ≤ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_bInter (λ x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) := bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) := subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_eq_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) = (⋃ x : s, t x.1) := set.ext $ by simp theorem bInter_eq_Inter (s : set α) (t : α → set β) : (⋂ x ∈ s, t x) = (⋂ x : s, t x.1) := set.ext $ by simp @[simp] theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false. from infi_emptyset @[simp] theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ -- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := show (⨅ x ∈ ({a} : set α), s x) = s a, by simp theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x), from infi_union -- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work @[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := begin rw insert_eq, simp [bInter_union] end -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by rw insert_of_has_insert; simp [inter_comm] @[simp] theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset @[simp] theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union -- TODO(Jeremy): once again, simp doesn't do it alone. @[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw [insert_eq], simp [bUnion_union] end theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by rw insert_of_has_insert; simp [union_comm] @[simp] -- complete_boolean_algebra theorem compl_bUnion (s : set α) (t : α → set β) : - (⋃ i ∈ s, t i) = (⋂ i ∈ s, - t i) := ext (λ x, by simp) -- classical -- complete_boolean_algebra theorem compl_bInter (s : set α) (t : α → set β) : -(⋂ i ∈ s, t i) = (⋃ i ∈ s, - t i) := ext (λ x, by simp [classical.not_forall]) theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) : u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i := begin ext x, simp only [exists_prop, mem_Union, mem_inter_eq], exact ⟨λ ⟨hx, ⟨i, is, xi⟩⟩, ⟨i, is, hx, xi⟩, λ ⟨i, is, hx, xi⟩, ⟨hx, ⟨i, is, xi⟩⟩⟩ end theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) : (⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) := by simp [@inter_comm _ _ u, inter_bUnion] /-- Intersection of a set of sets. -/ @[reducible] def sInter (S : set (set α)) : set α := Inf S prefix `⋂₀`:110 := sInter theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ⟨ht, hx⟩⟩ @[simp] theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t := ⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := (sUnion_insert _ _).trans $ by rw [union_comm, sUnion_singleton] theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := (sInter_insert _ _).trans $ by rw [inter_comm, sInter_singleton] @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image @[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := Sup_range @[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := Inf_range lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = @set.univ α ↔ ∀ a, ∃ b ∈ c, a ∈ b := ⟨λ H a, let ⟨b, hm, hb⟩ := mem_sUnion.1 $ by rw H; exact mem_univ a in ⟨b, hm, hb⟩, λ H, set.univ_subset_iff.1 $ λ x hx, let ⟨b, hm, hb⟩ := H x in set.mem_sUnion_of_mem hb hm⟩ theorem compl_sUnion (S : set (set α)) : - ⋃₀ S = ⋂₀ (compl '' S) := set.ext $ assume x, ⟨assume : ¬ (∃s∈S, x ∈ s), assume s h, match s, h with ._, ⟨t, hs, rfl⟩ := assume h, this ⟨t, hs, h⟩ end, assume : ∀s, s ∈ compl '' S → x ∈ s, assume ⟨t, tS, xt⟩, this (compl t) (mem_image_of_mem _ tS) xt⟩ -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = - ⋂₀ (compl '' S) := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : - ⋂₀ S = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_comp_sUnion_compl (S : set (set α)) : ⋂₀ S = -(⋃₀ (compl '' S)) := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintros ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {ι₂ : Sort*} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h @[simp] lemma Union_of_singleton (α : Type u) : (⋃(x : α), {x}) = @set.univ α := ext $ λ x, ⟨λ h, ⟨⟩, λ h, ⟨{x}, ⟨⟨x, rfl⟩, mem_singleton x⟩⟩⟩ theorem bUnion_subset_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) ⊆ (⋃ x, t x) := Union_subset_Union $ λ i, Union_subset $ λ h, by refl lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := set.ext $ by simp lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := set.ext $ by simp lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i.1) := set.ext $ λ x, by simp lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i.1) := set.ext $ λ x, by simp lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.exists_bool, or_comm] lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.forall_bool, and_comm] instance : complete_boolean_algebra (set α) := { neg := compl, sub := (\), inf_neg_eq_bot := assume s, ext $ assume x, ⟨assume ⟨h, nh⟩, nh h, false.elim⟩, sup_neg_eq_top := assume s, ext $ assume x, ⟨assume h, trivial, assume _, classical.em $ x ∈ s⟩, le_sup_inf := distrib_lattice.le_sup_inf, sub_eq := assume x y, rfl, infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t), by simp; exact assume h, or.imp_right (assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn) (classical.em $ x ∈ s), inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b), by simp [-and_imp, and.left_comm], ..set.lattice_set } lemma sInter_union_sInter {S T : set (set α)} : (⋂₀S) ∪ (⋂₀T) = (⋂p ∈ set.prod S T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀s) ∩ (⋃₀t) = (⋃p ∈ set.prod s t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup lemma sInter_bUnion {S : set (set α)} {T : set α → set (set α)} (hT : ∀s∈S, s = ⋂₀ T s) : ⋂₀ (⋃s∈S, T s) = ⋂₀ S := begin ext, simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib], split, { assume H s sS, rw [hT s sS, mem_sInter], assume t tTs, apply H t s sS tTs }, { assume H t s sS tTs, have xs : x ∈ s := H s sS, have : s ⊆ t, { have Z := hT s sS, rw sInter_eq_bInter at Z, rw Z, apply bInter_subset_of_mem, exact tTs }, exact this xs } end lemma sUnion_bUnion {S : set (set α)} {T : set α → set (set α)} (hT : ∀s∈S, s = ⋃₀ T s) : ⋃₀ (⋃s∈S, T s) = ⋃₀ S := begin ext, simp only [exists_prop, set.mem_Union, set.mem_set_of_eq], split, { rintros ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩, refine ⟨s, ⟨sS, _⟩⟩, rw hT s sS, exact subset_sUnion_of_mem tTs xt }, { rintros ⟨s, ⟨sS, xs⟩⟩, rw hT s sS at xs, rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩, exact ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩ } end lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀(s : C), β → s} (hf : ∀(s : C), surjective (f s)) : (⋃(y : β), range (λ(s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { rintro ⟨s, ⟨y, rfl⟩, ⟨⟨s, hs⟩, rfl⟩⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 }, { rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨⟨s, hs⟩, _⟩⟩, exact congr_arg subtype.val hy } end lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α) {f : ∀(x : ι), β → C x} (hf : ∀(x : ι), surjective (f x)) : (⋃(y : β), range (λ(x : ι), (f x y).val)) = ⋃x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, ⟨i, rfl⟩⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, refine ⟨y, ⟨i, congr_arg subtype.val hy⟩⟩ } end @[simp] theorem sub_eq_diff (s t : set α) : s - t = s \ t := rfl section variables {p : Prop} {μ : p → set α} @[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp @[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp @[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp @[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp @[simp] lemma Union_empty {ι : Sort*} : (⋃i:ι, ∅:set α) = ∅ := supr_bot @[simp] lemma Inter_univ {ι : Sort*} : (⋂i:ι, univ:set α) = univ := infi_top end section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) := begin apply set.ext, intro x, simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right], exact exists_swap end lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) := set.ext $ assume ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃i, {f i}) := set.ext $ assume a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃i∈s, {f i}) := set.ext $ assume b, by simp [@eq_comm β b] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃x ∈ range f, g x) = (⋃y, g (f y)) := by rw [← sUnion_image, ← range_comp, sUnion_range] lemma bInter_range {f : ι → α} {g : α → set β} : (⋂x ∈ range f, g x) = (⋂y, g (f y)) := by rw [← sInter_image, ← range_comp, sInter_range] variables {s : set γ} {f : γ → α} {g : α → set β} lemma bUnion_image : (⋃x∈ (f '' s), g x) = (⋃y ∈ s, g (f y)) := by rw [← sUnion_image, ← image_comp, sUnion_image] lemma bInter_image : (⋂x∈ (f '' s), g x) = (⋂y ∈ s, g (f y)) := by rw [← sInter_image, ← image_comp, sInter_image] end image section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h @[simp] theorem preimage_Union {ι : Sort w} {f : α → β} {s : ι → set β} : preimage f (⋃i, s i) = (⋃i, preimage f (s i)) := set.ext $ by simp [preimage] theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} : preimage f (⋃i ∈ s, t i) = (⋃i ∈ s, preimage f (t i)) := by simp @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : preimage f (⋃₀ s) = (⋃t ∈ s, preimage f t) := set.ext $ by simp [preimage] lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} : f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) := by ext; simp end preimage section seq def seq (s : set (α → β)) (t : set α) : set β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) := iff.intro (assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (assume c, iff.intro _ _), { rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : set.prod s t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp] end seq theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λx, set.prod (f x) (g x)) := assume a b h, prod_mono (hf h) (hg h) instance : monad set := { pure := λ(α : Type u) a, {a}, bind := λ(α β : Type u) s f, ⋃i∈s, f i, seq := λ(α β : Type u), set.seq, map := λ(α β : Type u), set.image } instance : is_lawful_monad set := { pure_bind := assume α β x f, by simp, bind_assoc := assume α β γ s f g, set.ext $ assume a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := assume α, id_map, bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := assume α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ assume α β s t, prod_image_seq_comm s t ⟩ section monad variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')} @[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl @[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl end monad section pi lemma pi_def {α : Type*} {π : α → Type*} (i : set α) (s : Πa, set (π a)) : pi i s = (⋂ a∈i, ((λf:(Πa, π a), f a) ⁻¹' (s a))) := by ext; simp [pi] end pi end set /- disjoint sets -/ section disjoint variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] theorem disjoint.symm {a b : α} : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := disjoint_iff.2 bot_inf_eq @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := disjoint_iff.2 inf_bot_eq theorem disjoint_mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint_mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint_mono h (le_refl _) theorem disjoint_mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint_mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma ne_of_disjoint {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } end disjoint namespace set protected theorem disjoint_iff {s t : set α} : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl lemma not_disjoint_iff {s t : set α} : ¬disjoint s t ↔ ∃x, x ∈ s ∧ x ∈ t := (not_congr (set.disjoint_iff.trans subset_empty_iff)).trans ne_empty_iff_nonempty lemma disjoint_left {s t : set α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩ theorem disjoint_right {s t : set α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) theorem disjoint_compl (s : set α) : disjoint s (-s) := assume a ⟨h₁, h₂⟩, h₂ h₁ theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀b∈s, ∀c∈t, f b ≠ g c) : disjoint (f '' s) (g '' t) := by rintros a ⟨⟨b, hb, eq⟩, ⟨c, hc, rfl⟩⟩; exact h b hb c hc eq def pairwise_disjoint (s : set (set α)) : Prop := pairwise_on s disjoint lemma pairwise_disjoint_subset {s t : set (set α)} (h : s ⊆ t) (ht : pairwise_disjoint t) : pairwise_disjoint s := pairwise_on.mono h ht lemma pairwise_disjoint_range {s : set (set α)} (f : s → set α) (hf : ∀(x : s), f x ⊆ x.1) (ht : pairwise_disjoint s) : pairwise_disjoint (range f) := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine disjoint_mono (hf x) (hf y) (ht _ x.2 _ y.2 _), intro h, apply hxy, apply congr_arg f, exact subtype.eq h end /- warning: classical -/ lemma pairwise_disjoint_elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α} (hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y := classical.not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩ end set namespace set variables (t : α → set β) def sigma_to_Union (x : Σi, t i) : (⋃i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma surjective_sigma_to_Union : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, ⟨b, hb⟩⟩, rfl⟩ lemma injective_sigma_to_Union (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, ⟨b₁, h₁⟩⟩ ⟨a₂, ⟨b₂, h₂⟩⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, h _ _ ne this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma bijective_sigma_to_Union (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨injective_sigma_to_Union t h, surjective_sigma_to_Union t⟩ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : (⋃i, t i) ≃ (Σi, t i) := (equiv.of_bijective $ bijective_sigma_to_Union t h).symm noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) := equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $ assume ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ assume eq, ne $ subtype.eq eq end set
e592d5f210460c931d2e94c2b1e090701c6426ee
b074a51e20fdb737b2d4c635dd292fc54685e010
/src/data/padics/padic_norm.lean
ca4423a0ba30b88b5e6ba5fceb6b4150e7a5baf9
[ "Apache-2.0" ]
permissive
minchaowu/mathlib
2daf6ffdb5a56eeca403e894af88bcaaf65aec5e
879da1cf04c2baa9eaa7bd2472100bc0335e5c73
refs/heads/master
1,609,628,676,768
1,564,310,105,000
1,564,310,105,000
99,461,307
0
0
null
null
null
null
UTF-8
Lean
false
false
16,925
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.rat.basic algebra.gcd_domain algebra.field_power import ring_theory.multiplicity tactic.ring import data.real.cau_seq import tactic.norm_cast /-! # p-adic norm This file defines the p-adic valuation and the p-adic norm on ℚ. The p-adic valuation on ℚ is the difference of the multiplicities of `p` in the numerator and denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate assumptions on p. The valuation induces a norm on ℚ. This norm is a nonarchimedean absolute value. It takes values in {0} ∪ {1/p^k | k ∈ ℤ}. ## Notations This file uses the local notation `/.` for `rat.mk`. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking (prime p) as a type class argument. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * https://en.wikipedia.org/wiki/P-adic_number ## Tags p-adic, p adic, padic, norm, valuation -/ universe u open nat attribute [class] nat.prime local infix `/.`:70 := rat.mk open multiplicity /-- For `p ≠ 1`, the p-adic valuation of an integer `z ≠ 0` is the largest natural number `n` such that p^n divides z. `padic_val_rat` defines the valuation of a rational `q` to be the valuation of `q.num` minus the valuation of `q.denom`. If `q = 0` or `p = 1`, then `padic_val_rat p q` defaults to 0. -/ def padic_val_rat (p : ℕ) (q : ℚ) : ℤ := if h : q ≠ 0 ∧ p ≠ 1 then (multiplicity (p : ℤ) q.num).get (multiplicity.finite_int_iff.2 ⟨h.2, rat.num_ne_zero_of_ne_zero h.1⟩) - (multiplicity (p : ℤ) q.denom).get (multiplicity.finite_int_iff.2 ⟨h.2, by exact_mod_cast rat.denom_ne_zero _⟩) else 0 /-- A simplification of the definition of `padic_val_rat p q` when `q ≠ 0` and `p` is prime. -/ lemma padic_val_rat_def (p : ℕ) [hp : p.prime] {q : ℚ} (hq : q ≠ 0) : padic_val_rat p q = (multiplicity (p : ℤ) q.num).get (finite_int_iff.2 ⟨hp.ne_one, rat.num_ne_zero_of_ne_zero hq⟩) - (multiplicity (p : ℤ) q.denom).get (finite_int_iff.2 ⟨hp.ne_one, by exact_mod_cast rat.denom_ne_zero _⟩) := dif_pos ⟨hq, hp.ne_one⟩ namespace padic_val_rat open multiplicity section padic_val_rat variables {p : ℕ} /-- `padic_val_rat p q` is symmetric in `q`. -/ @[simp] protected lemma neg (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q := begin unfold padic_val_rat, split_ifs, { simp [-add_comm]; refl }, { exfalso, simp * at * }, { exfalso, simp * at * }, { refl } end /-- `padic_val_rat p 1` is 0 for any `p`. -/ @[simp] protected lemma one : padic_val_rat p 1 = 0 := by unfold padic_val_rat; split_ifs; simp * /-- For `p ≠ 0, p ≠ 1, `padic_val_rat p p` is 1. -/ @[simp] lemma padic_val_rat_self (hp : 1 < p) : padic_val_rat p p = 1 := by unfold padic_val_rat; split_ifs; simp [*, nat.one_lt_iff_ne_zero_and_ne_one] at * /-- The p-adic value of an integer `z ≠ 0` is the multiplicity of `p` in `z`. -/ lemma padic_val_rat_of_int (z : ℤ) (hp : p ≠ 1) (hz : z ≠ 0) : padic_val_rat p (z : ℚ) = (multiplicity (p : ℤ) z).get (finite_int_iff.2 ⟨hp, hz⟩) := by rw [padic_val_rat, dif_pos]; simp *; refl end padic_val_rat section padic_val_rat open multiplicity variables (p : ℕ) [p_prime : nat.prime p] include p_prime /-- The multiplicity of `p : ℕ` in `a : ℤ` is finite exactly when `a ≠ 0`. -/ lemma finite_int_prime_iff {p : ℕ} [p_prime : p.prime] {a : ℤ} : finite (p : ℤ) a ↔ a ≠ 0 := by simp [finite_int_iff, ne.symm (ne_of_lt (p_prime.gt_one))] /-- A rewrite lemma for `padic_val_rat p q` when `q` is expressed in terms of `rat.mk`. -/ protected lemma defn {q : ℚ} {n d : ℤ} (hqz : q ≠ 0) (qdf : q = n /. d) : padic_val_rat p q = (multiplicity (p : ℤ) n).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt p_prime.gt_one, λ hn, by simp * at *⟩) - (multiplicity (p : ℤ) d).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt p_prime.gt_one, λ hd, by simp * at *⟩) := have hn : n ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqz qdf, have hd : d ≠ 0, from rat.mk_denom_ne_zero_of_ne_zero hqz qdf, let ⟨c, hc1, hc2⟩ := rat.num_denom_mk hn hd qdf in by rw [padic_val_rat, dif_pos]; simp [hc1, hc2, multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime), (ne.symm (ne_of_lt p_prime.gt_one)), hqz] /-- A rewrite lemma for `padic_val_rat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q * r) = padic_val_rat p q + padic_val_rat p r := have q*r = (q.num * r.num) /. (↑q.denom * ↑r.denom), by rw_mod_cast rat.mul_num_denom, have hq' : q.num /. q.denom ≠ 0, by rw ← rat.num_denom q; exact hq, have hr' : r.num /. r.denom ≠ 0, by rw ← rat.num_denom r; exact hr, have hp' : _root_.prime (p : ℤ), from nat.prime_iff_prime_int.1 p_prime, begin rw [padic_val_rat.defn p (mul_ne_zero hq hr) this], conv_rhs { rw [rat.num_denom q, padic_val_rat.defn p hq', rat.num_denom r, padic_val_rat.defn p hr'] }, rw [multiplicity.mul' hp', multiplicity.mul' hp']; simp end /-- A rewrite lemma for `padic_val_rat p (q^k) with condition `q ≠ 0`. -/ protected lemma pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} : padic_val_rat p (q ^ k) = k * padic_val_rat p q := by induction k; simp [*, padic_val_rat.mul _ hq (pow_ne_zero _ hq), _root_.pow_succ, add_mul] /-- A rewrite lemma for `padic_val_rat p (q⁻¹)` with condition `q ≠ 0`. -/ protected lemma inv {q : ℚ} (hq : q ≠ 0) : padic_val_rat p (q⁻¹) = -padic_val_rat p q := by rw [eq_neg_iff_add_eq_zero, ← padic_val_rat.mul p (inv_ne_zero hq) hq, inv_mul_cancel hq, padic_val_rat.one] /-- A rewrite lemma for `padic_val_rat p (q / r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r := by rw [div_eq_mul_inv, padic_val_rat.mul p hq (inv_ne_zero hr), padic_val_rat.inv p hr, sub_eq_add_neg] /-- A condition for `padic_val_rat p (n₁ / d₁) ≤ padic_val_rat p (n₂ / d₂), in terms of divisibility by `p^n`. -/ lemma padic_val_rat_le_padic_val_rat_iff {n₁ n₂ d₁ d₂ : ℤ} (hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0) (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) : padic_val_rat p (n₁ /. d₁) ≤ padic_val_rat p (n₂ /. d₂) ↔ ∀ (n : ℕ), ↑p ^ n ∣ n₁ * d₂ → ↑p ^ n ∣ n₂ * d₁ := have hf1 : finite (p : ℤ) (n₁ * d₂), from finite_int_prime_iff.2 (mul_ne_zero hn₁ hd₂), have hf2 : finite (p : ℤ) (n₂ * d₁), from finite_int_prime_iff.2 (mul_ne_zero hn₂ hd₁), by conv { to_lhs, rw [padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₁ hd₁) rfl, padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₂ hd₂) rfl, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le], norm_cast, rw [← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime) hf1, add_comm, ← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime) hf2, enat.get_le_get, multiplicity_le_multiplicity_iff] } /-- Sufficient conditions to show that the p-adic valuation of `q` is less than or equal to the p-adic vlauation of `q + r`. -/ theorem le_padic_val_rat_add_of_le {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) (h : padic_val_rat p q ≤ padic_val_rat p r) : padic_val_rat p q ≤ padic_val_rat p (q + r) := have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hq, have hqd : (q.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _, have hrn : r.num ≠ 0, from rat.num_ne_zero_of_ne_zero hr, have hrd : (r.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _, have hqdv : q.num /. q.denom ≠ 0, from rat.mk_ne_zero_of_ne_zero hqn hqd, have hrdv : r.num /. r.denom ≠ 0, from rat.mk_ne_zero_of_ne_zero hrn hrd, have hqreq : q + r = (((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ)), from rat.add_num_denom _ _, have hqrd : q.num * ↑(r.denom) + ↑(q.denom) * r.num ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqr hqreq, begin conv_lhs { rw rat.num_denom q }, rw [hqreq, padic_val_rat_le_padic_val_rat_iff p hqn hqrd hqd (mul_ne_zero hqd hrd), ← multiplicity_le_multiplicity_iff, mul_left_comm, multiplicity.mul (nat.prime_iff_prime_int.1 p_prime), add_mul], rw [rat.num_denom q, rat.num_denom r, padic_val_rat_le_padic_val_rat_iff p hqn hrn hqd hrd, ← multiplicity_le_multiplicity_iff] at h, calc _ ≤ min (multiplicity ↑p (q.num * ↑(r.denom) * ↑(q.denom))) (multiplicity ↑p (↑(q.denom) * r.num * ↑(q.denom))) : (le_min (by rw [@multiplicity.mul _ _ _ _ (_ * _) _ (nat.prime_iff_prime_int.1 p_prime), add_comm]) (by rw [mul_assoc, @multiplicity.mul _ _ _ _ (q.denom : ℤ) (_ * _) (nat.prime_iff_prime_int.1 p_prime)]; exact add_le_add_left' h)) ... ≤ _ : min_le_multiplicity_add end /-- The minimum of the valuations of `q` and `r` is less than or equal to the valuation of `q + r`. -/ theorem min_le_padic_val_rat_add {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) : min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) := (le_total (padic_val_rat p q) (padic_val_rat p r)).elim (λ h, by rw [min_eq_left h]; exact le_padic_val_rat_add_of_le _ hq hr hqr h) (λ h, by rw [min_eq_right h, add_comm]; exact le_padic_val_rat_add_of_le _ hr hq (by rwa add_comm) h) end padic_val_rat end padic_val_rat /-- If `q ≠ 0`, the p-adic norm of a rational `q` is `p ^ (-(padic_val_rat p q))`. If `q = 0`, the p-adic norm of `q` is 0. -/ def padic_norm (p : ℕ) (q : ℚ) : ℚ := if q = 0 then 0 else (↑p : ℚ) ^ (-(padic_val_rat p q)) namespace padic_norm section padic_norm open padic_val_rat variables (p : ℕ) [hp : p.prime] include hp /-- The p-adic norm of 0 is 0. -/ @[simp] protected lemma zero : padic_norm p 0 = 0 := by simp [padic_norm] /-- The p-adic norm of 1 is 1. -/ @[simp] protected lemma one : padic_norm p 1 = 1 := by simp [padic_norm] /-- Unfolds the definition of the p-adic norm of `q` when `q ≠ 0`. -/ @[simp] protected lemma eq_fpow_of_nonzero {q : ℚ} (hq : q ≠ 0) : padic_norm p q = p ^ (-(padic_val_rat p q)) := by simp [hq, padic_norm] /-- If `q ≠ 0`, then `padic_norm p q ≠ 0`. -/ protected lemma nonzero {q : ℚ} (hq : q ≠ 0) : padic_norm p q ≠ 0 := begin rw padic_norm.eq_fpow_of_nonzero p hq, apply fpow_ne_zero_of_ne_zero, exact_mod_cast ne_of_gt hp.pos end /-- `padic_norm p` is symmetric. -/ @[simp] protected lemma neg (q : ℚ) : padic_norm p (-q) = padic_norm p q := if hq : q = 0 then by simp [hq] else by simp [padic_norm, hq, hp.gt_one] /-- If the p-adic norm of `q` is 0, then `q` is 0. -/ lemma zero_of_padic_norm_eq_zero {q : ℚ} (h : padic_norm p q = 0) : q = 0 := begin apply by_contradiction, intro hq, unfold padic_norm at h, rw if_neg hq at h, apply absurd h, apply fpow_ne_zero_of_ne_zero, exact_mod_cast hp.ne_zero end /-- The p-adic norm is nonnegative. -/ protected lemma nonneg (q : ℚ) : padic_norm p q ≥ 0 := if hq : q = 0 then by simp [hq] else begin unfold padic_norm; split_ifs, apply fpow_nonneg_of_nonneg, exact_mod_cast nat.zero_le _ end /-- The p-adic norm is multiplicative. -/ @[simp] protected theorem mul (q r : ℚ) : padic_norm p (q*r) = padic_norm p q * padic_norm p r := if hq : q = 0 then by simp [hq] else if hr : r = 0 then by simp [hr] else have q*r ≠ 0, from mul_ne_zero hq hr, have (↑p : ℚ) ≠ 0, by simp [prime.ne_zero hp], by simp [padic_norm, *, padic_val_rat.mul, fpow_add this] /-- The p-adic norm respects division. -/ @[simp] protected theorem div (q r : ℚ) : padic_norm p (q / r) = padic_norm p q / padic_norm p r := if hr : r = 0 then by simp [hr] else eq_div_of_mul_eq _ _ (padic_norm.nonzero _ hr) (by rw [←padic_norm.mul, div_mul_cancel _ hr]) /-- The p-adic norm of an integer is at most 1. -/ protected theorem of_int (z : ℤ) : padic_norm p ↑z ≤ 1 := if hz : z = 0 then by simp [hz] else begin unfold padic_norm, rw [if_neg _], { refine fpow_le_one_of_nonpos _ _, { exact_mod_cast le_of_lt hp.gt_one, }, { rw [padic_val_rat_of_int _ hp.ne_one hz, neg_nonpos], norm_cast, simp }}, exact_mod_cast hz end private lemma nonarchimedean_aux {q r : ℚ} (h : padic_val_rat p q ≤ padic_val_rat p r) : padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) := have hnqp : padic_norm p q ≥ 0, from padic_norm.nonneg _ _, have hnrp : padic_norm p r ≥ 0, from padic_norm.nonneg _ _, if hq : q = 0 then by simp [hq, max_eq_right hnrp, le_max_right] else if hr : r = 0 then by simp [hr, max_eq_left hnqp, le_max_left] else if hqr : q + r = 0 then le_trans (by simpa [hqr] using hnqp) (le_max_left _ _) else begin unfold padic_norm, split_ifs, apply le_max_iff.2, left, apply fpow_le_of_le, { exact_mod_cast le_of_lt hp.gt_one }, { apply neg_le_neg, have : padic_val_rat p q = min (padic_val_rat p q) (padic_val_rat p r), from (min_eq_left h).symm, rw this, apply min_le_padic_val_rat_add; assumption } end /-- The p-adic norm is nonarchimedean: the norm of `p + q` is at most the max of the norm of `p` and the norm of `q`. -/ protected theorem nonarchimedean {q r : ℚ} : padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) := begin wlog hle := le_total (padic_val_rat p q) (padic_val_rat p r) using [q r], exact nonarchimedean_aux p hle end /-- The p-adic norm respects the triangle inequality: the norm of `p + q` is at most the norm of `p` plus the norm of `q`. -/ theorem triangle_ineq (q r : ℚ) : padic_norm p (q + r) ≤ padic_norm p q + padic_norm p r := calc padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) : padic_norm.nonarchimedean p ... ≤ padic_norm p q + padic_norm p r : max_le_add_of_nonneg (padic_norm.nonneg p _) (padic_norm.nonneg p _) /-- The p-adic norm of a difference is at most the max of each component. Restates the archimedean property of the p-adic norm. -/ protected theorem sub {q r : ℚ} : padic_norm p (q - r) ≤ max (padic_norm p q) (padic_norm p r) := by rw [sub_eq_add_neg, ←padic_norm.neg p r]; apply padic_norm.nonarchimedean /-- If the p-adic norms of `q` and `r` are different, then the norm of `q + r` is equal to the max of the norms of `q` and `r`. -/ lemma add_eq_max_of_ne {q r : ℚ} (hne : padic_norm p q ≠ padic_norm p r) : padic_norm p (q + r) = max (padic_norm p q) (padic_norm p r) := begin wlog hle := le_total (padic_norm p r) (padic_norm p q) using [q r], have hlt : padic_norm p r < padic_norm p q, from lt_of_le_of_ne hle hne.symm, have : padic_norm p q ≤ max (padic_norm p (q + r)) (padic_norm p r), from calc padic_norm p q = padic_norm p (q + r - r) : by congr; ring ... ≤ max (padic_norm p (q + r)) (padic_norm p (-r)) : padic_norm.nonarchimedean p ... = max (padic_norm p (q + r)) (padic_norm p r) : by simp, have hnge : padic_norm p r ≤ padic_norm p (q + r), { apply le_of_not_gt, intro hgt, rw max_eq_right_of_lt hgt at this, apply not_lt_of_ge this, assumption }, have : padic_norm p q ≤ padic_norm p (q + r), by rwa [max_eq_left hnge] at this, apply _root_.le_antisymm, { apply padic_norm.nonarchimedean p }, { rw max_eq_left_of_lt hlt, assumption } end /-- The image of `padic_norm p` is {0} ∪ {p^(-n) | n ∈ ℤ}. -/ protected theorem image {q : ℚ} (hq : q ≠ 0) : ∃ n : ℤ, padic_norm p q = p ^ (-n) := ⟨ (padic_val_rat p q), by simp [padic_norm, hq] ⟩ /-- The p-adic norm is an absolute value: positive-definite and multiplicative, satisfying the triangle inequality. -/ instance : is_absolute_value (padic_norm p) := { abv_nonneg := padic_norm.nonneg p, abv_eq_zero := begin intros, constructor; intro, { apply zero_of_padic_norm_eq_zero p, assumption }, { simp [*] } end, abv_add := padic_norm.triangle_ineq p, abv_mul := padic_norm.mul p } /-- If `p^n` divides an integer `z`, then the p-adic norm of `z` is at most `p^(-n)`. -/ lemma le_of_dvd {n : ℕ} {z : ℤ} (hd : ↑(p^n) ∣ z) : padic_norm p z ≤ ↑p ^ (-n : ℤ) := begin unfold padic_norm, split_ifs with hz hz, { apply fpow_nonneg_of_nonneg, exact_mod_cast le_of_lt hp.pos }, { apply fpow_le_of_le, exact_mod_cast le_of_lt hp.gt_one, apply neg_le_neg, rw padic_val_rat_of_int _ hp.ne_one _, { norm_cast, rw [← enat.coe_le_coe, enat.coe_get], apply multiplicity.le_multiplicity_of_pow_dvd, exact_mod_cast hd }, { exact_mod_cast hz }} end end padic_norm end padic_norm
b87396b1d22d47664877ea2e7a82b8d40514fba5
82e44445c70db0f03e30d7be725775f122d72f3e
/archive/100-theorems-list/16_abel_ruffini.lean
0e79ae86ab76a97094c7387d561bc40b5b7fc4fa
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
7,900
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import field_theory.abel_ruffini import analysis.calculus.local_extr /-! Construction of an algebraic number that is not solvable by radicals. The main ingredients are: * `solvable_by_rad.is_solvable'` in `field_theory/abel_ruffini` : an irreducible polynomial with an `is_solvable_by_rad` root has solvable Galois group * `gal_action_hom_bijective_of_prime_degree'` in `field_theory/polynomial_galois_group` : an irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group * `equiv.perm.not_solvable` in `group_theory/solvable` : the symmetric group is not solvable Then all that remains is the construction of a specific polynomial satisfying the conditions of `gal_action_hom_bijective_of_prime_degree'`, which is done in this file. -/ namespace abel_ruffini open function polynomial polynomial.gal ideal local attribute [instance] splits_ℚ_ℂ variables (R : Type*) [comm_ring R] (a b : ℕ) /-- A quintic polynomial that we will show is irreducible -/ noncomputable def Φ : polynomial R := X ^ 5 - C ↑a * X + C ↑b variables {R} @[simp] lemma map_Phi {S : Type*} [comm_ring S] (f : R →+* S) : (Φ R a b).map f = Φ S a b := by simp [Φ] @[simp] lemma coeff_zero_Phi : (Φ R a b).coeff 0 = ↑b := by simp [Φ, coeff_X_pow] @[simp] lemma coeff_five_Phi : (Φ R a b).coeff 5 = 1 := by simp [Φ, coeff_X, coeff_C, -C_eq_nat_cast, -ring_hom.map_nat_cast] variables [nontrivial R] lemma degree_Phi : (Φ R a b).degree = ↑5 := begin suffices : degree (X ^ 5 - C ↑a * X) = ↑5, { rwa [Φ, degree_add_eq_left_of_degree_lt], convert degree_C_le.trans_lt (with_bot.coe_lt_coe.mpr (nat.zero_lt_bit1 2)) }, rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow, exact (degree_C_mul_X_le _).trans_lt (with_bot.coe_lt_coe.mpr (nat.one_lt_bit1 two_ne_zero)), end lemma nat_degree_Phi : (Φ R a b).nat_degree = 5 := nat_degree_eq_of_degree_eq_some (degree_Phi a b) lemma leading_coeff_Phi : (Φ R a b).leading_coeff = 1 := by rw [polynomial.leading_coeff, nat_degree_Phi, coeff_five_Phi] lemma monic_Phi : (Φ R a b).monic := leading_coeff_Phi a b lemma irreducible_Phi (p : ℕ) (hp : p.prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬ p ^ 2 ∣ b) : irreducible (Φ ℚ a b) := begin rw [←map_Phi a b (int.cast_ring_hom ℚ), ←is_primitive.int.irreducible_iff_irreducible_map_cast], apply irreducible_of_eisenstein_criterion, { rwa [span_singleton_prime (int.coe_nat_ne_zero.mpr hp.ne_zero), int.prime_iff_nat_abs_prime] }, { rw [leading_coeff_Phi, mem_span_singleton], exact_mod_cast mt nat.dvd_one.mp (hp.ne_one) }, { intros n hn, rw mem_span_singleton, rw [degree_Phi, with_bot.coe_lt_coe] at hn, interval_cases n with hn; simp [Φ, coeff_X_pow, coeff_C, int.coe_nat_dvd.mpr, hpb, hpa, -ring_hom.eq_int_cast] }, { simp only [degree_Phi, ←with_bot.coe_zero, with_bot.coe_lt_coe, nat.succ_pos'] }, { rw [coeff_zero_Phi, span_singleton_pow, mem_span_singleton, int.nat_cast_eq_coe_nat], exact mt int.coe_nat_dvd.mp hp2b }, all_goals { exact monic.is_primitive (monic_Phi a b) }, end lemma real_roots_Phi_le : fintype.card ((Φ ℚ a b).root_set ℝ) ≤ 3 := begin rw [←map_Phi a b (algebra_map ℤ ℚ), Φ, ←one_mul (X ^ 5), ←C_1], refine (card_root_set_le_derivative _).trans (nat.succ_le_succ ((card_root_set_le_derivative _).trans (nat.succ_le_succ _))), suffices : ((C ((algebra_map ℤ ℚ) 20) * X ^ 3).root_set ℝ).subsingleton, { norm_num [fintype.card_le_one_iff_subsingleton, ← mul_assoc, *] at * }, rw root_set_C_mul_X_pow; norm_num, end lemma real_roots_Phi_ge_aux (hab : b < a) : ∃ x y : ℝ, x ≠ y ∧ aeval x (Φ ℚ a b) = 0 ∧ aeval y (Φ ℚ a b) = 0 := begin let f := λ x : ℝ, aeval x (Φ ℚ a b), have hf : f = λ x, x ^ 5 - a * x + b := by simp [f, Φ], have hc : ∀ s : set ℝ, continuous_on f s := λ s, (Φ ℚ a b).continuous_on_aeval, have ha : (1 : ℝ) ≤ a := nat.one_le_cast.mpr (nat.one_le_of_lt hab), have hle : (0 : ℝ) ≤ 1 := zero_le_one, have hf0 : 0 ≤ f 0 := by norm_num [hf], by_cases hb : (1 : ℝ) - a + b < 0, { have hf1 : f 1 < 0 := by norm_num [hf, hb], have hfa : 0 ≤ f a, { simp_rw [hf, ←sq], refine add_nonneg (sub_nonneg.mpr (pow_le_pow ha _)) _; norm_num }, obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Ico' hle (hc _) (set.mem_Ioc.mpr ⟨hf1, hf0⟩), obtain ⟨y, ⟨hy1, -⟩, hy2⟩ := intermediate_value_Ioc ha (hc _) (set.mem_Ioc.mpr ⟨hf1, hfa⟩), exact ⟨x, y, (hx1.trans hy1).ne, hx2, hy2⟩ }, { replace hb : (b : ℝ) = a - 1 := by linarith [show (b : ℝ) + 1 ≤ a, by exact_mod_cast hab], have hf1 : f 1 = 0 := by norm_num [hf, hb], have hfa := calc f (-a) = a ^ 2 - a ^ 5 + b : by norm_num [hf, ← sq] ... ≤ a ^ 2 - a ^ 3 + (a - 1) : by refine add_le_add (sub_le_sub_left (pow_le_pow ha _) _) _; linarith ... = -(a - 1) ^ 2 * (a + 1) : by ring ... ≤ 0 : by nlinarith, have ha' := neg_nonpos.mpr (hle.trans ha), obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Icc ha' (hc _) (set.mem_Icc.mpr ⟨hfa, hf0⟩), exact ⟨x, 1, (hx1.trans_lt zero_lt_one).ne, hx2, hf1⟩ }, end lemma real_roots_Phi_ge (hab : b < a) : 2 ≤ fintype.card ((Φ ℚ a b).root_set ℝ) := begin have q_ne_zero : Φ ℚ a b ≠ 0 := (monic_Phi a b).ne_zero, obtain ⟨x, y, hxy, hx, hy⟩ := real_roots_Phi_ge_aux a b hab, have key : ↑({x, y} : finset ℝ) ⊆ (Φ ℚ a b).root_set ℝ, { simp [set.insert_subset, mem_root_set q_ne_zero, hx, hy] }, convert fintype.card_le_of_embedding (set.embedding_of_subset _ _ key), simp only [finset.coe_sort_coe, fintype.card_coe, finset.card_singleton, finset.card_insert_of_not_mem (mt finset.mem_singleton.mp hxy)] end lemma complex_roots_Phi (h : (Φ ℚ a b).separable) : fintype.card ((Φ ℚ a b).root_set ℂ) = 5 := (card_root_set_eq_nat_degree h (is_alg_closed.splits_codomain _)).trans (nat_degree_Phi a b) lemma gal_Phi (hab : b < a) (h_irred : irreducible (Φ ℚ a b)) : bijective (gal_action_hom (Φ ℚ a b) ℂ) := begin apply gal_action_hom_bijective_of_prime_degree' h_irred, { norm_num [nat_degree_Phi] }, { rw [complex_roots_Phi a b h_irred.separable, nat.succ_le_succ_iff], exact (real_roots_Phi_le a b).trans (nat.le_succ 3) }, { simp_rw [complex_roots_Phi a b h_irred.separable, nat.succ_le_succ_iff], exact real_roots_Phi_ge a b hab }, end theorem not_solvable_by_rad (p : ℕ) (x : ℂ) (hx : aeval x (Φ ℚ a b) = 0) (hab : b < a) (hp : p.prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬ p ^ 2 ∣ b) : ¬ is_solvable_by_rad ℚ x := begin have h_irred := irreducible_Phi a b p hp hpa hpb hp2b, apply mt (solvable_by_rad.is_solvable' h_irred hx), introI h, refine equiv.perm.not_solvable _ (le_of_eq _) (solvable_of_surjective (gal_Phi a b hab h_irred).2), rw_mod_cast [cardinal.fintype_card, complex_roots_Phi a b h_irred.separable], end theorem not_solvable_by_rad' (x : ℂ) (hx : aeval x (Φ ℚ 4 2) = 0) : ¬ is_solvable_by_rad ℚ x := by apply not_solvable_by_rad 4 2 2 x hx; norm_num /-- **Abel-Ruffini Theorem** -/ theorem exists_not_solvable_by_rad : ∃ x : ℂ, is_algebraic ℚ x ∧ ¬ is_solvable_by_rad ℚ x := begin obtain ⟨x, hx⟩ := exists_root_of_splits (algebra_map ℚ ℂ) (is_alg_closed.splits_codomain (Φ ℚ 4 2)) (ne_of_eq_of_ne (degree_Phi 4 2) (mt with_bot.coe_eq_coe.mp (nat.bit1_ne_zero 2))), exact ⟨x, ⟨Φ ℚ 4 2, (monic_Phi 4 2).ne_zero, hx⟩, not_solvable_by_rad' x hx⟩, end end abel_ruffini
ff38b04ec7ed63d9bc6731c8cb7f4a854e27715f
ddf69e0b8ad10bfd251aa1fb492bd92f064768ec
/src/linear_algebra/eigenspace.lean
eb157806a8756d2da107adaf232a908d4f52ae13
[ "Apache-2.0" ]
permissive
MaboroshiChan/mathlib
db1c1982df384a2604b19a5e1f5c6464c7c76de1
7f74e6b35f6bac86b9218250e83441ac3e17264c
refs/heads/master
1,671,993,587,476
1,601,911,102,000
1,601,911,102,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,117
lean
/- Copyright (c) 2020 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Alexander Bentkamp. -/ import field_theory.algebraic_closure import linear_algebra.finsupp import linear_algebra.matrix /-! # Eigenvectors and eigenvalues This file defines eigenspaces, eigenvalues, and eigenvalues, as well as their generalized counterparts. We follow Axler's approach [axler2015] because it allows us to derive many properties without choosing a basis and without using matrices. An eigenspace of a linear map `f` for a scalar `μ` is the kernel of the map `(f - μ • id)`. The nonzero elements of an eigenspace are eigenvectors `x`. They have the property `f x = μ • x`. If there are eigenvectors for a scalar `μ`, the scalar `μ` is called an eigenvalue. There is no consensus in the literature whether `0` is an eigenvector. Our definition of `has_eigenvector` permits only nonzero vectors. For an eigenvector `x` that may also be `0`, we write `x ∈ f.eigenspace μ`. A generalized eigenspace of a linear map `f` for a natural number `k` and a scalar `μ` is the kernel of the map `(f - μ • id) ^ k`. The nonzero elements of a generalized eigenspace are generalized eigenvectors `x`. If there are generalized eigenvectors for a natural number `k` and a scalar `μ`, the scalar `μ` is called a generalized eigenvalue. ## References * [Sheldon Axler, *Linear Algebra Done Right*][axler2015] * https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors ## Tags eigenspace, eigenvector, eigenvalue, eigen -/ universes u v w namespace module namespace End open vector_space principal_ideal_ring polynomial finite_dimensional variables {K R : Type v} {V M : Type w} [comm_ring R] [add_comm_group M] [module R M] [field K] [add_comm_group V] [vector_space K V] /-- The submodule `eigenspace f μ` for a linear map `f` and a scalar `μ` consists of all vectors `x` such that `f x = μ • x`. (Def 5.36 of [axler2015])-/ def eigenspace (f : End R M) (μ : R) : submodule R M := (f - algebra_map R (End R M) μ).ker /-- A nonzero element of an eigenspace is an eigenvector. (Def 5.7 of [axler2015]) -/ def has_eigenvector (f : End R M) (μ : R) (x : M) : Prop := x ≠ 0 ∧ x ∈ eigenspace f μ /-- A scalar `μ` is an eigenvalue for a linear map `f` if there are nonzero vectors `x` such that `f x = μ • x`. (Def 5.5 of [axler2015]) -/ def has_eigenvalue (f : End R M) (a : R) : Prop := eigenspace f a ≠ ⊥ lemma mem_eigenspace_iff {f : End R M} {μ : R} {x : M} : x ∈ eigenspace f μ ↔ f x = μ • x := by rw [eigenspace, linear_map.mem_ker, linear_map.sub_apply, algebra_map_End_apply, sub_eq_zero] lemma eigenspace_div (f : End K V) (a b : K) (hb : b ≠ 0) : eigenspace f (a / b) = (b • f - algebra_map K (End K V) a).ker := calc eigenspace f (a / b) = eigenspace f (b⁻¹ * a) : by { dsimp [(/)], rw mul_comm } ... = (f - (b⁻¹ * a) • linear_map.id).ker : rfl ... = (f - b⁻¹ • a • linear_map.id).ker : by rw smul_smul ... = (f - b⁻¹ • algebra_map K (End K V) a).ker : rfl ... = (b • (f - b⁻¹ • algebra_map K (End K V) a)).ker : by rw linear_map.ker_smul _ b hb ... = (b • f - algebra_map K (End K V) a).ker : by rw [smul_sub, smul_inv_smul' hb] lemma eigenspace_aeval_polynomial_degree_1 (f : End K V) (q : polynomial K) (hq : degree q = 1) : eigenspace f (- q.coeff 0 / q.leading_coeff) = (aeval f q).ker := calc eigenspace f (- q.coeff 0 / q.leading_coeff) = (q.leading_coeff • f - algebra_map K (End K V) (- q.coeff 0)).ker : by { rw eigenspace_div, intro h, rw leading_coeff_eq_zero_iff_deg_eq_bot.1 h at hq, cases hq } ... = (aeval f (C q.leading_coeff * X + C (q.coeff 0))).ker : by { rw [C_mul', aeval_def], simpa [algebra_map, algebra.to_ring_hom], } ... = (aeval f q).ker : by { congr, apply (eq_X_add_C_of_degree_eq_one hq).symm } lemma ker_aeval_ring_hom'_unit_polynomial (f : End K V) (c : units (polynomial K)) : (aeval f (c : polynomial K)).ker = ⊥ := begin rw polynomial.eq_C_of_degree_eq_zero (degree_coe_units c), simp only [aeval_def, eval₂_C], apply ker_algebra_map_End, apply coeff_coe_units_zero_ne_zero c end theorem aeval_apply_of_has_eigenvector {f : End K V} {p : polynomial K} {μ : K} {x : V} (h : f.has_eigenvector μ x) : aeval f p x = (p.eval μ) • x := begin apply p.induction_on, { intro a, simp [module.algebra_map_End_apply] }, { intros p q hp hq, simp [hp, hq, add_smul] }, { intros n a hna, rw [mul_comm, pow_succ, mul_assoc, alg_hom.map_mul, linear_map.mul_app, mul_comm, hna], simp [algebra_map_End_apply, mem_eigenspace_iff.1 h.2, smul_smul, mul_comm] } end section minimal_polynomial variables [finite_dimensional K V] (f : End K V) protected theorem is_integral : is_integral K f := is_integral_of_noetherian (by apply_instance) f variables {f} {μ : K} theorem is_root_of_has_eigenvalue (h : f.has_eigenvalue μ) : (minimal_polynomial f.is_integral).is_root μ := begin rcases (submodule.ne_bot_iff _).1 h with ⟨w, ⟨H, ne0⟩⟩, refine or.resolve_right (smul_eq_zero.1 _) ne0, simp [← aeval_apply_of_has_eigenvector ⟨ne0, H⟩, minimal_polynomial.aeval f.is_integral], end theorem has_eigenvalue_of_is_root (h : (minimal_polynomial f.is_integral).is_root μ) : f.has_eigenvalue μ := begin cases dvd_iff_is_root.2 h with p hp, rw [has_eigenvalue, eigenspace], intro con, cases (linear_map.is_unit_iff _).2 con with u hu, have p_ne_0 : p ≠ 0, { intro con, apply minimal_polynomial.ne_zero f.is_integral, rw [hp, con, mul_zero] }, have h_deg := minimal_polynomial.degree_le_of_ne_zero f.is_integral p_ne_0 _, { rw [hp, degree_mul, degree_X_sub_C, polynomial.degree_eq_nat_degree p_ne_0] at h_deg, norm_cast at h_deg, linarith, }, { have h_aeval := minimal_polynomial.aeval f.is_integral, revert h_aeval, simp [hp, ← hu] }, end theorem has_eigenvalue_iff_is_root : f.has_eigenvalue μ ↔ (minimal_polynomial f.is_integral).is_root μ := ⟨is_root_of_has_eigenvalue, has_eigenvalue_of_is_root⟩ end minimal_polynomial /-- Every linear operator on a vector space over an algebraically closed field has an eigenvalue. (Lemma 5.21 of [axler2015]) -/ lemma exists_eigenvalue [is_alg_closed K] [finite_dimensional K V] [nontrivial V] (f : End K V) : ∃ (c : K), f.has_eigenvalue c := begin classical, -- Choose a nonzero vector `v`. obtain ⟨v, hv⟩ : ∃ v : V, v ≠ 0 := exists_ne (0 : V), -- The infinitely many vectors v, f v, f (f v), ... cannot be linearly independent -- because the vector space is finite dimensional. have h_lin_dep : ¬ linear_independent K (λ n : ℕ, (f ^ n) v), { apply not_linear_independent_of_infinite, }, -- Therefore, there must be a nonzero polynomial `p` such that `p(f) v = 0`. obtain ⟨p, ⟨h_mon, h_eval_p⟩⟩ := f.is_integral, have h_eval_p_not_unit : aeval f p ∉ is_unit.submonoid (End K V), { rw [is_unit.mem_submonoid_iff, linear_map.is_unit_iff, linear_map.ker_eq_bot'], intro h, apply hv (h v _), rw [aeval_def, h_eval_p, linear_map.zero_apply] }, -- Hence, there must be a factor `q` of `p` such that `q(f)` is not invertible. obtain ⟨q, hq_factor, hq_nonunit⟩ : ∃ q, q ∈ factors p ∧ ¬ is_unit (aeval f q), { simp only [←not_imp, (is_unit.mem_submonoid_iff _).symm], apply not_forall.1 (λ h, h_eval_p_not_unit (ring_hom_mem_submonoid_of_factors_subset_of_units_subset (eval₂_ring_hom' (algebra_map _ _) algebra.commutes f) (is_unit.submonoid (End K V)) p h_mon.ne_zero h _)), simp only [is_unit.mem_submonoid_iff, linear_map.is_unit_iff], apply ker_aeval_ring_hom'_unit_polynomial }, -- Since the field is algebraically closed, `q` has degree 1. have h_deg_q : q.degree = 1 := is_alg_closed.degree_eq_one_of_irreducible _ (ne_zero_of_mem_factors h_mon.ne_zero hq_factor) ((factors_spec p h_mon.ne_zero).1 q hq_factor), -- Then the kernel of `q(f)` is an eigenspace. have h_eigenspace: eigenspace f (-q.coeff 0 / q.leading_coeff) = (aeval f q).ker, from eigenspace_aeval_polynomial_degree_1 f q h_deg_q, -- Since `q(f)` is not invertible, the kernel is not `⊥`, and thus there exists an eigenvalue. show ∃ (c : K), f.has_eigenvalue c, { use -q.coeff 0 / q.leading_coeff, rw [has_eigenvalue, h_eigenspace], intro h_eval_ker, exact hq_nonunit ((linear_map.is_unit_iff (aeval f q)).2 h_eval_ker) } end /-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly independent. (Lemma 5.10 of [axler2015]) We use the eigenvalues as indexing set to ensure that there is only one eigenvector for each eigenvalue in the image of `xs`. -/ lemma eigenvectors_linear_independent (f : End K V) (μs : set K) (xs : μs → V) (h_eigenvec : ∀ μ : μs, f.has_eigenvector μ (xs μ)) : linear_independent K xs := begin classical, -- We need to show that if a linear combination `l` of the eigenvectors `xs` is `0`, then all -- its coefficients are zero. suffices : ∀ l, finsupp.total μs V K xs l = 0 → l = 0, { rw linear_independent_iff, apply this }, intros l hl, -- We apply induction on the finite set of eigenvalues whose eigenvectors have nonzero -- coefficients, i.e. on the support of `l`. induction h_l_support : l.support using finset.induction with μ₀ l_support' hμ₀ ih generalizing l, -- If the support is empty, all coefficients are zero and we are done. { exact finsupp.support_eq_empty.1 h_l_support }, -- Now assume that the support of `l` contains at least one eigenvalue `μ₀`. We define a new -- linear combination `l'` to apply the induction hypothesis on later. The linear combination `l'` -- is derived from `l` by multiplying the coefficient of the eigenvector with eigenvalue `μ` -- by `μ - μ₀`. -- To get started, we define `l'` as a function `l'_f : μs → K` with potentially infinite support. { let l'_f : μs → K := (λ μ : μs, (↑μ - ↑μ₀) * l μ), -- The support of `l'_f` is the support of `l` without `μ₀`. have h_l_support' : ∀ (μ : μs), μ ∈ l_support' ↔ l'_f μ ≠ 0 , { intro μ, suffices : μ ∈ l_support' → μ ≠ μ₀, { simp [l'_f, ← finsupp.not_mem_support_iff, h_l_support, sub_eq_zero, ←subtype.ext_iff], tauto }, rintro hμ rfl, contradiction }, -- Now we can define `l'_f` as an actual linear combination `l'` because we know that the -- support is finite. let l' : μs →₀ K := { to_fun := l'_f, support := l_support', mem_support_to_fun := h_l_support' }, -- The linear combination `l'` over `xs` adds up to `0`. have total_l' : finsupp.total μs V K xs l' = 0, { let g := f - algebra_map K (End K V) μ₀, have h_gμ₀: g (l μ₀ • xs μ₀) = 0, by rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).2, algebra_map_End_apply, sub_self, smul_zero], have h_useless_filter : finset.filter (λ (a : μs), l'_f a ≠ 0) l_support' = l_support', { rw finset.filter_congr _, { apply finset.filter_true }, { apply_instance }, exact λ μ hμ, (iff_true _).mpr ((h_l_support' μ).1 hμ) }, have bodies_eq : ∀ (μ : μs), l'_f μ • xs μ = g (l μ • xs μ), { intro μ, dsimp only [g, l'_f], rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).2, algebra_map_End_apply, ←sub_smul, smul_smul, mul_comm] }, rw [←linear_map.map_zero g, ←hl, finsupp.total_apply, finsupp.total_apply, finsupp.sum, finsupp.sum, linear_map.map_sum, h_l_support, finset.sum_insert hμ₀, h_gμ₀, zero_add], refine finset.sum_congr rfl (λ μ _, _), apply bodies_eq }, -- Therefore, by the induction hypothesis, all coefficients in `l'` are zero. have l'_eq_0 : l' = 0 := ih l' total_l' rfl, -- By the defintion of `l'`, this means that `(μ - μ₀) * l μ = 0` for all `μ`. have h_mul_eq_0 : ∀ μ : μs, (↑μ - ↑μ₀) * l μ = 0, { intro μ, calc (↑μ - ↑μ₀) * l μ = l' μ : rfl ... = 0 : by { rw [l'_eq_0], refl } }, -- Thus, the coefficients in `l` for all `μ ≠ μ₀` are `0`. have h_lμ_eq_0 : ∀ μ : μs, μ ≠ μ₀ → l μ = 0, { intros μ hμ, apply or_iff_not_imp_left.1 (mul_eq_zero.1 (h_mul_eq_0 μ)), rwa [sub_eq_zero, ←subtype.ext_iff] }, -- So if we sum over all these coefficients, we obtain `0`. have h_sum_l_support'_eq_0 : finset.sum l_support' (λ (μ : ↥μs), l μ • xs μ) = 0, { rw ←finset.sum_const_zero, apply finset.sum_congr rfl, intros μ hμ, rw h_lμ_eq_0, apply zero_smul, intro h, rw h at hμ, contradiction }, -- The only potentially nonzero coefficient in `l` is the one corresponding to `μ₀`. But since -- the overall sum is `0` by assumption, this coefficient must also be `0`. have : l μ₀ = 0, { rw [finsupp.total_apply, finsupp.sum, h_l_support, finset.sum_insert hμ₀, h_sum_l_support'_eq_0, add_zero] at hl, by_contra h, exact (h_eigenvec μ₀).1 ((smul_eq_zero.1 hl).resolve_left h) }, -- Thus, all coefficients in `l` are `0`. show l = 0, { ext μ, by_cases h_cases : μ = μ₀, { rw h_cases, assumption }, exact h_lμ_eq_0 μ h_cases } } end /-- The generalized eigenspace for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the kernel of `(f - μ • id) ^ k`. (Def 8.10 of [axler2015])-/ def generalized_eigenspace (f : End R M) (μ : R) (k : ℕ) : submodule R M := ((f - algebra_map R (End R M) μ) ^ k).ker /-- A nonzero element of a generalized eigenspace is a generalized eigenvector. (Def 8.9 of [axler2015])-/ def has_generalized_eigenvector (f : End R M) (μ : R) (k : ℕ) (x : M) : Prop := x ≠ 0 ∧ x ∈ generalized_eigenspace f μ k /-- A scalar `μ` is a generalized eigenvalue for a linear map `f` and an exponent `k ∈ ℕ` if there are generalized eigenvectors for `f`, `k`, and `μ`. -/ def has_generalized_eigenvalue (f : End R M) (μ : R) (k : ℕ) : Prop := generalized_eigenspace f μ k ≠ ⊥ /-- The generalized eigenrange for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the range of `(f - μ • id) ^ k`. -/ def generalized_eigenrange (f : End R M) (μ : R) (k : ℕ) : submodule R M := ((f - algebra_map R (End R M) μ) ^ k).range /-- The exponent of a generalized eigenvalue is never 0. -/ lemma exp_ne_zero_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ} (h : f.has_generalized_eigenvalue μ k) : k ≠ 0 := begin rintro rfl, exact h linear_map.ker_id end /-- A generalized eigenspace for some exponent `k` is contained in the generalized eigenspace for exponents larger than `k`. -/ lemma generalized_eigenspace_mono {f : End K V} {μ : K} {k : ℕ} {m : ℕ} (hm : k ≤ m) : f.generalized_eigenspace μ k ≤ f.generalized_eigenspace μ m := begin simp only [generalized_eigenspace, ←pow_sub_mul_pow _ hm], exact linear_map.ker_le_ker_comp ((f - algebra_map K (End K V) μ) ^ k) ((f - algebra_map K (End K V) μ) ^ (m - k)) end /-- A generalized eigenvalue for some exponent `k` is also a generalized eigenvalue for exponents larger than `k`. -/ lemma has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le {f : End K V} {μ : K} {k : ℕ} {m : ℕ} (hm : k ≤ m) (hk : f.has_generalized_eigenvalue μ k) : f.has_generalized_eigenvalue μ m := begin unfold has_generalized_eigenvalue at *, contrapose! hk, rw [←le_bot_iff, ←hk], exact generalized_eigenspace_mono hm end /-- The eigenspace is a subspace of the generalized eigenspace. -/ lemma eigenspace_le_generalized_eigenspace {f : End K V} {μ : K} {k : ℕ} (hk : 0 < k) : f.eigenspace μ ≤ f.generalized_eigenspace μ k := generalized_eigenspace_mono (nat.succ_le_of_lt hk) /-- All eigenvalues are generalized eigenvalues. -/ lemma has_generalized_eigenvalue_of_has_eigenvalue {f : End K V} {μ : K} {k : ℕ} (hk : 0 < k) (hμ : f.has_eigenvalue μ) : f.has_generalized_eigenvalue μ k := begin apply has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le hk, rwa [has_generalized_eigenvalue, generalized_eigenspace, pow_one] end /-- Every generalized eigenvector is a generalized eigenvector for exponent `findim K V`. (Lemma 8.11 of [axler2015]) -/ lemma generalized_eigenspace_le_generalized_eigenspace_findim [finite_dimensional K V] (f : End K V) (μ : K) (k : ℕ) : f.generalized_eigenspace μ k ≤ f.generalized_eigenspace μ (findim K V) := ker_pow_le_ker_pow_findim _ _ /-- Generalized eigenspaces for exponents at least `findim K V` are equal to each other. -/ lemma generalized_eigenspace_eq_generalized_eigenspace_findim_of_le [finite_dimensional K V] (f : End K V) (μ : K) {k : ℕ} (hk : findim K V ≤ k) : f.generalized_eigenspace μ k = f.generalized_eigenspace μ (findim K V) := ker_pow_eq_ker_pow_findim_of_le hk /-- If `f` maps a subspace `p` into itself, then the generalized eigenspace of the restriction of `f` to `p` is the part of the generalized eigenspace of `f` that lies in `p`. -/ lemma generalized_eigenspace_restrict (f : End K V) (p : submodule K V) (k : ℕ) (μ : K) (hfp : ∀ (x : V), x ∈ p → f x ∈ p) : generalized_eigenspace (linear_map.restrict f hfp) μ k = submodule.comap p.subtype (f.generalized_eigenspace μ k) := begin rw [generalized_eigenspace, generalized_eigenspace, ←linear_map.ker_comp], induction k with k ih, { rw [pow_zero,pow_zero], convert linear_map.ker_id, apply submodule.ker_subtype }, { erw [pow_succ', pow_succ', linear_map.ker_comp, ih, ←linear_map.ker_comp, linear_map.comp_assoc], } end /-- Generalized eigenrange and generalized eigenspace for exponent `findim K V` are disjoint. -/ lemma generalized_eigenvec_disjoint_range_ker [finite_dimensional K V] (f : End K V) (μ : K) : disjoint (f.generalized_eigenrange μ (findim K V)) (f.generalized_eigenspace μ (findim K V)) := begin have h := calc submodule.comap ((f - algebra_map _ _ μ) ^ findim K V) (f.generalized_eigenspace μ (findim K V)) = ((f - algebra_map _ _ μ) ^ findim K V * (f - algebra_map K (End K V) μ) ^ findim K V).ker : by { rw [generalized_eigenspace, ←linear_map.ker_comp], refl } ... = f.generalized_eigenspace μ (findim K V + findim K V) : by { rw ←pow_add, refl } ... = f.generalized_eigenspace μ (findim K V) : by { rw generalized_eigenspace_eq_generalized_eigenspace_findim_of_le, linarith }, rw [disjoint, generalized_eigenrange, linear_map.range, submodule.map_inf_eq_map_inf_comap, top_inf_eq, h], apply submodule.map_comap_le end /-- The generalized eigenspace of an eigenvalue has positive dimension for positive exponents. -/ lemma pos_findim_generalized_eigenspace_of_has_eigenvalue [finite_dimensional K V] {f : End K V} {k : ℕ} {μ : K} (hx : f.has_eigenvalue μ) (hk : 0 < k): 0 < findim K (f.generalized_eigenspace μ k) := calc 0 = findim K (⊥ : submodule K V) : by rw findim_bot ... < findim K (f.eigenspace μ) : submodule.findim_lt_findim_of_lt (bot_lt_iff_ne_bot.2 hx) ... ≤ findim K (f.generalized_eigenspace μ k) : submodule.findim_mono (generalized_eigenspace_mono (nat.succ_le_of_lt hk)) /-- A linear map maps a generalized eigenrange into itself. -/ lemma map_generalized_eigenrange_le {f : End K V} {μ : K} {n : ℕ} : submodule.map f (f.generalized_eigenrange μ n) ≤ f.generalized_eigenrange μ n := calc submodule.map f (f.generalized_eigenrange μ n) = (f * ((f - algebra_map _ _ μ) ^ n)).range : (linear_map.range_comp _ _).symm ... = (((f - algebra_map _ _ μ) ^ n) * f).range : by rw algebra.mul_sub_algebra_map_pow_commutes ... = submodule.map ((f - algebra_map _ _ μ) ^ n) f.range : linear_map.range_comp _ _ ... ≤ f.generalized_eigenrange μ n : linear_map.map_le_range /-- The generalized eigenvectors span the entire vector space (Lemma 8.21 of [axler2015]). -/ lemma supr_generalized_eigenspace_eq_top [is_alg_closed K] [finite_dimensional K V] (f : End K V) : (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤ := begin tactic.unfreeze_local_instances, -- We prove the claim by strong induction on the dimension of the vector space. induction h_dim : findim K V using nat.strong_induction_on with n ih generalizing V, cases n, -- If the vector space is 0-dimensional, the result is trivial. { rw ←top_le_iff, simp only [findim_eq_zero.1 (eq.trans findim_top h_dim), bot_le] }, -- Otherwise the vector space is nontrivial. { haveI : nontrivial V := findim_pos_iff.1 (by { rw h_dim, apply nat.zero_lt_succ }), -- Hence, `f` has an eigenvalue `μ₀`. obtain ⟨μ₀, hμ₀⟩ : ∃ μ₀, f.has_eigenvalue μ₀ := exists_eigenvalue f, -- We define `ES` to be the generalized eigenspace let ES := f.generalized_eigenspace μ₀ (findim K V), -- and `ER` to be the generalized eigenrange. let ER := f.generalized_eigenrange μ₀ (findim K V), -- `f` maps `ER` into itself. have h_f_ER : ∀ (x : V), x ∈ ER → f x ∈ ER, from λ x hx, map_generalized_eigenrange_le (submodule.mem_map_of_mem hx), -- Therefore, we can define the restriction `f'` of `f` to `ER`. let f' : End K ER := f.restrict h_f_ER, -- The dimension of `ES` is positive have h_dim_ES_pos : 0 < findim K ES, { dsimp only [ES], rw h_dim, apply pos_findim_generalized_eigenspace_of_has_eigenvalue hμ₀ (nat.zero_lt_succ n) }, -- and the dimensions of `ES` and `ER` add up to `findim K V`. have h_dim_add : findim K ER + findim K ES = findim K V, { apply linear_map.findim_range_add_findim_ker }, -- Therefore the dimension `ER` mus be smaller than `findim K V`. have h_dim_ER : findim K ER < n.succ, by omega, -- This allows us to apply the induction hypothesis on `ER`: have ih_ER : (⨆ (μ : K) (k : ℕ), f'.generalized_eigenspace μ k) = ⊤, from ih (findim K ER) h_dim_ER f' rfl, -- The induction hypothesis gives us a statement about subspaces of `ER`. We can transfer this -- to a statement about subspaces of `V` via `submodule.subtype`: have ih_ER' : (⨆ (μ : K) (k : ℕ), (f'.generalized_eigenspace μ k).map ER.subtype) = ER, by simp only [(submodule.map_supr _ _).symm, ih_ER, submodule.map_subtype_top ER], -- Moreover, every generalized eigenspace of `f'` is contained in the corresponding generalized -- eigenspace of `f`. have hff' : ∀ μ k, (f'.generalized_eigenspace μ k).map ER.subtype ≤ f.generalized_eigenspace μ k, { intros, rw generalized_eigenspace_restrict, apply submodule.map_comap_le }, -- It follows that `ER` is contained in the span of all generalized eigenvectors. have hER : ER ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, { rw ← ih_ER', apply supr_le_supr _, exact λ μ, supr_le_supr (λ k, hff' μ k), }, -- `ES` is contained in this span by definition. have hES : ES ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, from le_trans (le_supr (λ k, f.generalized_eigenspace μ₀ k) (findim K V)) (le_supr (λ (μ : K), ⨆ (k : ℕ), f.generalized_eigenspace μ k) μ₀), -- Moreover, we know that `ER` and `ES` are disjoint. have h_disjoint : disjoint ER ES, from generalized_eigenvec_disjoint_range_ker f μ₀, -- Since the dimensions of `ER` and `ES` add up to the dimension of `V`, it follows that the -- span of all generalized eigenvectors is all of `V`. show (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤, { rw [←top_le_iff, ←submodule.eq_top_of_disjoint ER ES h_dim_add h_disjoint], apply sup_le hER hES } } end end End end module
8572a53e92acceb4867d6b06036aaaa457a1a7b9
d1bbf1801b3dcb214451d48214589f511061da63
/src/order/complete_lattice.lean
96234676af8027c0bfe85e54843e4dc75f15555e
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,794
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 α → α)⟩ /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ class complete_lattice (α : Type*) extends bounded_lattice α, has_Sup α, has_Inf α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) /-- 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 } /-- 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 } /-- 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 : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf 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 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 le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_Sup s) @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_Inf s) theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_of_forall_le' (by simp only [Sup_le_iff]; introv h₀ h₁; rcases h _ h₁ with ⟨y,hy,hy'⟩; solve_by_elim [le_trans hy']) theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le (by simp only [le_Inf_iff]; introv h₀ h₁; rcases h _ h₁ with ⟨y,hy,hy'⟩; solve_by_elim [le_trans _ hy']) 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 -- TODO: it is weird that we have to add union_def 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_instert_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) -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq 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⟩, } 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 @[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 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 : f₁ ∘ pq.mpr = f₂ := funext f, rw [← this], refine (function.surjective.supr_comp (λ h, ⟨pq.1 h, _⟩) f₁).symm, refl 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 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_left_of_le $ infi_le _ _) (inf_le_right_of_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 α) β _ _ _ /- 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 @[simp] theorem infi_true {s : true → α} : infi s = s trivial := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_true {s : true → α} : supr s = s trivial := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) @[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_left_of_le $ infi_le _ _ | or.inr j := inf_le_right_of_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 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_left_of_le $ infi_le _ _ | sum.inr j := inf_le_right_of_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 α) _ _ _ _ /-! ### `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 α) _ _ _ 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 complete_lattice_Prop : 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, .. bounded_distrib_lattice_Prop } lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl 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) 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 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 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
ffb0ccb137d73e62e953e69201a92e0e57cc2969
f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83
/data/set/finite.lean
a4e7708e3a2c74e89e6ada102c8e9096a0d95d9f
[ "Apache-2.0" ]
permissive
mjendrusch/mathlib
df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214
5c209edb7eb616a26f64efe3500f2b1ba95b8d55
refs/heads/master
1,585,663,284,800
1,539,062,055,000
1,539,062,055,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,250
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Finite sets. -/ import data.set.lattice data.nat.basic logic.function data.fintype open set lattice function universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s /-- Construct a fintype from a finset with the same elements. -/ def fintype_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_fintype_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (fintype_of_finset s H) = s.card := fintype.subtype_card s H theorem card_fintype_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_fintype_of_finset s H; congr /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset noncomputable instance finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ (finite.fintype h) @[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ (finite.fintype h) _ theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := let ⟨s', h⟩ := hs.exists_finset in ⟨s', set.ext h⟩ theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype_of_finset s (λ _, iff.rfl)⟩ instance decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype_of_finset ∅ $ by simp 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 @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype_of_finset ⟨a :: s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', card_fintype_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' 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 : card_fintype_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 : (card_fintype_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 instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h @[simp] theorem finite_insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (finite_insert a hs).to_finset = insert a hs.to_finset := finset.ext.mpr $ by simp @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (finite_insert a h)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := fintype_insert' _ (not_mem_empty _) @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := by rw [show fintype.card ({a} : set α) = _, from card_fintype_insert' ∅ (not_mem_empty a)]; refl @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ 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 theorem finite_union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ 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 α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) := set.fintype_sep s t 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_instance theorem finite_subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype_of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype_of_finset (finset.univ.image f) $ by simp [range] theorem finite_range (f : α → β) [fintype α] : finite (range f) := by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩ theorem finite_image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ def fintype_of_fintype_image [decidable_eq β] (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype_of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ 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 theorem finite_of_finite_image {s : set α} {f : α → β} (I : injective f) : finite (f '' s) → finite s | ⟨hs⟩ := by haveI := classical.dec_eq β; exact ⟨fintype_of_fintype_image _ (partial_inv_of_injective I)⟩ theorem finite_preimage {s : set β} {f : α → β} (I : injective f) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (finite_subset h (image_preimage_subset f s)) instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype_of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ theorem finite_sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H 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) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype_of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite_prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ end set namespace finset variables [decidable_eq β] variables {s t u : finset α} {f : α → β} {a : α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma coe_to_finset {s : set α} {hs : set.finite s} : ↑(hs.to_finset) = s := by simp [set.ext_iff] @[simp] lemma coe_to_finset' [decidable_eq α] (s : set α) [fintype s] : (↑s.to_finset : set α) = s := by ext; simp end finset namespace set lemma finite_subset_Union {s : set α} (hs : finite s) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i := begin unfreezeI, cases hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, _⟩, rintro x hx, simp, exact ⟨_, ⟨_, hx, rfl⟩, hf ⟨x, hx⟩⟩ end lemma infinite_univ_nat : infinite (univ : set ℕ) := assume (h : finite (univ : set ℕ)), let ⟨n, hn⟩ := finset.exists_nat_subset_range h.to_finset in have n ∈ finset.range n, from finset.subset_iff.mpr hn $ by simp, by simp * at * lemma not_injective_nat_fintype [fintype α] [decidable_eq α] {f : ℕ → α} : ¬ injective f := assume (h : injective f), have finite (f '' univ), from finite_subset (finset.finite_to_set $ fintype.elems α) (assume a h, fintype.complete a), have finite (univ : set ℕ), from finite_of_finite_image h this, infinite_univ_nat this lemma not_injective_int_fintype [fintype α] [decidable_eq α] {f : ℤ → α} : ¬ injective f := assume hf, have injective (f ∘ (coe : ℕ → ℤ)), from injective_comp hf $ assume i j, int.of_nat_inj, not_injective_nat_fintype this lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := begin haveI := classical.prop_decidable, rw [← finset.coe_to_finset' s, ← finset.coe_to_finset' t, finset.coe_ssubset] at h, rw [card_fintype_of_finset' _ (λ x, mem_to_finset), card_fintype_of_finset' _ (λ x, mem_to_finset)], exact finset.card_lt_card h, end lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := calc fintype.card s = s.to_finset.card : set.card_fintype_of_finset' _ (by simp) ... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *) ... = fintype.card t : eq.symm (set.card_fintype_of_finset' _ (by simp)) 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 := classical.by_contradiction (λ h, lt_irrefl (fintype.card t) (have fintype.card s < fintype.card t := set.card_lt_card ⟨hsub, h⟩, by rwa [le_antisymm (card_le_of_subset hsub) hcard] at this)) end set
f57afe6f7696db0fbad7c34be85fc5189a7ee412
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/over3.lean
8267330e9c876db64c13fc4dc15a58ac59aadbff
[ "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
197
lean
constant foo.f {A B : Type} : (A → B) → (B → A) constant bla.f {A : Type} : (A → nat) → (A → nat) open foo bla noncomputable example : nat → bool := f (λ b, bool.cases_on b 0 1)
fa87dc36dba6f44dcdbbd6ea0d8ddfc554007659
0bf99ea6e10a791d50ee4597247799c17b488264
/src/Test.lean
e2ea959e523ced3dc069dbae01b6f4675ff1efdc
[]
no_license
laughinggas/DVR
746a40ead219988f295979010322f5950938e914
2bd99457817d3bb4d62d30ee2f2c0b4f9083ef76
refs/heads/master
1,669,799,663,699
1,595,844,424,000
1,595,844,424,000
275,800,206
0
0
null
null
null
null
UTF-8
Lean
false
false
21,029
lean
import ring_theory.ideals import ring_theory.principal_ideal_domain import ring_theory.localization import tactic import order.bounded_lattice import algebra.field_power import order.conditionally_complete_lattice universe u class discrete_valuation_ring (R : Type u) [integral_domain R] [is_principal_ideal_ring R] := (prime_ideal' : ideal R) (primality : prime_ideal'.is_prime) (is_nonzero : prime_ideal' ≠ ⊥) (unique_nonzero_prime_ideal : ∀ P : ideal R, P.is_prime → P = ⊥ ∨ P = prime_ideal') namespace discrete_valuation_ring def prime_ideal (R : Type u) [integral_domain R] [is_principal_ideal_ring R] [discrete_valuation_ring R] : ideal R := prime_ideal' instance is_prime (R : Type*) [integral_domain R] [is_principal_ideal_ring R] [discrete_valuation_ring R] : (prime_ideal R).is_prime := primality variables {R : Type u} [integral_domain R] [is_principal_ideal_ring R] [discrete_valuation_ring R] open discrete_valuation_ring lemma prime_ideal_is_maximal : (prime_ideal R).is_maximal := begin have f : prime_ideal R ≠ ⊥, { apply discrete_valuation_ring.is_nonzero }, apply is_prime.to_maximal_ideal, exact f, end lemma unique_max_ideal : ∃! I : ideal R, I.is_maximal := begin use prime_ideal R, split, { exact prime_ideal_is_maximal }, { intros y a, cases discrete_valuation_ring.unique_nonzero_prime_ideal y a.is_prime, { exfalso, rw h at a, apply discrete_valuation_ring.primality.left, exact a.right (prime_ideal R) (bot_lt_iff_ne_bot.2 discrete_valuation_ring.is_nonzero) }, { assumption } } end instance is_local_ring : local_ring R := local_of_unique_max_ideal unique_max_ideal open local_ring noncomputable theory open_locale classical class discrete_valuation_field (K : Type*) [field K] := (v : K -> with_top ℤ ) (hv : function.surjective v) (mul : ∀ (x y : K), v(x*y) = v(x) + v(y) ) (add : ∀ (x y : K), min (v(x)) (v(y)) ≤ v(x + y) ) (non_zero : ∀ (x : K), v(x) = ⊤ ↔ x = 0 ) namespace discrete_valuation_field definition valuation (K : Type*) [field K] [ discrete_valuation_field K ] : K -> with_top ℤ := v variables {K : Type*} [field K] [discrete_valuation_field K] lemma with_top.cases (a : with_top ℤ) : a = ⊤ ∨ ∃ n : ℤ, a = n := begin cases a with n, { -- a = ⊤ case left, refl, -- true by definition }, { -- ℤ case right, use n, refl, -- true by definition } end lemma sum_zero_iff_zero (a : with_top ℤ) : a + a = 0 ↔ a = 0 := begin split, { -- the hard way intro h, -- h is a proof of a+a=0 -- split into cases cases (with_top.cases a) with htop hn, { -- a = ⊤ rw htop at h, -- h is false cases h, -- no cases! }, { -- a = n cases hn with n hn, rw hn at h ⊢, -- now h says n+n=0 and our goal is n=0 -- but these are equalities in `with_top ℤ -- so we need to get them into ℤ -- A tactic called `norm_cast` does this norm_cast at h ⊢, -- we finally have a hypothesis n + n = 0 -- and a goal n = 0 -- and everything is an integer rw add_self_eq_zero at h, assumption } }, { -- the easy way intro ha, rw ha, simp } end --Thanks Kevin! lemma val_one_eq_zero : v(1 : K) = 0 := begin have h : (1 : K) * 1 = 1, simp, apply_fun v at h, rw mul at h, -- now we know v(1)+v(1)=v(1) and we want to deduce v(1)=0 (i.e. rule out v(1)=⊤) rcases (with_top.cases (v(1:K))) with h1 | ⟨n, h2⟩, -- do all the cases in one go { rw non_zero at h1, cases (one_ne_zero h1) }, { rw h2 at *, norm_cast at *, -- library_search found the next line exact add_left_eq_self.mp (congr_arg (has_add.add n) (congr_arg (has_add.add n) h)), }, end lemma val_minus_one_is_zero : v((-1) : K) = 0 := begin have f : (-1:K)*(-1:K) = (1 : K) := by simp, apply_fun v at f, rwa [mul, val_one_eq_zero, sum_zero_iff_zero] at f, end @[simp] lemma val_zero : v(0:K) = ⊤ := begin rw non_zero, end lemma with_top.transitivity {a b c : with_top ℤ} : a ≤ b -> b ≤ c -> a ≤ c := begin rcases(with_top.cases a) with rfl | ⟨a, rfl⟩; rcases(with_top.cases b) with rfl | ⟨b, rfl⟩; rcases(with_top.cases c) with rfl | ⟨c, rfl⟩; try {simp}, exact le_trans, end def val_ring (K : Type*) [field K] [discrete_valuation_field K] := { x : K | 0 ≤ v x } instance (K : Type*) [field K] [discrete_valuation_field K] : is_add_subgroup (val_ring K) := { zero_mem := begin unfold val_ring, simp, end, add_mem := begin unfold val_ring, simp only [set.mem_set_of_eq], rintros a b h1 h2, have g : min (v(a)) (v(b)) ≤ v(a + b) := by apply add, rw min_le_iff at g, cases g, exact with_top.transitivity h1 g, exact with_top.transitivity h2 g, end, neg_mem := begin unfold val_ring, rintros a g, simp only [set.mem_set_of_eq] at g ⊢, have f : -a = a * (-1 : K) := by simp, rw [f, mul, val_minus_one_is_zero], simp [g], end, } instance (K:Type*) [field K] [discrete_valuation_field K] : is_submonoid (val_ring K) := { one_mem := begin unfold val_ring, simp, rw val_one_eq_zero, norm_num, end, mul_mem := begin unfold val_ring, rintros a b ha hb, simp at ha hb ⊢, rw mul, apply add_nonneg ha hb, end, } instance valuation_ring (K:Type*) [field K] [discrete_valuation_field K] : is_subring (val_ring K) := {} instance is_domain (K:Type*) [field K] [discrete_valuation_field K] : integral_domain (val_ring K) := subring.domain (val_ring K) def unif (K:Type*) [field K] [discrete_valuation_field K] : set K := { π | v π = 1 } variables (π : K) (hπ : π ∈ unif K) lemma val_unif_eq_one (hπ : π ∈ unif K) : v(π) = 1 := begin unfold unif at hπ, simp at hπ, exact hπ, end lemma unif_ne_zero (hπ : π ∈ unif K) : π ≠ 0 := begin unfold unif at hπ, simp at hπ, intro g, rw [<-non_zero, hπ] at g, cases g, end lemma with_top.add_happens (a b c : with_top ℤ) (ne_top : a ≠ ⊤) : b=c ↔ a+b = a+c := begin rcases (with_top.cases a) with rfl | ⟨a, rfl⟩; rcases (with_top.cases b) with rfl | ⟨b, rfl⟩; rcases (with_top.cases c) with rfl | ⟨c, rfl⟩; try{tauto}, norm_cast, simp, end lemma with_top.add_le_happens (a b c : with_top ℤ) (ne_top : a ≠ ⊤) : b ≤ c ↔ a + b ≤ a+c := begin rcases(with_top.cases a) with rfl | ⟨a, rfl⟩; rcases(with_top.cases b) with rfl | ⟨b, rfl⟩; rcases(with_top.cases c) with rfl | ⟨n, rfl⟩; try {tauto}, { norm_cast, rw [with_top.add_top, classical.iff_iff_not_or_and_or_not], simp, }, norm_cast, simp, end lemma with_top.distrib {a b c : with_top ℤ} (na : a ≠ ⊤) (nb : b ≠ ⊤) (nc : c ≠ ⊤) : (a + b)*c = a*c + b*c := begin rcases(with_top.cases a) with rfl | ⟨a, rfl⟩; rcases(with_top.cases b) with rfl | ⟨b, rfl⟩; rcases(with_top.cases c) with rfl | ⟨c, rfl⟩; try {tauto}, norm_cast, rw add_mul, end lemma one_mul (a : with_top ℤ) : 1 * a = a := begin rcases (with_top.cases a) with rfl | ⟨a, rfl⟩; try{norm_cast, simp}, simp, rw [<-with_top.coe_one, <-with_top.coe_zero, with_top.coe_eq_coe], simp, end lemma val_inv (x : K) (nz : x ≠ 0) : v(x) + v(x)⁻¹ = 0 := begin rw [<- mul, mul_inv_cancel, val_one_eq_zero], assumption, end lemma with_top.sub_add_eq_zero (n : ℕ) : ((-n : ℤ) : with_top ℤ) + (n : with_top ℤ) = 0 := begin rw [<-with_top.coe_nat, <-with_top.coe_add], simp only [add_left_neg, int.nat_cast_eq_coe_nat, with_top.coe_zero], end lemma with_top.add_sub_eq_zero (n : ℕ) : (n : with_top ℤ) + ((-n : ℤ) : with_top ℤ) = 0 := begin rw [add_comm, with_top.sub_add_eq_zero], end lemma contra_non_zero (x : K) (n : ℕ) (nz : n ≠ 0) : v(x^n) ≠ ⊤ ↔ x ≠ 0 := begin split, repeat{contrapose, simp, intro}, { rw [a, zero_pow', val_zero], exact nz, }, { rw non_zero at a, contrapose a, apply pow_ne_zero, exact a, }, end lemma contra_non_zero_one (x : K) : v(x) ≠ ⊤ ↔ x ≠ 0 := begin have g := contra_non_zero x 1, simp at g, exact g, end lemma val_nat_power (a : K) (nz : a ≠ 0) : ∀ n : ℕ, v(a^n) = (n : with_top ℤ)*v(a) := begin rintros, induction n with d hd, { rw [pow_zero, val_one_eq_zero], simp, }, { rw [nat.succ_eq_add_one, pow_succ', mul, hd], norm_num, rw [with_top.distrib, one_mul], apply with_top.nat_ne_top, apply with_top.one_ne_top, rw contra_non_zero_one, exact nz, } end lemma val_int_power (a : K) (nz : a ≠ 0) : ∀ n : ℤ, v(a^n) = (n : with_top ℤ)*v(a) := begin rintros, cases n, { rw [fpow_of_nat, val_nat_power], { simp only [int.of_nat_eq_coe], rw <-with_top.coe_nat, simp only [int.nat_cast_eq_coe_nat], }, exact nz, }, { simp only [fpow_neg_succ_of_nat], rw [nat.succ_eq_add_one, with_top.add_happens (v (a ^ (n + 1))) (v (a ^ (n + 1))⁻¹) (↑-[1+ n] * v a), val_inv, val_nat_power], { simp only [nat.cast_add, nat.cast_one], rw <-with_top.distrib, { simp only [zero_eq_mul], left, rw [int.neg_succ_of_nat_coe', sub_eq_add_neg, with_top.coe_add, add_comm (↑-↑n), <-add_assoc, add_comm, add_assoc, <-with_top.coe_one, <-with_top.coe_add], simp, rw with_top.sub_add_eq_zero, }, { norm_cast, apply with_top.nat_ne_top, }, simp, { intro f, simp_rw [non_zero, nz] at f, exact f, }, }, exact nz, { apply pow_ne_zero, exact nz, }, rw contra_non_zero, exact nz, simp, }, end lemma unit_iff_val_zero (α : K) (hα : α ∈ val_ring K) (nzα : α ≠ 0) : v (α) = 0 ↔ ∃ β ∈ val_ring K, α * β = 1 := begin split, { rintros, use α⁻¹, split, { unfold val_ring, simp, rw [<-with_top.coe_zero, with_top.coe_le_iff], rintros b f, rw [with_top.add_happens (v(α)) _ _, val_inv, a] at f, simp only [with_top.zero_eq_coe, zero_add] at f, rw f, exact nzα, simp_rw [contra_non_zero_one], exact nzα, }, rw mul_inv_cancel, exact nzα, }, { rintros, cases a with b a, simp at a, cases a with a1 a2, unfold val_ring at a1, simp at a1, have f : v((α)*(b)) = v(1:K) := by rw a2, rw [mul, val_one_eq_zero, add_eq_zero_iff'] at f, { cases f, exact f_left, }, { erw val_ring at hα, simp at hα, exact hα, }, exact a1, }, end lemma val_eq_iff_asso (x y : K) (hx : x ∈ val_ring K) (hy : y ∈ val_ring K) (nzx : x ≠ 0) (nzy : y ≠ 0) : v(x) = v(y) ↔ ∃ β ∈ val_ring K, v(β) = 0 ∧ x * β = y := begin split, intros, use (x⁻¹*y), { { unfold val_ring, simp, rw mul, rw with_top.add_happens (v(x⁻¹)) _ _ at a, { rw [add_comm, val_inv] at a, { rw <-a, norm_num, rw mul_inv_cancel_left', exact nzx, }, exact nzx, }, { rw contra_non_zero_one, simp [nzx], }, }, }, { rintros, cases a with z a, simp at a, cases a with a1 a2, cases a2 with a2 a3, apply_fun v at a3, rw [mul,a2] at a3, simp at a3, exact a3, }, end lemma unif_assoc (x : K) (hx : x ∈ val_ring K) (nz : x ≠ 0) (hπ : π ∈ unif K) : ∃ β ∈ val_ring K, (v(β) = 0 ∧ ∃! n : ℤ, x * β = π^n) := begin have hπ' : π ≠ 0, { apply unif_ne_zero, exact hπ, }, unfold unif at hπ, simp at hπ, cases (with_top.cases) (v(x)), { rw non_zero at h, exfalso, apply nz, exact h, }, { cases h with n h, split, let y := x⁻¹ * π^n, have g : v(y) = 0, { rw [mul, val_int_power π, hπ, add_comm], norm_cast, simp, rw [<-h, val_inv], exact nz, exact hπ', }, have f : y ∈ val_ring K, { unfold val_ring, simp, rw g, norm_num, }, { use f, split, { exact g, }, rw mul_inv_cancel_left', use n, { split, simp only [eq_self_iff_true], rintros, apply_fun v at a, rw [val_int_power, val_int_power, hπ] at a, { norm_cast at a, simp at a, exact eq.symm a, }, exact hπ', exact hπ', }, exact nz, }, }, end lemma blah (n : ℤ) : n < n -> false := begin simp only [forall_prop_of_false, not_lt], end lemma val_is_nat (hπ : π ∈ unif K) (x : val_ring K) (nzx : x ≠ 0) : ∃ m : ℕ, v(x:K) = ↑m := begin cases with_top.cases (v(x:K)), { rw h, simp, rw non_zero at h, apply nzx, exact subtype.eq h, }, { cases h with n h, cases n, { use n, simp_rw h, simp, rw <-with_top.coe_nat, simp, }, { have H : 0 ≤ v(x:K), exact x.2, rw h at H, norm_cast at H, exfalso, contrapose H, simp, tidy, exact int.neg_succ_lt_zero n, }, }, end lemma exists_unif : ∃ π : K, v(π) = 1 := begin cases hv 1 with π hv, use π, rw hv, end instance is_pir (K:Type*) [field K] [discrete_valuation_field K] : is_principal_ideal_ring (val_ring K) := {principal := begin cases exists_unif with π hπ, change π ∈ unif K at hπ, rintros, by_cases S = ⊥, { rw h, use 0, apply eq.symm, rw submodule.span_singleton_eq_bot, }, let Q := {n : ℕ | ∃ x ∈ S, (n : with_top ℤ) = v(x:K) }, have g : v(π ^(Inf Q)) = ↑(Inf Q), { rw [val_nat_power, val_unif_eq_one, <-with_top.coe_one, <-with_top.coe_nat, <-with_top.coe_mul, mul_one], exact hπ, apply unif_ne_zero, exact hπ, }, have nz : π^(Inf Q) ≠ 0, { by_contradiction, simp at a, apply_fun v at a, rw [g, val_zero] at a, apply with_top.nat_ne_top (Inf Q), exact a, }, use π^(Inf Q), { unfold val_ring, simp only [set.mem_set_of_eq], rw [g, <-with_top.coe_nat], norm_cast, norm_num, }, apply submodule.ext, rintros, split, { rintros, rw submodule.mem_span_singleton, use (x * (π^(Inf Q))⁻¹), { unfold val_ring, simp, rw mul, by_cases x = 0, { rw h, simp, }, rw with_top.add_le_happens (v(π^(Inf Q))), { norm_num, rw [add_left_comm, val_inv _ nz], simp, rw g, have f' : ∃ m : ℕ, v(x:K) = ↑m, { apply val_is_nat π hπ, exact h, }, cases f' with m f', rw [f', <-with_top.coe_nat, <-with_top.coe_nat], norm_cast, have h' : m ∈ Q, { split, simp, split, use a, use [eq.symm f'], }, rw [nat.Inf_def ⟨m, h'⟩], exact nat.find_min' ⟨m, h'⟩ h', }, rw g, apply with_top.nat_ne_top, }, { tidy, assoc_rw inv_mul_cancel nz, simp, }, }, { rw submodule.mem_span, rintros, specialize a S, apply a, have f' : ∃ x ∈ S, x ≠ (0 : val_ring K), { contrapose h, simp at h, simp, apply ideal.ext, rintros, simp only [submodule.mem_bot], split, { rintros, specialize h x_1, simp at h, apply h a_1, }, rintros, rw a_1, simp, }, have p : Inf Q ∈ Q, { apply nat.Inf_mem, cases f' with x' f', have f_1 : ∃ m : ℕ, v(x':K) = ↑(m), { apply val_is_nat, exact hπ, cases f', contrapose f'_h, simp, simp at f'_h, exact f'_h, }, cases f_1 with m' f_1, have g' : m' ∈ Q, { simp, use x', simp, split, cases f', assumption, exact eq.symm f_1, }, use m', apply g', }, have f : ∃ z ∈ S, v(z : K) = ↑(Inf Q), { simp at p, cases p with z p, cases p, use z, cases p_left, assumption, split, cases p_left, assumption, simp, exact eq.symm p_right, }, cases f with z f, rw <-g at f, simp at f, cases f, rw val_eq_iff_asso at f_right, { cases f_right with w f_1, cases f_1 with f_1 f_2, cases f_2 with f_2 f_3, rw set.singleton_subset_iff, simp only [submodule.mem_coe], simp_rw [← f_3], change z * ⟨w,f_1⟩ ∈ S, apply ideal.mul_mem_right S f_left, }, simp, { unfold val_ring, simp, rw g, rw <-with_top.coe_nat, norm_cast, simp, }, { rw g at f_right, contrapose f_right, simp at f_right, rw f_right, simp, }, { exact nz, }, }, end } instance is_dvr (K:Type*) [field K] [discrete_valuation_field K] : discrete_valuation_ring (val_ring K) := { prime_ideal' := begin have f : ∃ π : val_ring K, v(π : K) = 1, { sorry, }, choose π f using f, exact ideal.span {π}, end, primality := begin apply ideal.is_maximal.is_prime, rw ideal.is_maximal_iff, split, { by_contradiction, simp at a, rw ideal.mem_span_singleton' at a, cases a, tidy, apply_fun v at h_1, rw [mul, val_one_eq_zero] at h_1, rw add_eq_zero_iff' at h_1, cases h_1, unfold classical.some at h_1_right, sorry, exact a_w_property, sorry, }, rintros, simp at a, simp at a_1, have f : v(x : K) = 0, { sorry, }, rw [eq.symm val_one_eq_zero] at f, rw val_eq_iff_asso at f, cases f with f_1 f_2, cases f_2 with f_2 f_3, cases f_3 with f_3 f_4, sorry, simp, { unfold val_ring, simp, rw val_one_eq_zero, norm_num, }, { by_contradiction, simp at a_3, rw a_3 at f, simp [val_one_eq_zero] at f, assumption, }, simp, end, is_nonzero := begin by_contra, simp at a, rw <-ideal.span_singleton_eq_bot at a, cases classical.some _ with π, sorry, end, unique_nonzero_prime_ideal := begin rintros, by_cases P = ⊥, left, exact h, right, simp, apply submodule.ext, rintros, split, { rintros, sorry, }, sorry, end } end discrete_valuation_field end discrete_valuation_ring
5b595f11f2e7ef8835baf6d874b2bc47c425dd51
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Elab/Declaration.lean
85c9e2e2403963c0fcb907d150e8d8938c55a70c
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,358
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 -/ prelude import Init.Lean.Util.CollectLevelParams import Init.Lean.Elab.Definition namespace Lean namespace Elab namespace Command def expandOptDeclSig (stx : Syntax) : Syntax × Option Syntax := -- many Term.bracketedBinder >> Term.optType let binders := stx.getArg 0; let optType := stx.getArg 1; -- optional (parser! " : " >> termParser) if optType.isNone then (binders, none) else let typeSpec := optType.getArg 0; (binders, some $ typeSpec.getArg 1) def expandDeclSig (stx : Syntax) : Syntax × Syntax := -- many Term.bracketedBinder >> Term.typeSpec let binders := stx.getArg 0; let typeSpec := stx.getArg 1; (binders, typeSpec.getArg 1) def elabAbbrev (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "abbrev " >> declId >> optDeclSig >> declVal let (binders, type) := expandOptDeclSig (stx.getArg 2); let modifiers := modifiers.addAttribute { name := `inline }; let modifiers := modifiers.addAttribute { name := `reducible }; elabDefLike { ref := stx, kind := DefKind.abbrev, modifiers := modifiers, declId := stx.getArg 1, binders := binders, type? := type, val := stx.getArg 3 } def elabDef (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "def " >> declId >> optDeclSig >> declVal let (binders, type) := expandOptDeclSig (stx.getArg 2); elabDefLike { ref := stx, kind := DefKind.def, modifiers := modifiers, declId := stx.getArg 1, binders := binders, type? := type, val := stx.getArg 3 } def elabTheorem (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "theorem " >> declId >> declSig >> declVal let (binders, type) := expandDeclSig (stx.getArg 2); elabDefLike { ref := stx, kind := DefKind.theorem, modifiers := modifiers, declId := stx.getArg 1, binders := binders, type? := some type, val := stx.getArg 3 } def elabConstant (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- parser! "constant " >> declId >> declSig >> optional declValSimple let (binders, type) := expandDeclSig (stx.getArg 2); val ← match (stx.getArg 3).getOptional? with | some val => pure val | none => do { val ← `(arbitrary _); pure $ Syntax.node `Lean.Parser.Command.declValSimple #[ mkAtomFrom stx ":=", val ] }; elabDefLike { ref := stx, kind := DefKind.opaque, modifiers := modifiers, declId := stx.getArg 1, binders := binders, type? := some type, val := val } def elabInstance (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- parser! "instance " >> optional declId >> declSig >> declVal let (binders, type) := expandDeclSig (stx.getArg 2); let modifiers := modifiers.addAttribute { name := `instance }; declId ← match (stx.getArg 1).getOptional? with | some declId => pure declId | none => throwError stx "not implemented yet"; elabDefLike { ref := stx, kind := DefKind.def, modifiers := modifiers, declId := declId, binders := binders, type? := type, val := stx.getArg 3 } def elabExample (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "example " >> declSig >> declVal let (binders, type) := expandDeclSig (stx.getArg 1); let id := mkIdentFrom stx `_example; let declId := Syntax.node `Lean.Parser.Command.declId #[id, mkNullNode]; elabDefLike { ref := stx, kind := DefKind.example, modifiers := modifiers, declId := declId, binders := binders, type? := some type, val := stx.getArg 2 } def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "axiom " >> declId >> declSig let declId := stx.getArg 1; let (binders, typeStx) := expandDeclSig (stx.getArg 2); withDeclId declId $ fun name => do declName ← mkDeclName modifiers name; applyAttributes stx declName modifiers.attrs AttributeApplicationTime.beforeElaboration; explictLevelNames ← getLevelNames; decl ← runTermElabM declName $ fun vars => Term.elabBinders binders.getArgs $ fun xs => do { type ← Term.elabType typeStx; Term.synthesizeSyntheticMVars false; type ← Term.instantiateMVars typeStx type; type ← Term.mkForall typeStx xs type; (type, _) ← Term.mkForallUsedOnly typeStx vars type; type ← Term.levelMVarToParam type; let usedParams := (collectLevelParams {} type).params; let levelParams := sortDeclLevelParams explictLevelNames usedParams; pure $ Declaration.axiomDecl { name := declName, lparams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } }; addDecl stx decl; applyAttributes stx declName modifiers.attrs AttributeApplicationTime.afterTypeChecking; applyAttributes stx declName modifiers.attrs AttributeApplicationTime.afterCompilation def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := pure () -- TODO def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := pure () -- TODO def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := pure () -- TODO @[builtinCommandElab declaration] def elabDeclaration : CommandElab := fun stx => do modifiers ← elabModifiers (stx.getArg 0); let decl := stx.getArg 1; let declKind := decl.getKind; if declKind == `Lean.Parser.Command.abbrev then elabAbbrev modifiers decl else if declKind == `Lean.Parser.Command.def then elabDef modifiers decl else if declKind == `Lean.Parser.Command.theorem then elabTheorem modifiers decl else if declKind == `Lean.Parser.Command.constant then elabConstant modifiers decl else if declKind == `Lean.Parser.Command.instance then elabInstance modifiers decl else if declKind == `Lean.Parser.Command.axiom then elabAxiom modifiers decl else if declKind == `Lean.Parser.Command.example then elabExample modifiers decl else if declKind == `Lean.Parser.Command.inductive then elabInductive modifiers decl else if declKind == `Lean.Parser.Command.classInductive then elabClassInductive modifiers decl else if declKind == `Lean.Parser.Command.structure then elabStructure modifiers decl else throwError stx "unexpected declaration" end Command end Elab end Lean
3f07ef23e6c438eedd4155a7f09135ee37a70b39
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/set_theory/cardinal.lean
7444a5db91d8d2786be45b1c33918e8d02828ce8
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
42,086
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro -/ import data.set.countable data.quot logic.function set_theory.schroeder_bernstein /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic: addition, multiplication, power, cardinal successor, minimum, supremum, infinitary sums and products ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. There is a lift operation lifting cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/ordinal.lean`, because concepts from that file are used in the proof. ## References * https://en.wikipedia.org/wiki/Cardinal_number ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega -/ open function lattice set local attribute [instance] classical.prop_decidable universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : zero_ne_one_class cardinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } instance : canonically_ordered_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.lattice.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [←le_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_succ (n : ℕ) : succ n = n.succ := le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _) @[simp] theorem succ_zero : succ 0 = 1 := by simpa using nat_succ 0 theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, ←nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, classical.not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ @[simp] theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨equiv.equiv_sigma_subtype list.length⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} {s : set α} : mk s ≤ mk α := mk_le_of_injective subtype.val_injective @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_inj {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.surjective_sigma_to_Union f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union (disjoint_iff.1 H)⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨ set.embedding_of_subset h ⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := ⟨⟨subtype.val, subtype.val_injective⟩⟩ lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : α → Prop) (e : α ≃ β) : mk {a : α // p a} = mk {b : β // p (e.symm b)} := quotient.sound ⟨equiv.subtype_equiv_of_subtype' e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact injective_comp h subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal
a6509240aa015bfbd71985762d4963cca0e2cfea
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/star/spectrum.lean
4575aad083a64d81a851daacdffc65cec8bcb506
[ "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,154
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 analysis.normed_space.star.basic import analysis.normed_space.spectrum import algebra.star.module import analysis.normed_space.star.exponential /-! # Spectral properties in C⋆-algebras In this file, we establish various propreties related to the spectrum of elements in C⋆-algebras. -/ local postfix `⋆`:std.prec.max_plus := star open_locale topological_space ennreal open filter ennreal spectrum cstar_ring section unitary_spectrum variables {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_ring E] [star_ring E] [cstar_ring E] [normed_algebra 𝕜 E] [complete_space E] [nontrivial E] lemma unitary.spectrum_subset_circle (u : unitary E) : spectrum 𝕜 (u : E) ⊆ metric.sphere 0 1 := begin refine λ k hk, mem_sphere_zero_iff_norm.mpr (le_antisymm _ _), { simpa only [cstar_ring.norm_coe_unitary u] using norm_le_norm_of_mem hk }, { rw ←unitary.coe_to_units_apply u at hk, have hnk := ne_zero_of_mem_of_unit hk, rw [←inv_inv (unitary.to_units u), ←spectrum.map_inv, set.mem_inv] at hk, have : ∥k∥⁻¹ ≤ ∥↑((unitary.to_units u)⁻¹)∥, simpa only [norm_inv] using norm_le_norm_of_mem hk, simpa using inv_le_of_inv_le (norm_pos_iff.mpr hnk) this } end lemma spectrum.subset_circle_of_unitary {u : E} (h : u ∈ unitary E) : spectrum 𝕜 u ⊆ metric.sphere 0 1 := unitary.spectrum_subset_circle ⟨u, h⟩ end unitary_spectrum section complex_scalars open complex variables {A : Type*} [normed_ring A] [normed_algebra ℂ A] [complete_space A] [star_ring A] [cstar_ring A] local notation `↑ₐ` := algebra_map ℂ A lemma spectral_radius_eq_nnnorm_of_self_adjoint [norm_one_class A] {a : A} (ha : a ∈ self_adjoint A) : spectral_radius ℂ a = ∥a∥₊ := begin have hconst : tendsto (λ n : ℕ, (∥a∥₊ : ℝ≥0∞)) at_top _ := tendsto_const_nhds, refine tendsto_nhds_unique _ hconst, convert (spectrum.pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius (a : A)).comp (nat.tendsto_pow_at_top_at_top_of_one_lt (by linarith : 1 < 2)), refine funext (λ n, _), rw [function.comp_app, nnnorm_pow_two_pow_of_self_adjoint ha, ennreal.coe_pow, ←rpow_nat_cast, ←rpow_mul], simp, end lemma spectral_radius_eq_nnnorm_of_star_normal [norm_one_class A] (a : A) [is_star_normal a] : spectral_radius ℂ a = ∥a∥₊ := begin refine (ennreal.pow_strict_mono two_ne_zero).injective _, have ha : a⋆ * a ∈ self_adjoint A, from self_adjoint.mem_iff.mpr (by simpa only [star_star] using (star_mul a⋆ a)), have heq : (λ n : ℕ, ((∥(a⋆ * a) ^ n∥₊ ^ (1 / n : ℝ)) : ℝ≥0∞)) = (λ x, x ^ 2) ∘ (λ n : ℕ, ((∥a ^ n∥₊ ^ (1 / n : ℝ)) : ℝ≥0∞)), { funext, rw [function.comp_apply, ←rpow_nat_cast, ←rpow_mul, mul_comm, rpow_mul, rpow_nat_cast, ←coe_pow, sq, ←nnnorm_star_mul_self, commute.mul_pow (star_comm_self' a), star_pow], }, have h₂ := ((ennreal.continuous_pow 2).tendsto (spectral_radius ℂ a)).comp (spectrum.pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius a), rw ←heq at h₂, convert tendsto_nhds_unique h₂ (pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius (a⋆ * a)), rw [spectral_radius_eq_nnnorm_of_self_adjoint ha, sq, nnnorm_star_mul_self, coe_mul], end /-- Any element of the spectrum of a selfadjoint is real. -/ theorem self_adjoint.mem_spectrum_eq_re [star_module ℂ A] [nontrivial A] {a : A} (ha : a ∈ self_adjoint A) {z : ℂ} (hz : z ∈ spectrum ℂ a) : z = z.re := begin let Iu := units.mk0 I I_ne_zero, have : exp ℂ (I • z) ∈ spectrum ℂ (exp ℂ (I • a)), by simpa only [units.smul_def, units.coe_mk0] using spectrum.exp_mem_exp (Iu • a) (smul_mem_smul_iff.mpr hz), exact complex.ext (of_real_re _) (by simpa only [←complex.exp_eq_exp_ℂ, mem_sphere_zero_iff_norm, norm_eq_abs, abs_exp, real.exp_eq_one_iff, smul_eq_mul, I_mul, neg_eq_zero] using spectrum.subset_circle_of_unitary (self_adjoint.exp_i_smul_unitary ha) this), end /-- Any element of the spectrum of a selfadjoint is real. -/ theorem self_adjoint.mem_spectrum_eq_re' [star_module ℂ A] [nontrivial A] (a : self_adjoint A) {z : ℂ} (hz : z ∈ spectrum ℂ (a : A)) : z = z.re := self_adjoint.mem_spectrum_eq_re a.property hz /-- The spectrum of a selfadjoint is real -/ theorem self_adjoint.coe_re_map_spectrum [star_module ℂ A] [nontrivial A] {a : A} (ha : a ∈ self_adjoint A) : spectrum ℂ a = (coe ∘ re '' (spectrum ℂ a) : set ℂ) := le_antisymm (λ z hz, ⟨z, hz, (self_adjoint.mem_spectrum_eq_re ha hz).symm⟩) (λ z, by { rintros ⟨z, hz, rfl⟩, simpa only [(self_adjoint.mem_spectrum_eq_re ha hz).symm, function.comp_app] using hz }) /-- The spectrum of a selfadjoint is real -/ theorem self_adjoint.coe_re_map_spectrum' [star_module ℂ A] [nontrivial A] (a : self_adjoint A) : spectrum ℂ (a : A) = (coe ∘ re '' (spectrum ℂ (a : A)) : set ℂ) := self_adjoint.coe_re_map_spectrum a.property end complex_scalars
bb838a93757d6b0c6db8810c844dd1666f861cc3
56af0912bd25910f5caae91d6dd0603b0c032989
/kb_solutions/of_real.lean
df663d53ade7cd06fa3c9f3f0d49c8de8f131ad9
[ "Apache-2.0" ]
permissive
isabella232/complex-number-game
ae36e0b1df9761d9df07049ca29c91ae44dbdc2d
3d767f14041f9002e435bed3a3527fdd297c166d
refs/heads/master
1,679,305,953,116
1,606,397,567,000
1,606,397,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,747
lean
import complex.kb_solutions.norm_sq /-! # Coercion This file sets up the coercion from the reals to the complexes, sending `r` to `⟨r, 0⟩`. Mathematically it is relatively straightforward. -/ namespace complex /-- The canonical map from ℝ to ℂ. -/ def of_real (r : ℝ) : ℂ := ⟨r, 0⟩ /-- The coercion from ℝ to ℂ sending `r` to the complex number `⟨r, 0⟩` -/ instance : has_coe ℝ ℂ := ⟨of_real⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := begin split, { rintro ⟨⟩, refl}, { cc} end /- We now go through all our basic constants and constructions, namely 0, 1, +, *, I, conj and norm_sq, and tell the simplifier how they behave with respect to this new function. -/ /-! ## zero -/ @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := by ext; refl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := begin split, { intro h, simpa using h, }, { rintro rfl, refl} end theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := begin simp, end /-! ## one -/ @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := begin refl, end /-! ## add -/ @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := begin ext; simp end /-! ## neg -/ @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := begin simp, end /-! ## mul -/ @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := begin simp, end /-! ## I -/ lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := begin ext; simp end @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := begin ext; simp, end /-! ## conj -/ @[simp] lemma conj_of_real (r : ℝ) : conj r = r := begin simp, end lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := begin -- not my finest hour split, { intro h, simp at h, use z.re, ext, { refl}, simp, linarith}, { cases z with x y, rintro ⟨x, hx⟩, ext, refl, dsimp at *, rw ext_iff at hx, simp * at * } end lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := begin cases z with x y, -- `simp` doesn't quite work, so just prove the goal it leaves independently. have h : -y = y ↔ 0 = y, { split; intros; linarith}, -- Makes for more readable and maintainable code. simp [h], end theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := begin cases z with x y, simp, ring, end /-! ## norm_sq -/ @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := begin simp [norm_sq], end theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := begin cases z with x y, simp [norm_sq], ring, end /-! ## Appendix: numerals. If you're not a computer scientist feel free to skip this bit. These last two are to do with the canonical map from numerals into the complexes, e.g. `(23 : ℂ)`. Lean stores the numeral in binary. See for example set_option pp.numerals false #check (37 : ℂ)-- bit1 (bit0 (bit1 (bit0 (bit0 has_one.one)))) : ℂ `bit0 x` is defined to be `x + x`, and `bit1 x` is defined to be `bit0 x + 1`. We need these results so that `norm_cast` can prove results such as (↑(37 : ℝ) : ℂ) = 37 : ℂ (i.e. coercion commutes with numerals) -/ @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := begin ext; simp [bit0] end @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := begin ext; simp [bit1], end end complex
53c25f4fa6279172c3f222dcc6970d8010794944
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/isDefEqCheckAssignmentBug.lean
bc13c13b8e29bf7c34c977ddffb2cfd94cb4e95b
[ "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
838
lean
import Lean open Lean open Lean.Meta def f (x : Type) := x def tst : MetaM Unit := do let m1 ← mkFreshExprMVar none withLocalDeclD `x m1 fun x => do trace[Meta.debug] "{x} : {← inferType x}" trace[Meta.debug] "{m1} : {← inferType m1}" let m2 ← mkFreshExprMVar (mkSort levelOne) let t ← mkAppM ``f #[m2] trace[Meta.debug] "{m2} : {← inferType m2}" unless (← fullApproxDefEq <| isDefEq m1 t) do -- m1 := f m3 -- where `m3` has a smaller scope than `m2` throwError "isDefEq failed" trace[Meta.debug] "{m2} : {← inferType m2}" trace[Meta.debug] "{m1} : {← inferType m1}" let e ← mkForallFVars #[x] m2 -- `forall (x : f ?m2), ?m2` trace[Meta.debug] "{e} : {← inferType e}" return () set_option trace.Meta.isDefEq true set_option trace.Meta.debug true #eval tst
e75643faad74096213d3b7552e9f0720e9481140
b7fc5b86b12212bea5542eb2c9d9f0988fd78697
/src/exercises_sources/tuesday/numbers.lean
b07e0f4e6cacd8c949120be3bf0ed161719cb2d0
[]
no_license
stjordanis/lftcm2020
3b16591aec853c8546d9c8b69c0bf3f5f3956fee
1f3485e4dafdc587b451ec5144a1d8d3ec9b411e
refs/heads/master
1,675,958,865,413
1,609,901,722,000
1,609,901,722,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,265
lean
import tactic import data.real.basic import data.padics import data.int.gcd /-! ## Exercises about numbers and casts -/ /-! ## First exercises These first examples are just to get you comfortable with `norm_num`, `norm_cast`, and friends. -/ example : 12345 < 67890 := begin sorry end example {α : Type} [linear_ordered_field α] : 123 + 45 < 67890/3 := begin sorry end example : nat.prime 17 := begin sorry end -- prove either this or its negation! example : 7/3 > 2 := begin sorry end example (x : ℝ) (hx : x < 50*50) : x < 25*100 := begin sorry end example (x : ℤ) (hx : (x : ℝ) < 25*100) : x < 25*100 := begin sorry end example (x : ℤ) (hx : (x : ℝ) < 2500) : x < 25*100 := begin sorry end example (p q r : ℕ) (h : r < p - q) (hpq : q ≤ p) : (r : ℝ) < p - q := begin sorry end example (p q r : ℕ) (hr : r < p + 2 - p) : (r : ℤ) < 5 := begin sorry end /-! ## Exercise 2 This comes from the development of the p-adic numbers. `norm_cast` is very useful here, since we need to talk about values in ℕ, ℤ, ℚ, ℚ_p, and ℤ_p. We've done some work to get you started. You might look for the lemmas: -/ open padic_val_rat #check fpow_le_of_le #check fpow_nonneg_of_nonneg #check padic_val_rat_of_int example {p n : ℕ} (hp : p.prime) {z : ℤ} (hd : ↑(p^n) ∣ z) : padic_norm p z ≤ ↑p ^ (-n : ℤ) := begin -- This lemma will be useful later in the proof. -- Ignore the "inst" argument; just use `apply aux_lemma` when you need it! -- Note that we haven't finished it. Fill in that final sorry. have aux_lemma : ∀ inst, (n : ℤ) ≤ (multiplicity ↑p z).get inst, { intro, norm_cast, rw [← enat.coe_le_coe, enat.coe_get], apply multiplicity.le_multiplicity_of_pow_dvd, sorry }, unfold padic_norm, split_ifs with hz hz, { sorry }, { sorry } end /-! ## Exercise 3 This seems like a very natural way to write the theorem "If `a` and `b` are coprime, then there are coefficients `u` and `v` such that `u*a + v*b = 1`." But I've made a mistake! What did I do wrong? Correct the statement of the theorem and prove it. I've started you off with a lemma that will be useful. You might find the `specialize` tactic to be handy as well: if you have `h : ∀ (x y : T), R x y` and `a, b : T` in the context, then `specialize h a b` will change the type of `h` to `R a b`. -/ example (a b : ℕ) (h : nat.coprime a b) : ∃ u v, u*a+v*b = 1 := begin have := nat.gcd_eq_gcd_ab, sorry end /-! ## Exercise 4 We did an example together that was similar to this. This one takes a bit more arithmetic work. To save you some time, here are some lemmas that may be useful! (You may not need all of them, depending on how you approach it.) Remember you can also use `library_search` to try to find useful lemmas. A hint: you might find it helpful to do this once you've introduced `n`. ``` have n_pos: 0 < n, { ... } ``` -/ #check sub_le_iff_le_add #check add_le_add_iff_left #check div_le_iff #check mul_one_div_cancel #check mul_le_mul_left notation `|`x`|` := abs x def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε example : seq_limit (λ n : ℕ, (n+1)/n) 1 := begin sorry end
f822f9ee99d63bfbaac42473664fc532d6fb7ece
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/set_family/compression/down.lean
2445f2eb75c105d9adf14fed1ae4b7041fde04b9
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,693
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.card /-! # Down-compressions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines down-compression. Down-compressing `𝒜 : finset (finset α)` along `a : α` means removing `a` from the elements of `𝒜`, when the resulting set is not already in `𝒜`. ## Main declarations * `finset.non_member_subfamily`: `𝒜.non_member_subfamily a` is the subfamily of sets not containing `a`. * `finset.member_subfamily`: `𝒜.member_subfamily a` is the image of the subfamily of sets containing `a` under removing `a`. * `down.compression`: Down-compression. ## Notation `𝓓 a 𝒜` is notation for `down.compress a 𝒜` in locale `set_family`. ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf ## Tags compression, down-compression -/ variables {α : Type*} [decidable_eq α] {𝒜 ℬ : finset (finset α)} {s : finset α} {a : α} namespace finset /-- Elements of `𝒜` that do not contain `a`. -/ def non_member_subfamily (a : α) (𝒜 : finset (finset α)) : finset (finset α) := 𝒜.filter $ λ s, a ∉ s /-- Image of the elements of `𝒜` which contain `a` under removing `a`. Finsets that do not contain `a` such that `insert a s ∈ 𝒜`. -/ def member_subfamily (a : α) (𝒜 : finset (finset α)) : finset (finset α) := (𝒜.filter $ λ s, a ∈ s).image $ λ s, erase s a @[simp] lemma mem_non_member_subfamily : s ∈ 𝒜.non_member_subfamily a ↔ s ∈ 𝒜 ∧ a ∉ s := mem_filter @[simp] lemma mem_member_subfamily : s ∈ 𝒜.member_subfamily a ↔ insert a s ∈ 𝒜 ∧ a ∉ s := begin simp_rw [member_subfamily, mem_image, mem_filter], refine ⟨_, λ h, ⟨insert a s, ⟨h.1, mem_insert_self _ _⟩, erase_insert h.2⟩⟩, rintro ⟨s, hs, rfl⟩, rw insert_erase hs.2, exact ⟨hs.1, not_mem_erase _ _⟩, end lemma non_member_subfamily_inter (a : α) (𝒜 ℬ : finset (finset α)) : (𝒜 ∩ ℬ).non_member_subfamily a = 𝒜.non_member_subfamily a ∩ ℬ.non_member_subfamily a := filter_inter_distrib _ _ _ lemma member_subfamily_inter (a : α) (𝒜 ℬ : finset (finset α)) : (𝒜 ∩ ℬ).member_subfamily a = 𝒜.member_subfamily a ∩ ℬ.member_subfamily a := begin unfold member_subfamily, rw [filter_inter_distrib, image_inter_of_inj_on _ _ ((erase_inj_on' _).mono _)], rw [←coe_union, ←filter_union, coe_filter], exact set.inter_subset_right _ _, end lemma non_member_subfamily_union (a : α) (𝒜 ℬ : finset (finset α)) : (𝒜 ∪ ℬ).non_member_subfamily a = 𝒜.non_member_subfamily a ∪ ℬ.non_member_subfamily a := filter_union _ _ _ lemma member_subfamily_union (a : α) (𝒜 ℬ : finset (finset α)) : (𝒜 ∪ ℬ).member_subfamily a = 𝒜.member_subfamily a ∪ ℬ.member_subfamily a := by simp_rw [member_subfamily, filter_union, image_union] lemma card_member_subfamily_add_card_non_member_subfamily (a : α) (𝒜 : finset (finset α)) : (𝒜.member_subfamily a).card + (𝒜.non_member_subfamily a).card = 𝒜.card := begin rw [member_subfamily, non_member_subfamily, card_image_of_inj_on, filter_card_add_filter_neg_card_eq_card], exact (erase_inj_on' _).mono (λ s hs, (mem_filter.1 hs).2), end lemma member_subfamily_union_non_member_subfamily (a : α) (𝒜 : finset (finset α)) : 𝒜.member_subfamily a ∪ 𝒜.non_member_subfamily a = 𝒜.image (λ s, s.erase a) := begin ext s, simp only [mem_union, mem_member_subfamily, mem_non_member_subfamily, mem_image, exists_prop], split, { rintro (h | h), { exact ⟨_, h.1, erase_insert h.2⟩ }, { exact ⟨_, h.1, erase_eq_of_not_mem h.2⟩ } }, { rintro ⟨s, hs, rfl⟩, by_cases ha : a ∈ s, { exact or.inl ⟨by rwa insert_erase ha, not_mem_erase _ _⟩ }, { exact or.inr ⟨by rwa erase_eq_of_not_mem ha, not_mem_erase _ _⟩ } } end @[simp] lemma member_subfamily_member_subfamily : (𝒜.member_subfamily a).member_subfamily a = ∅ := by { ext, simp } @[simp] lemma member_subfamily_non_member_subfamily : (𝒜.non_member_subfamily a).member_subfamily a = ∅ := by { ext, simp } @[simp] lemma non_member_subfamily_member_subfamily : (𝒜.member_subfamily a).non_member_subfamily a = 𝒜.member_subfamily a := by { ext, simp } @[simp] lemma non_member_subfamily_non_member_subfamily : (𝒜.non_member_subfamily a).non_member_subfamily a = 𝒜.non_member_subfamily a := by { ext, simp } end finset open finset -- The namespace is here to distinguish from other compressions. namespace down /-- `a`-down-compressing `𝒜` means removing `a` from the elements of `𝒜` that contain it, when the resulting finset is not already in `𝒜`. -/ def compression (a : α) (𝒜 : finset (finset α)) : finset (finset α) := (𝒜.filter $ λ s, erase s a ∈ 𝒜).disj_union ((𝒜.image $ λ s, erase s a).filter $ λ s, s ∉ 𝒜) $ disjoint_left.2 $ λ s h₁ h₂, (mem_filter.1 h₂).2 (mem_filter.1 h₁).1 localized "notation (name := down.compression) `𝓓 ` := down.compression" in finset_family /-- `a` is in the down-compressed family iff it's in the original and its compression is in the original, or it's not in the original but it's the compression of something in the original. -/ lemma mem_compression : s ∈ 𝓓 a 𝒜 ↔ s ∈ 𝒜 ∧ s.erase a ∈ 𝒜 ∨ s ∉ 𝒜 ∧ insert a s ∈ 𝒜 := begin simp_rw [compression, mem_disj_union, mem_filter, mem_image, and_comm (s ∉ 𝒜)], refine or_congr_right' (and_congr_left $ λ hs, ⟨_, λ h, ⟨_, h, erase_insert $ insert_ne_self.1 $ ne_of_mem_of_not_mem h hs⟩⟩), rintro ⟨t, ht, rfl⟩, rwa insert_erase (erase_ne_self.1 (ne_of_mem_of_not_mem ht hs).symm), end lemma erase_mem_compression (hs : s ∈ 𝒜) : s.erase a ∈ 𝓓 a 𝒜 := begin simp_rw [mem_compression, erase_idem, and_self], refine (em _).imp_right (λ h, ⟨h, _⟩), rwa insert_erase (erase_ne_self.1 (ne_of_mem_of_not_mem hs h).symm), end -- This is a special case of `erase_mem_compression` once we have `compression_idem`. lemma erase_mem_compression_of_mem_compression : s ∈ 𝓓 a 𝒜 → s.erase a ∈ 𝓓 a 𝒜 := begin simp_rw [mem_compression, erase_idem], refine or.imp (λ h, ⟨h.2, h.2⟩) (λ h, _), rwa [erase_eq_of_not_mem (insert_ne_self.1 $ ne_of_mem_of_not_mem h.2 h.1)], end lemma mem_compression_of_insert_mem_compression (h : insert a s ∈ 𝓓 a 𝒜) : s ∈ 𝓓 a 𝒜 := begin by_cases ha : a ∈ s, { rwa insert_eq_of_mem ha at h }, { rw ←erase_insert ha, exact erase_mem_compression_of_mem_compression h } end /-- Down-compressing a family is idempotent. -/ @[simp] lemma compression_idem (a : α) (𝒜 : finset (finset α)) : 𝓓 a (𝓓 a 𝒜) = 𝓓 a 𝒜 := begin ext s, refine mem_compression.trans ⟨_, λ h, or.inl ⟨h, erase_mem_compression_of_mem_compression h⟩⟩, rintro (h | h), { exact h.1 }, { cases h.1 (mem_compression_of_insert_mem_compression h.2) } end /-- Down-compressing a family doesn't change its size. -/ @[simp] lemma card_compression (a : α) (𝒜 : finset (finset α)) : (𝓓 a 𝒜).card = 𝒜.card := begin rw [compression, card_disj_union, image_filter, card_image_of_inj_on ((erase_inj_on' _).mono $ λ s hs, _), ←card_disjoint_union, filter_union_filter_neg_eq], { exact disjoint_filter_filter_neg _ _ _ }, rw [mem_coe, mem_filter] at hs, exact not_imp_comm.1 erase_eq_of_not_mem (ne_of_mem_of_not_mem hs.1 hs.2).symm, end end down
62718852eb60db3b510cc9b94bf8528cac303d46
50b3917f95cf9fe84639812ea0461b38f8f0dbe1
/Examples/sheaf_on_opens_total_glueing.lean
c775f30e6eea4083966aa59cad476e636ac36365
[]
no_license
roro47/xena
6389bcd7dcf395656a2c85cfc90a4366e9b825bb
237910190de38d6ff43694ffe3a9b68f79363e6c
refs/heads/master
1,598,570,061,948
1,570,052,567,000
1,570,052,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,166
lean
import order.lattice -- for lattice.semilattice_inf import order.bounds -- for is_lub import algebra.ring -- for is_ring_hom import topology.opens -- only for the conjecture that i need precisely opens α --import sheaves.sheaf -- import sheaves.covering.covering -- import sheaves.presheaf import data.equiv.basic import tactic.where -- cool debugging tool -- this is the only non-mathlib import. Should that stuff be in mathlib -- or not? If not then feel free to rewrite the below. -- In the Xena project this import is in src/ import for_mathlib_complete_lattice --open lattice universes v u open lattice structure presheaf (α : Type u) [semilattice_inf α] := (F : α → Type v) (res : ∀ (U V) (HVU : V ≤ U), F U → F V) (Hid : ∀ (U), res U U (le_refl U) = id) (Hcomp : ∀ (U V W) (HWV : W ≤ V) (HVU : V ≤ U), res U W (le_trans HWV HVU) = res V W HWV ∘ res U V HVU) namespace presheaf variables {α : Type u} [semilattice_inf α] instance : has_coe_to_fun (presheaf α) := { F := λ _, α → Type v, coe := presheaf.F } -- Simplification lemmas for Hid and Hcomp. @[simp] lemma Hcomp' (F : presheaf α) : ∀ (U V W) (HWV : W ≤ V) (HVU : V ≤ U) (s : F U), (F.res U W (le_trans HWV HVU)) s = (F.res V W HWV) ((F.res U V HVU) s) := λ U V W HWV HVU s, by rw F.Hcomp U V W HWV HVU @[simp] lemma Hid' (F : presheaf α) : ∀ (U) (s : F U), (F.res U U (le_refl U)) s = s := λ U s, by rw F.Hid U; simp def total (F : presheaf α) : Type (max u v) := Σ U, F.F U instance (F : presheaf α) (U : α) : has_coe_t (F U) F.total := ⟨sigma.mk _⟩ @[elab_as_eliminator] theorem total.cases_on (F : presheaf α) {C : F.total → Sort*} (x) (H : ∀ U (x : F U), C x) : C x := by cases x; apply H def res' (F : presheaf α) (V : α) : F.total → F.total | ⟨U, x⟩ := F.res U (U ⊓ V) inf_le_left x theorem res'_def (F : presheaf α) {U V} (x : F U) : F.res' V x = F.res U (U ⊓ V) inf_le_left x := rfl theorem res'_val (F : presheaf α) {U V} (x : F U) (h : V ≤ U) : F.res' V x = F.res U V h x := have ∀ W (H : W ≤ U), W = V → (F.res U W H x : F.total) = F.res U V h x := by rintro _ _ rfl; refl, this _ _ (inf_of_le_right h) theorem res'_eq_inf (F : presheaf α) {U V} (x : F U) : F.res' V x = F.res' (U ⊓ V) x := by rw [res'_def, ← res'_val _ _ inf_le_left] theorem res'_eq_left (F : presheaf α) {U V W} (x : F U) (H : U ⊓ V = U ⊓ W) : F.res' V x = F.res' W x := by rw [res'_eq_inf, H, ← res'_eq_inf] @[simp] theorem res'_id {F : presheaf α} {U} (x : F U) : F.res' U x = x := by rw [res'_val _ _ (le_refl U), F.Hid]; refl @[simp] theorem res'_comp {F : presheaf α} {U V} (x : F.total) : F.res' U (F.res' V x) = F.res' (U ⊓ V) x := total.cases_on F x $ λ W x, by rw [res'_def, res'_def, ← F.Hcomp', ← res'_val, res'_eq_left]; simp [inf_left_comm, inf_comm] def locality (F : presheaf α) := ∀ {{U S}}, is_lub S U → ∀ {{s t : F U}}, (∀ V ∈ S, F.res' V s = F.res' V t) → s = t def gluing (F : presheaf α) := ∀ {{U : α}} {{S}}, is_lub S U → ∀ (s : Π V : S, F V), (∀ V W : S, res' F (V ⊓ W) (s V) = res' F (V ⊓ W) (s W)) → ∃ x : F U, ∀ V:S, F.res' V x = s V end presheaf structure sheaf (α : Type u) [semilattice_inf α] extends presheaf α := (locality : to_presheaf.locality) (gluing : to_presheaf.gluing) structure sheaf_of_rings (α : Type u) [semilattice_inf α] extends sheaf α := [ring : ∀ U, ring (F U)] [ring_hom : ∀ U V h, is_ring_hom (res U V h)] --#where universes w u₁ v₁ /- memo for porting opens X -> α top space X -> sdemilattice_inf α -/ -- open topological_space def sheaf_on_opens (α : Type u) [semilattice_inf α] (U : α) : Type (max u (v+1)) := sheaf.{u v} α namespace sheaf_on_opens variables {α : Type u} [semilattice_inf α] {U : α} def eval (F : sheaf_on_opens α U) (V : α) (HVU : V ≤ U) : Type v := presheaf.F (sheaf.to_presheaf F) V def res (F : sheaf_on_opens α U) (V : α) (HVU : V ≤ U) (W : α) (HWU : W ≤ U) (HWV : W ≤ V) : F.eval V HVU → F.eval W HWU := presheaf.res _ _ _ HWV theorem res_comp (F : sheaf_on_opens α U) (V1 : α) (HV1 : V1 ≤ U) (V2 : α) (HV2 : V2 ≤ U) (V3 : α) (HV3 : V3 ≤ U) (H12 : V2 ≤ V1) (H23 : V3 ≤ V2) (f : F.eval V1 HV1) : F.res V2 HV2 V3 HV3 H23 (F.res V1 HV1 V2 HV2 H12 f) = F.res V1 HV1 V3 HV3 (le_trans H23 H12) f := (F.to_presheaf.Hcomp' _ _ _ _ _ f).symm def res_subset (F : sheaf_on_opens α U) (V : α) (HVU : V ≤ U) : sheaf_on_opens α V := F theorem eval_res_subset (F : sheaf_on_opens α U) (V : α) (HVU : V ≤ U) (W : α) (HWV : W ≤ V) : eval (res_subset F V HVU) W HWV = eval F W (le_trans HWV HVU) := rfl structure morphism (F : sheaf_on_opens.{v} α U) (G : sheaf_on_opens.{w} α U) : Type (max u v w) := (map : ∀ V ≤ U, F.eval V H → G.eval V H) (commutes : ∀ (V : α) (HV : V ≤ U) (W : α) (HW : W ≤ U) (HWV : W ≤ V) (x), map W HW (F.res V HV W HW HWV x) = G.res V HV W HW HWV (map V HV x)) namespace morphism protected def id (F : sheaf_on_opens.{v} α U) : F.morphism F := { map := λ V HV, id, commutes := λ V HV W HW HWV x, rfl } def comp {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{w} α U} {H : sheaf_on_opens.{u₁} α U} (η : G.morphism H) (ξ : F.morphism G) : F.morphism H := { map := λ V HV x, η.map V HV (ξ.map V HV x), commutes := λ V HV W HW HWV x, by rw [ξ.commutes, η.commutes] } @[extensionality] lemma ext {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{w} α U} {η ξ : F.morphism G} (H : ∀ V HV x, η.map V HV x = ξ.map V HV x) : η = ξ := by cases η; cases ξ; congr; ext; apply H @[simp] lemma id_comp {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{w} α U} (η : F.morphism G) : (morphism.id G).comp η = η := ext $ λ V HV x, rfl @[simp] lemma comp_id {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{w} α U} (η : F.morphism G) : η.comp (morphism.id F) = η := ext $ λ V HV x, rfl @[simp] lemma comp_assoc {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{w} α U} {H : sheaf_on_opens.{u₁} α U} {I : sheaf_on_opens.{v₁} α U} (η : H.morphism I) (ξ : G.morphism H) (χ : F.morphism G) : (η.comp ξ).comp χ = η.comp (ξ.comp χ) := rfl def res_subset {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{w} α U} (η : F.morphism G) (V : α) (HVU : V ≤ U) : (F.res_subset V HVU).morphism (G.res_subset V HVU) := { map := λ W HWV, η.map W (le_trans HWV HVU), commutes := λ S HSV T HTV, η.commutes S (le_trans HSV HVU) T (le_trans HTV HVU) } @[simp] lemma comp_res_subset {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{w} α U} {H : sheaf_on_opens.{u₁} α U} (η : G.morphism H) (ξ : F.morphism G) (V : α) (HVU : V ≤ U) : (η.res_subset V HVU).comp (ξ.res_subset V HVU) = (η.comp ξ).res_subset V HVU := rfl @[simp] lemma id_res_subset {F : sheaf_on_opens.{v} α U} (V : α) (HVU : V ≤ U) : (morphism.id F).res_subset V HVU = morphism.id (F.res_subset V HVU) := rfl end morphism -- #where structure equiv (F : sheaf_on_opens.{v} α U) (G : sheaf_on_opens.{w} α U) : Type (max u v w) := (to_fun : morphism F G) (inv_fun : morphism G F) (left_inv : inv_fun.comp to_fun = morphism.id F) (right_inv : to_fun.comp inv_fun = morphism.id G) namespace equiv def refl (F : sheaf_on_opens.{v} α U) : equiv F F := ⟨morphism.id F, morphism.id F, rfl, rfl⟩ def symm {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{v} α U} (e : equiv F G) : equiv G F := ⟨e.2, e.1, e.4, e.3⟩ def trans {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{v} α U} {H : sheaf_on_opens.{u₁} α U} (e₁ : equiv F G) (e₂ : equiv G H) : equiv F H := ⟨e₂.1.comp e₁.1, e₁.2.comp e₂.2, by rw [morphism.comp_assoc, ← e₂.2.comp_assoc, e₂.3, morphism.id_comp, e₁.3], by rw [morphism.comp_assoc, ← e₁.1.comp_assoc, e₁.4, morphism.id_comp, e₂.4]⟩ def res_subset {F : sheaf_on_opens.{v} α U} {G : sheaf_on_opens.{w} α U} (e : equiv F G) (V : α) (HVU : V ≤ U) : equiv (F.res_subset V HVU) (G.res_subset V HVU) := ⟨e.1.res_subset V HVU, e.2.res_subset V HVU, by rw [morphism.comp_res_subset, e.3, morphism.id_res_subset], by rw [morphism.comp_res_subset, e.4, morphism.id_res_subset]⟩ end equiv end sheaf_on_opens /- ** TODO ** #check @lattice.supr supr : Π {α : Type u_1} {ι : Sort u_2} [_inst_1 : has_Sup α], (ι → α) → α Why not supr : Π {α : Type u_1} [_inst_1 : has_Sup α] {ι : Sort u_2}, (ι → α) → α -/ def complete_lattice.supr (α : Type u) (ι : Sort v) [X : complete_lattice α] := @lattice.supr α ι _ -- Grumpy old mathematician observes that stupid polymorphism -- makes me have to fill in more stuff theorem complete_lattice.subset_Union (α : Type u) [X : complete_lattice α] {I : Type} (s : I → α) (i : I) : s i ≤ supr s := lattice.complete_lattice.le_supr s i --def complete_lattice.Union : Π {I : Type 37}, (I → α) → α --#check complete_lattice.supr -- fails /-- thing I need -/ structure thing (α : Type u) extends semilattice_inf α := (supr {ι : Sort v} (s : ι → α) : α) (le_supr {ι : Sort v} : ∀ (s : ι → α) (i : ι), s i ≤ supr s) /- hey -- that just *forced* me to make `thing.le_supr` have inputs in the following order: thing.le_supr : ∀ {α : Type u_2} (c : thing α) {ι : Sort u_1} (s : ι → α) (i : ι), s i ≤ c.supr s But lattice.le_supr : ∀ {α : Type u_1} {ι : Sort u_2} [_inst_1 : lattice.complete_lattice α] (s : ι → α) (i : ι), s i ≤ lattice.supr s -/ namespace thing -- Debugging starts here. -- structure thing (α : Type u) extends semilattice_inf α := -- #print semilattice_inf /- /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) @[class] structure lattice.semilattice_inf : Type u → Type u fields: ... -/ -- #print notation ⊓ -- lattice.has_inf.inf at 70 -- #check semilattice_inf -- class semilattice_inf (α : Type u) extends has_inf α, partial_order α := --#where /- structure thing (α : Type u) extends semilattice_inf α := (supr {ι : Sort v} (s : ι → α) : α) (le_supr {ι : Sort v} : ∀ (s : ι → α) (i : ι), s i ≤ supr s) -/ --#print semilattice_inf -- it's a class example (α : Type u) [bounded_lattice α] [has_Sup α] [has_Inf α] [lattice.complete_lattice α] : semilattice_inf α := by apply_instance -- #print lattice.complete_lattice /- class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) -/ set_option pp.structure_instances true def canonical2.to_fun (α : Type u) [lattice.complete_lattice α] : thing.{v} α := begin --let this : semilattice_inf α := by apply_instance, refine { inf := semilattice_inf.inf, le := semilattice_inf.le, le_refl := semilattice_inf.le_refl, le_trans := semilattice_inf.le_trans, le_antisymm := semilattice_inf.le_antisymm, -- inf_le_inf := semilattice_inf.inf_le_inf, inf_le_left := semilattice_inf.inf_le_left, inf_le_right := semilattice_inf.inf_le_right, le_inf := semilattice_inf.le_inf, -- the rest are not from semilattice namespace le_supr := λ (ι : Sort v) s, begin convert lattice.complete_lattice.le_supr s, convert rfl end,--convert rfl using 0, congr', ext, convert iff.rfl, ext, convert iff.rfl, ext, convert iff.rfl, sorry end, supr := λ ι s, lattice.complete_lattice.supr s, }, end #exit def canonical2.inv_fun (α : Type u) [lattice.complete_lattice α] : thing.{v} α := begin #exit begin sorry end #exit apply ..X, { supr := λ ι s, lattice.complete_lattice.supr,--∀ {ι : Sort v} (s : ι → α), α := λ ι s, lattice.complete_lattice.supr, le_supr {ι : Sort v} : ∀ (s : ι → α) (i : ι), s i ≤ supr s := sorry} #exit -- by apply_instance #exit -- semilattice_inf begin letI : has_inf α := by apply_instance, letI : partial_order α := by apply_instance, exactI { inf := X.inf, le := _, le_refl := X.le_refl, le_trans := begin convert X.le_trans, ext, convert iff.rfl, ext, sorry end, le_antisymm := _, -- TODO : convert docstring does not mention inf_le_left := begin convert X.inf_le_left, convert rfl, convert rfl, sorry end, inf_le_right := _, le_inf := _ }, repeat {sorry} end #exit { inf := _, le := _, lt := _, le_refl := _, le_trans := _, lt_iff_le_not_le := _, le_antisymm := _, inf_le_left := _, inf_le_right := _, le_inf := _ } --#where -- thing is a structure, complete_lattice is a class --#print lattice.complete_lattice /- Mario: complete_lattice <- bounded_lattice <- lattice, order_top, order_bot and lattice <- semilattice_sup, semilattice_inf <- partial order Lean: class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α := -/ --def lattice.complete_lattice.supr := sorry def canonical1.to_fun (α : Type u) [bounded_lattice α] [has_Sup α] [has_Inf α] [X : lattice.complete_lattice α] : thing α := begin resetI, exact { inf := _, le := X.le, le_refl := X.le_refl, le_trans := X.le_trans, le_antisymm := X.le_antisymm, inf_le_left := X.inf_le_left, inf_le_right := X.inf_le_right, le_inf := X.le_inf, supr := X.supr, le_supr := _ }, repeat {sorry}, end #exit def canonical1 (α : Type u) : _root_.equiv (lattice.complete_lattice α) (thing α) := { to_fun := λ X, { inf := _, le := X.le, le_refl := X.le_refl, le_trans := X.le_trans, le_antisymm := X.le_antisymm, inf_le_left := X.inf_le_left, inf_le_right := X.inf_le_right, le_inf := X.le_inf, supr := λ I, @lattice.supr α I (by resetI; apply_instance), -- bit of an effort! le_supr := λ ι, @lattice.complete_lattice.le_supr _ ι (by resetI; apply_instance),--==s i ≤ lattice.supr s@lattice.complete_lattice.le_supr ,--==lattice.complete_lattice.le_supr},--begin sorry, end, },inv_fun := λ Y, by exact { sup := _, le := Y.le, lt := _, le_refl := _, le_trans := _, lt_iff_le_not_le := Y.lt_iff_le_not_le, le_antisymm := _, le_sup_left := begin convert Y.le_sup_left, sorry end--sorry, -- I hate it when sorry is underlined le_sup_right := _, sup_le := _, inf := _, inf_le_left := _, inf_le_right := _, le_inf := _, top := _, le_top := _, bot := _, bot_le := _, Sup := _, Inf := _, le_Sup := _, Sup_le := _, Inf_le := _, le_Inf := _ }, left_inv := λ X, _, right_inv := sorry } #exit #print canonical1.le _root_.equiv (thing α) (topological_space.opens (thing.Union α )) := { to_fun := begin rintro ⟨SLIα,U,sU⟩, end, inv_fun := _, left_inv := _, right_inv := _ } -- should be in mathlib #check semilattice_inf namespace opens def Union {I : Type*} (s : I → α) : α := ⟨set.Union (λ i, (s i).1), is_open_Union (λ i, (s i).2)⟩ variables {I : Type*} (s : I → α) theorem subset_Union : ∀ (s : I → α) (i : I), s i ≤ Union s := -- why does lattice.le_supr need complete lattice? λ s i x hx, set.mem_Union.2 ⟨i, hx⟩ /- Other things I might need about this Union @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate ∃i, ... ∧ i = t ∧ ... theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ set.lattice_set _ _ h theorem Union_subset_iff {α : Sort u} {s : α → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t):= ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr theorem Union_const [inhabited ι] (s : set β) : (⋃ i:ι, s) = s := ext $ by simp theorem inter_Union_left (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem inter_Union_right (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem union_Union_left [inhabited ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := by rw [Union_union_distrib, Union_const] theorem union_Union_right [inhabited ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := by rw [Union_union_distrib, Union_const] theorem diff_Union_right (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := inter_Union_right _ _ -/ end opens def glue {I : Type*} (S : I → α) (F : Π (i : I), sheaf_on_opens.{v} α (S i)) (φ : Π (i j : I), equiv ((F i).res_subset ((S i) ∩ (S j)) (set.inter_subset_left _ _)) ((F j).res_subset ((S i) ∩ (S j)) (set.inter_subset_right _ _))) (Hφ1 : ∀ i, φ i i = equiv.refl (F i)) (Hφ2 : ∀ i j k, ((φ i j).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.inter_subset_left _ _)).trans ((φ j k).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.inter_subset_right _ _))) = (φ i k).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_left _ _)) (set.inter_subset_right _ _))) : sheaf_on_opens.{max u v} α (opens.Union S) := { F := { F := λ W, { f : Π i, (F i).eval ((S i) ∩ W) (set.inter_subset_left _ _) // ∀ i j, (φ i j).1.map ((S i) ∩ (S j) ∩ W) (set.inter_subset_left _ _) ((F i).res ((S i) ∩ W) _ _ (le_trans (set.inter_subset_left _ _) (set.inter_subset_left _ _)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_left _ _)) (set.inter_subset_right _ _)) (f i)) = (F j).res ((S j) ∩ W) _ _ (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.inter_subset_right _ _)) (f j) }, res := λ U V HUV f, ⟨λ i, (F i).res (S i ∩ U) _ (S i ∩ V) _ (set.inter_subset_inter_right _ HUV) (f.val i), begin intros i j, rw res_comp, rw res_comp, have answer := congr_arg (res (F j) (S i ∩ (S j) ∩ U) _ (S i ∩ (S j) ∩ V) (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.inter_subset_inter_right _ HUV) ) (f.property i j), rw res_comp at answer, rw ←answer, clear answer, convert (φ i j).to_fun.commutes (S i ∩ (S j) ∩ U) (set.inter_subset_left _ _) (S i ∩ (S j) ∩ V) (set.inter_subset_left _ _) (set.inter_subset_inter_right _ HUV) ( (@sheaf_on_opens.res _ _ (S i ∩ U) (F i) (S i ∩ U) (by refl) (S i ∩ S j ∩ U) (set.inter_subset_inter_left _ (set.inter_subset_left _ _)) (set.inter_subset_inter_left _ (set.inter_subset_left _ _)) (f.val i) ) ) using 2, convert (F i).F.Hcomp' (S i ∩ U) (S i ∩ S j ∩ U) (S i ∩ S j ∩ V) _ _ (f.val i), end⟩, Hid := begin sorry end, Hcomp := sorry }, locality := sorry, gluing := sorry } def universal_property (I : Type*) (S : I → α) (F : Π (i : I), sheaf_on_opens.{v} α (S i)) (φ : Π (i j : I), equiv ((F i).res_subset ((S i) ∩ (S j)) (set.inter_subset_left _ _)) ((F j).res_subset ((S i) ∩ (S j)) (set.inter_subset_right _ _))) (Hφ1 : ∀ i, φ i i = equiv.refl (F i)) (Hφ2 : ∀ i j k, ((φ i j).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.inter_subset_left _ _)).trans ((φ j k).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.inter_subset_right _ _))) = (φ i k).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_left _ _)) (set.inter_subset_right _ _))) : ∀ i : I, equiv (res_subset (glue S F φ Hφ1 Hφ2) (S i) $ opens.subset_Union S i) (F i) := sorry -- You are the winner if you get this far end sheaf_on_opens
a4d1ba63b11c773f4d7798ec738c89de5b66033a
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/support.lean
edff54bb49ddb32b4b7db670a3dc4a8bda3f58ab
[ "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
12,389
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 order.conditionally_complete_lattice import algebra.big_operators.basic import algebra.group.prod import algebra.group.pi import algebra.module.pi /-! # Support of a function In this file we define `function.support f = {x | f x ≠ 0}` and prove its basic properties. We also define `function.mul_support f = {x | f x ≠ 1}`. -/ open set open_locale big_operators namespace function variables {α β A B M N P R S G M₀ G₀ : Type*} {ι : Sort*} section has_one variables [has_one M] [has_one N] [has_one P] /-- `support` of a function is the set of points `x` such that `f x ≠ 0`. -/ def support [has_zero A] (f : α → A) : set α := {x | f x ≠ 0} /-- `mul_support` of a function is the set of points `x` such that `f x ≠ 1`. -/ @[to_additive] def mul_support (f : α → M) : set α := {x | f x ≠ 1} @[to_additive] lemma mul_support_eq_preimage (f : α → M) : mul_support f = f ⁻¹' {1}ᶜ := rfl @[to_additive] lemma nmem_mul_support {f : α → M} {x : α} : x ∉ mul_support f ↔ f x = 1 := not_not @[to_additive] lemma compl_mul_support {f : α → M} : (mul_support f)ᶜ = {x | f x = 1} := ext $ λ x, nmem_mul_support @[simp, to_additive] lemma mem_mul_support {f : α → M} {x : α} : x ∈ mul_support f ↔ f x ≠ 1 := iff.rfl @[simp, to_additive] lemma mul_support_subset_iff {f : α → M} {s : set α} : mul_support f ⊆ s ↔ ∀ x, f x ≠ 1 → x ∈ s := iff.rfl @[to_additive] lemma mul_support_subset_iff' {f : α → M} {s : set α} : mul_support f ⊆ s ↔ ∀ x ∉ s, f x = 1 := forall_congr $ λ x, not_imp_comm @[to_additive] lemma mul_support_disjoint_iff {f : α → M} {s : set α} : disjoint (mul_support f) s ↔ eq_on f 1 s := by simp_rw [←subset_compl_iff_disjoint_right, mul_support_subset_iff', not_mem_compl_iff, eq_on, pi.one_apply] @[to_additive] lemma disjoint_mul_support_iff {f : α → M} {s : set α} : disjoint s (mul_support f) ↔ eq_on f 1 s := by rw [disjoint.comm, mul_support_disjoint_iff] @[simp, to_additive] lemma mul_support_eq_empty_iff {f : α → M} : mul_support f = ∅ ↔ f = 1 := by { simp_rw [← subset_empty_iff, mul_support_subset_iff', funext_iff], simp } @[simp, to_additive] lemma mul_support_nonempty_iff {f : α → M} : (mul_support f).nonempty ↔ f ≠ 1 := by rw [← ne_empty_iff_nonempty, ne.def, mul_support_eq_empty_iff] @[to_additive] lemma range_subset_insert_image_mul_support (f : α → M) : range f ⊆ insert 1 (f '' mul_support f) := begin intros y hy, rcases eq_or_ne y 1 with rfl|h2y, { exact mem_insert _ _ }, { obtain ⟨x, rfl⟩ := hy, refine mem_insert_of_mem _ ⟨x, h2y, rfl⟩ } end @[simp, to_additive] lemma mul_support_one' : mul_support (1 : α → M) = ∅ := mul_support_eq_empty_iff.2 rfl @[simp, to_additive] lemma mul_support_one : mul_support (λ x : α, (1 : M)) = ∅ := mul_support_one' @[to_additive] lemma mul_support_const {c : M} (hc : c ≠ 1) : mul_support (λ x : α, c) = set.univ := by { ext x, simp [hc] } @[to_additive] lemma mul_support_binop_subset (op : M → N → P) (op1 : op 1 1 = 1) (f : α → M) (g : α → N) : mul_support (λ x, op (f x) (g x)) ⊆ mul_support f ∪ mul_support g := λ x hx, classical.by_cases (λ hf : f x = 1, or.inr $ λ hg, hx $ by simp only [hf, hg, op1]) or.inl @[to_additive] lemma mul_support_sup [semilattice_sup M] (f g : α → M) : mul_support (λ x, f x ⊔ g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (⊔) sup_idem f g @[to_additive] lemma mul_support_inf [semilattice_inf M] (f g : α → M) : mul_support (λ x, f x ⊓ g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (⊓) inf_idem f g @[to_additive] lemma mul_support_max [linear_order M] (f g : α → M) : mul_support (λ x, max (f x) (g x)) ⊆ mul_support f ∪ mul_support g := mul_support_sup f g @[to_additive] lemma mul_support_min [linear_order M] (f g : α → M) : mul_support (λ x, min (f x) (g x)) ⊆ mul_support f ∪ mul_support g := mul_support_inf f g @[to_additive] lemma mul_support_supr [conditionally_complete_lattice M] [nonempty ι] (f : ι → α → M) : mul_support (λ x, ⨆ i, f i x) ⊆ ⋃ i, mul_support (f i) := begin rw mul_support_subset_iff', simp only [mem_Union, not_exists, nmem_mul_support], intros x hx, simp only [hx, csupr_const] end @[to_additive] lemma mul_support_infi [conditionally_complete_lattice M] [nonempty ι] (f : ι → α → M) : mul_support (λ x, ⨅ i, f i x) ⊆ ⋃ i, mul_support (f i) := @mul_support_supr _ Mᵒᵈ ι ⟨(1:M)⟩ _ _ f @[to_additive] lemma mul_support_comp_subset {g : M → N} (hg : g 1 = 1) (f : α → M) : mul_support (g ∘ f) ⊆ mul_support f := λ x, mt $ λ h, by simp only [(∘), *] @[to_additive] lemma mul_support_subset_comp {g : M → N} (hg : ∀ {x}, g x = 1 → x = 1) (f : α → M) : mul_support f ⊆ mul_support (g ∘ f) := λ x, mt hg @[to_additive] lemma mul_support_comp_eq (g : M → N) (hg : ∀ {x}, g x = 1 ↔ x = 1) (f : α → M) : mul_support (g ∘ f) = mul_support f := set.ext $ λ x, not_congr hg @[to_additive] lemma mul_support_comp_eq_preimage (g : β → M) (f : α → β) : mul_support (g ∘ f) = f ⁻¹' mul_support g := rfl @[to_additive support_prod_mk] lemma mul_support_prod_mk (f : α → M) (g : α → N) : mul_support (λ x, (f x, g x)) = mul_support f ∪ mul_support g := set.ext $ λ x, by simp only [mul_support, not_and_distrib, mem_union_eq, mem_set_of_eq, prod.mk_eq_one, ne.def] @[to_additive support_prod_mk'] lemma mul_support_prod_mk' (f : α → M × N) : mul_support f = mul_support (λ x, (f x).1) ∪ mul_support (λ x, (f x).2) := by simp only [← mul_support_prod_mk, prod.mk.eta] @[to_additive] lemma mul_support_along_fiber_subset (f : α × β → M) (a : α) : mul_support (λ b, f (a, b)) ⊆ (mul_support f).image prod.snd := by tidy @[simp, to_additive] lemma mul_support_along_fiber_finite_of_finite (f : α × β → M) (a : α) (h : (mul_support f).finite) : (mul_support (λ b, f (a, b))).finite := (h.image prod.snd).subset (mul_support_along_fiber_subset f a) end has_one @[to_additive] lemma mul_support_mul [mul_one_class M] (f g : α → M) : mul_support (λ x, f x * g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (*) (one_mul _) f g @[to_additive] lemma mul_support_pow [monoid M] (f : α → M) (n : ℕ) : mul_support (λ x, f x ^ n) ⊆ mul_support f := begin induction n with n hfn, { simpa only [pow_zero, mul_support_one] using empty_subset _ }, { simpa only [pow_succ] using subset_trans (mul_support_mul f _) (union_subset (subset.refl _) hfn) } end section division_monoid variables [division_monoid G] (f g : α → G) @[simp, to_additive] lemma mul_support_inv : mul_support (λ x, (f x)⁻¹) = mul_support f := ext $ λ _, inv_ne_one @[simp, to_additive] lemma mul_support_inv' : mul_support f⁻¹ = mul_support f := mul_support_inv f @[to_additive] lemma mul_support_mul_inv : mul_support (λ x, f x * (g x)⁻¹) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (λ a b, a * b⁻¹) (by simp) f g @[to_additive] lemma mul_support_div : mul_support (λ x, f x / g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (/) one_div_one f g end division_monoid @[simp] lemma support_mul [mul_zero_class R] [no_zero_divisors R] (f g : α → R) : support (λ x, f x * g x) = support f ∩ support g := set.ext $ λ x, by simp only [mem_support, mul_ne_zero_iff, mem_inter_eq, not_or_distrib] @[simp] lemma support_mul_subset_left [mul_zero_class R] (f g : α → R) : support (λ x, f x * g x) ⊆ support f := λ x hfg hf, hfg $ by simp only [hf, zero_mul] @[simp] lemma support_mul_subset_right [mul_zero_class R] (f g : α → R) : support (λ x, f x * g x) ⊆ support g := λ x hfg hg, hfg $ by simp only [hg, mul_zero] lemma support_smul_subset_right [add_monoid A] [monoid B] [distrib_mul_action B A] (b : B) (f : α → A) : support (b • f) ⊆ support f := λ x hbf hf, hbf $ by rw [pi.smul_apply, hf, smul_zero] lemma support_smul_subset_left [semiring R] [add_comm_monoid M] [module R M] (f : α → R) (g : α → M) : support (f • g) ⊆ support f := λ x hfg hf, hfg $ by rw [pi.smul_apply', hf, zero_smul] lemma support_smul [semiring R] [add_comm_monoid M] [module R M] [no_zero_smul_divisors R M] (f : α → R) (g : α → M) : support (f • g) = support f ∩ support g := ext $ λ x, smul_ne_zero lemma support_const_smul_of_ne_zero [semiring R] [add_comm_monoid M] [module R M] [no_zero_smul_divisors R M] (c : R) (g : α → M) (hc : c ≠ 0) : support (c • g) = support g := ext $ λ x, by simp only [hc, mem_support, pi.smul_apply, ne.def, smul_eq_zero, false_or] @[simp] lemma support_inv [group_with_zero G₀] (f : α → G₀) : support (λ x, (f x)⁻¹) = support f := set.ext $ λ x, not_congr inv_eq_zero @[simp] lemma support_div [group_with_zero G₀] (f g : α → G₀) : support (λ x, f x / g x) = support f ∩ support g := by simp [div_eq_mul_inv] @[to_additive] lemma mul_support_prod [comm_monoid M] (s : finset α) (f : α → β → M) : mul_support (λ x, ∏ i in s, f i x) ⊆ ⋃ i ∈ s, mul_support (f i) := begin rw mul_support_subset_iff', simp only [mem_Union, not_exists, nmem_mul_support], exact λ x, finset.prod_eq_one end lemma support_prod_subset [comm_monoid_with_zero A] (s : finset α) (f : α → β → A) : support (λ x, ∏ i in s, f i x) ⊆ ⋂ i ∈ s, support (f i) := λ x hx, mem_Inter₂.2 $ λ i hi H, hx $ finset.prod_eq_zero hi H lemma support_prod [comm_monoid_with_zero A] [no_zero_divisors A] [nontrivial A] (s : finset α) (f : α → β → A) : support (λ x, ∏ i in s, f i x) = ⋂ i ∈ s, support (f i) := set.ext $ λ x, by simp only [support, ne.def, finset.prod_eq_zero_iff, mem_set_of_eq, set.mem_Inter, not_exists] lemma mul_support_one_add [has_one R] [add_left_cancel_monoid R] (f : α → R) : mul_support (λ x, 1 + f x) = support f := set.ext $ λ x, not_congr add_right_eq_self lemma mul_support_one_add' [has_one R] [add_left_cancel_monoid R] (f : α → R) : mul_support (1 + f) = support f := mul_support_one_add f lemma mul_support_add_one [has_one R] [add_right_cancel_monoid R] (f : α → R) : mul_support (λ x, f x + 1) = support f := set.ext $ λ x, not_congr add_left_eq_self lemma mul_support_add_one' [has_one R] [add_right_cancel_monoid R] (f : α → R) : mul_support (f + 1) = support f := mul_support_add_one f lemma mul_support_one_sub' [has_one R] [add_group R] (f : α → R) : mul_support (1 - f) = support f := by rw [sub_eq_add_neg, mul_support_one_add', support_neg'] lemma mul_support_one_sub [has_one R] [add_group R] (f : α → R) : mul_support (λ x, 1 - f x) = support f := mul_support_one_sub' f end function namespace set open function variables {α β M : Type*} [has_one M] {f : α → M} @[to_additive] lemma image_inter_mul_support_eq {s : set β} {g : β → α} : (g '' s ∩ mul_support f) = g '' (s ∩ mul_support (f ∘ g)) := by rw [mul_support_comp_eq_preimage f g, image_inter_preimage] end set namespace pi variables {A : Type*} {B : Type*} [decidable_eq A] [has_zero B] {a : A} {b : B} lemma support_single_zero : function.support (pi.single a (0 : B)) = ∅ := by simp @[simp] lemma support_single_of_ne (h : b ≠ 0) : function.support (pi.single a b) = {a} := begin ext, simp only [mem_singleton_iff, ne.def, function.mem_support], split, { contrapose!, exact λ h', single_eq_of_ne h' b }, { rintro rfl, rw single_eq_same, exact h } end lemma support_single [decidable_eq B] : function.support (pi.single a b) = if b = 0 then ∅ else {a} := by { split_ifs with h; simp [h] } lemma support_single_subset : function.support (pi.single a b) ⊆ {a} := begin classical, rw support_single, split_ifs; simp end lemma support_single_disjoint {b' : B} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : A} : disjoint (function.support (single i b)) (function.support (single j b')) ↔ i ≠ j := by rw [support_single_of_ne hb, support_single_of_ne hb', disjoint_singleton] end pi
5d699680d23aa046f3f527762a764637bd1acbbf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/matrix/dmatrix.lean
dacbb08124504f54133e1afaccc04630edbd9ab6
[ "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,446
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 data.fintype.basic /-! # Matrices -/ universes u u' v w z /-- `dmatrix m n` is the type of dependently typed matrices whose rows are indexed by the fintype `m` and whose columns are indexed by the fintype `n`. -/ @[nolint unused_arguments] def dmatrix (m : Type u) (n : Type u') [fintype m] [fintype n] (α : m → n → Type v) : Type (max u u' v) := Π i j, α i j variables {l m n o : Type*} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : m → n → Type v} namespace dmatrix section ext variables {M N : dmatrix 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 /-- `M.map f` is the dmatrix obtained by applying `f` to each entry of the matrix `M`. -/ def map (M : dmatrix m n α) {β : m → n → Type w} (f : Π ⦃i j⦄, α i j → β i j) : dmatrix m n β := λ i j, f (M i j) @[simp] lemma map_apply {M : dmatrix m n α} {β : m → n → Type w} {f : Π ⦃i j⦄, α i j → β i j} {i : m} {j : n} : M.map f i j = f (M i j) := rfl @[simp] lemma map_map {M : dmatrix m n α} {β : m → n → Type w} {γ : m → n → Type z} {f : Π ⦃i j⦄, α i j → β i j} {g : Π ⦃i j⦄, β i j → γ i j} : (M.map f).map g = M.map (λ i j x, g (f x)) := by { ext, simp, } /-- The transpose of a dmatrix. -/ def transpose (M : dmatrix m n α) : dmatrix n m (λ j i, α i j) | x y := M y x localized "postfix (name := dmatrix.transpose) `ᵀ`:1500 := dmatrix.transpose" in dmatrix /-- `dmatrix.col u` is the column matrix whose entries are given by `u`. -/ def col {α : m → Type v} (w : Π i, α i) : dmatrix m unit (λ i j, α i) | x y := w x /-- `dmatrix.row u` is the row matrix whose entries are given by `u`. -/ def row {α : n → Type v} (v : Π j, α j) : dmatrix unit n (λ i j, α j) | x y := v y instance [∀ i j, inhabited (α i j)] : inhabited (dmatrix m n α) := pi.inhabited _ instance [∀ i j, has_add (α i j)] : has_add (dmatrix m n α) := pi.has_add instance [∀ i j, add_semigroup (α i j)] : add_semigroup (dmatrix m n α) := pi.add_semigroup instance [∀ i j, add_comm_semigroup (α i j)] : add_comm_semigroup (dmatrix m n α) := pi.add_comm_semigroup instance [∀ i j, has_zero (α i j)] : has_zero (dmatrix m n α) := pi.has_zero instance [∀ i j, add_monoid (α i j)] : add_monoid (dmatrix m n α) := pi.add_monoid instance [∀ i j, add_comm_monoid (α i j)] : add_comm_monoid (dmatrix m n α) := pi.add_comm_monoid instance [∀ i j, has_neg (α i j)] : has_neg (dmatrix m n α) := pi.has_neg instance [∀ i j, has_sub (α i j)] : has_sub (dmatrix m n α) := pi.has_sub instance [∀ i j, add_group (α i j)] : add_group (dmatrix m n α) := pi.add_group instance [∀ i j, add_comm_group (α i j)] : add_comm_group (dmatrix m n α) := pi.add_comm_group instance [∀ i j, unique (α i j)] : unique (dmatrix m n α) := pi.unique instance [∀ i j, subsingleton (α i j)] : subsingleton (dmatrix m n α) := pi.subsingleton @[simp] theorem zero_apply [∀ i j, has_zero (α i j)] (i j) : (0 : dmatrix m n α) i j = 0 := rfl @[simp] theorem neg_apply [∀ i j, has_neg (α i j)] (M : dmatrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_apply [∀ i j, has_add (α i j)] (M N : dmatrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl @[simp] theorem sub_apply [∀ i j, has_sub (α i j)] (M N : dmatrix m n α) (i j) : (M - N) i j = M i j - N i j := rfl @[simp] lemma map_zero [∀ i j, has_zero (α i j)] {β : m → n → Type w} [∀ i j, has_zero (β i j)] {f : Π ⦃i j⦄, α i j → β i j} (h : ∀ i j, f (0 : α i j) = 0) : (0 : dmatrix m n α).map f = 0 := by { ext, simp [h], } lemma map_add [∀ i j, add_monoid (α i j)] {β : m → n → Type w} [∀ i j, add_monoid (β i j)] (f : Π ⦃i j⦄, α i j →+ β i j) (M N : dmatrix m n α) : (M + N).map (λ i j, @f i j) = M.map (λ i j, @f i j) + N.map (λ i j, @f i j) := by { ext, simp, } lemma map_sub [∀ i j, add_group (α i j)] {β : m → n → Type w} [∀ i j, add_group (β i j)] (f : Π ⦃i j⦄, α i j →+ β i j) (M N : dmatrix m n α) : (M - N).map (λ i j, @f i j) = M.map (λ i j, @f i j) - N.map (λ i j, @f i j) := by { ext, simp } instance subsingleton_of_empty_left [is_empty m] : subsingleton (dmatrix m n α) := ⟨λ M N, by { ext, exact is_empty_elim i }⟩ instance subsingleton_of_empty_right [is_empty n] : subsingleton (dmatrix m n α) := ⟨λ M N, by { ext, exact is_empty_elim j }⟩ end dmatrix /-- The `add_monoid_hom` between spaces of dependently typed matrices induced by an `add_monoid_hom` between their coefficients. -/ def add_monoid_hom.map_dmatrix [∀ i j, add_monoid (α i j)] {β : m → n → Type w} [∀ i j, add_monoid (β i j)] (f : Π ⦃i j⦄, α i j →+ β i j) : dmatrix m n α →+ dmatrix m n β := { to_fun := λ M, M.map (λ i j, @f i j), map_zero' := by simp, map_add' := dmatrix.map_add f, } @[simp] lemma add_monoid_hom.map_dmatrix_apply [∀ i j, add_monoid (α i j)] {β : m → n → Type w} [∀ i j, add_monoid (β i j)] (f : Π ⦃i j⦄, α i j →+ β i j) (M : dmatrix m n α) : add_monoid_hom.map_dmatrix f M = M.map (λ i j, @f i j) := rfl
412e76850ce258019f2de0a259f0687cada381bf
2f8bf12144551bc7d8087a6320990c4621741f3d
/library/init/lean/elaborator.lean
fa0281abb5b815f1e27c98af3e858b1218a983ef
[ "Apache-2.0" ]
permissive
jesse-michael-han/lean4
eb63a12960e69823749edceb4f23fd33fa2253ce
fa16920a6a7700cabc567aa629ce4ae2478a2f40
refs/heads/master
1,589,935,810,594
1,557,177,860,000
1,557,177,860,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
42,017
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich Elaborator for the Lean language: takes commands and produces side effects -/ prelude import init.lean.parser.module import init.lean.expander import init.lean.expr import init.lean.options namespace Lean -- TODO(Sebastian): should probably be meta together with the whole Elaborator constant environment : Type := Unit @[extern "lean_environment_contains"] constant environment.contains (env : @& environment) (n : @& Name) : Bool := false -- deprecated Constructor @[extern "lean_expr_local"] constant Expr.local (n : Name) (pp : Name) (ty : Expr) (bi : BinderInfo) : Expr := default Expr namespace Elaborator -- TODO(Sebastian): move -- TODO(Sebastian): should be its own Monad? structure NameGenerator := («prefix» : Name) (nextIdx : UInt32) structure SectionVar := (uniqName : Name) (BinderInfo : BinderInfo) (type : Expr) /-- Simplified State of the Lean 3 Parser. Maps are replaced with lists for easier interop. -/ structure OldElaboratorState := (env : environment) (ngen : NameGenerator) (univs : List (Name × Level)) (vars : List (Name × SectionVar)) (includeVars : List Name) (Options : Options) (nextInstIdx : Nat) (ns : Name) @[extern "lean_elaborator_elaborate_command"] constant elaborateCommand (filename : @& String) (e : Expr) (s : @& OldElaboratorState) : Option OldElaboratorState × MessageLog := (none, ⟨[]⟩) open Parser open Parser.Combinators open Parser.Term open Parser.command open Parser.command.NotationSpec open Expander -- TODO(Sebastian): move /-- An RBMap that remembers the insertion order. -/ structure OrderedRBMap (α β : Type) (lt : α → α → Bool) := (entries : List (α × β)) (map : RBMap α (Nat × β) lt) (size : Nat) namespace OrderedRBMap variables {α β : Type} {lt : α → α → Bool} (m : OrderedRBMap α β lt) def empty : OrderedRBMap α β lt := {entries := [], map := mkRBMap _ _ _, size := 0} def insert (k : α) (v : β) : OrderedRBMap α β lt := {entries := (k, v)::m.entries, map := m.map.insert k (m.size, v), size := m.size + 1} def find (a : α) : Option (Nat × β) := m.map.find a def ofList (l : List (α × β)) : OrderedRBMap α β lt := l.foldl (λ m p, OrderedRBMap.insert m (Prod.fst p) (Prod.snd p)) OrderedRBMap.empty end OrderedRBMap structure ElaboratorConfig extends FrontendConfig := (initialParserCfg : ModuleParserConfig) instance elaboratorConfigCoeFrontendConfig : HasCoe ElaboratorConfig FrontendConfig := ⟨ElaboratorConfig.toFrontendConfig⟩ /-- Elaborator State that will be reverted at the end of a section or namespace. -/ structure Scope := -- "section" or "namespace" (or "MODULE"), currently (cmd : String) -- Scope header, should match identifier after `end`. Can be `Name.anonymous` for sections. (header : Name) (notations : List NotationMacro := []) /- The set of local universe variables. We remember their insertion order so that we can keep the order when copying them to declarations. -/ (univs : OrderedRBMap Name Level Name.quickLt := OrderedRBMap.empty) /- The set of local variables. -/ (vars : OrderedRBMap Name SectionVar Name.quickLt := OrderedRBMap.empty) /- The subset of `vars` that is tagged as always included. -/ (includeVars : RBTree Name Name.quickLt := mkRBTree _ _) /- The stack of nested active `namespace` commands. -/ (nsStack : List Name := []) /- The set of active `open` declarations. -/ (openDecls : List openSpec.View := []) (Options : Options := {}) /-- An `export` command together with the namespace it was declared in. Opening the namespace activates the export. -/ structure ScopedExportDecl := (inNs : Name) (spec : openSpec.View) structure ElaboratorState := -- TODO(Sebastian): retrieve from environment (reservedNotations : List reserveNotation.View := []) (notations : List NotationMacro := []) (notationCounter := 0) /- The current set of `export` declarations (active or inactive). -/ (exportDecls : List ScopedExportDecl := []) -- Stack of current scopes. The bottom-most Scope is the Module Scope. (scopes : List Scope) (messages : MessageLog := MessageLog.empty) (parserCfg : ModuleParserConfig) (expanderCfg : Expander.ExpanderConfig) (env : environment) (ngen : NameGenerator) (nextInstIdx : Nat := 0) @[derive Monad MonadRec MonadReader MonadState MonadExcept] def ElaboratorM := RecT Syntax Unit $ ReaderT ElaboratorConfig $ StateT ElaboratorState $ ExceptT Message Id abbrev Elaborator := Syntax → ElaboratorM Unit instance elaboratorInh (α : Type) : Inhabited (ElaboratorM α) := ⟨λ _ _ _, Except.error (default _)⟩ /-- Recursively elaborate any command. -/ def command.elaborate : Elaborator := recurse def currentScope : ElaboratorM Scope := do st ← get, match st.scopes with | [] := error none "currentScope: unreachable" | sc::_ := pure sc def modifyCurrentScope (f : Scope → Scope) : ElaboratorM Unit := do st ← get, match st.scopes with | [] := error none "modifyCurrentScope: unreachable" | sc::scs := set {st with scopes := f sc::scs} def mangleIdent (id : SyntaxIdent) : Name := id.scopes.foldl Name.mkNumeral id.val partial def levelGetAppArgs : Syntax → ElaboratorM (Syntax × List Syntax) | stx := do match stx.kind with | some Level.leading := pure (stx, []) | some Level.trailing := match view Level.trailing stx with | Level.trailing.View.app lta := do (fn, args) ← levelGetAppArgs lta.fn, pure (fn, lta.Arg :: args) | Level.trailing.View.addLit _ := pure (stx, []) | _ := error stx $ "levelGetAppArgs: unexpected input: " ++ toString stx def levelAdd : Level → Nat → Level | l 0 := l | l (n+1) := (levelAdd l n).succ partial def toLevel : Syntax → ElaboratorM Level | stx := do (fn, args) ← levelGetAppArgs stx, sc ← currentScope, match fn.kind with | some Level.leading := match view Level.leading fn, args with | Level.leading.View.hole _, [] := pure $ Level.mvar Name.anonymous | Level.leading.View.lit lit, [] := pure $ Level.ofNat lit.toNat | Level.leading.View.var id, [] := let id := mangleIdent id in match sc.univs.find id with | some _ := pure $ Level.Param id | none := error stx $ "unknown universe variable '" ++ toString id ++ "'" | Level.leading.View.max _, (Arg::args) := List.foldr Level.max <$> toLevel Arg <*> args.mmap toLevel | Level.leading.View.imax _, (Arg::args) := List.foldr Level.imax <$> toLevel Arg <*> args.mmap toLevel | _, _ := error stx "ill-formed universe Level" | some Level.trailing := match view Level.trailing fn, args with | Level.trailing.View.addLit lta, [] := do l ← toLevel lta.lhs, pure $ levelAdd l lta.rhs.toNat | _, _ := error stx "ill-formed universe Level" | _ := error stx $ "toLevel: unexpected input: " ++ toString stx def Expr.mkAnnotation (ann : Name) (e : Expr) := Expr.mdata (MData.empty.setName `annotation ann) e def dummy : Expr := Expr.const `Prop [] def mkEqns (type : Expr) (eqns : List (Name × List Expr × Expr)): Expr := let eqns := eqns.map $ λ ⟨fn, lhs, rhs⟩, do { let fn := Expr.local fn fn type BinderInfo.auxDecl, let lhs := Expr.mkApp (Expr.mkAnnotation `@ fn) lhs, Expr.app lhs rhs } in Expr.mkAnnotation `preEquations $ Expr.mkCapp `_ eqns partial def toPexpr : Syntax → ElaboratorM Expr | stx@(Syntax.rawNode {kind := k, args := args}) := do e ← match k with | @identUnivs := do let v := view identUnivs stx, e ← match v with | {id := id, univs := some univs} := Expr.const (mangleIdent id) <$> univs.levels.mmap toLevel | {id := id, univs := none} := pure $ Expr.const (mangleIdent id) [], let m := MData.empty.setName `annotation `preresolved, let m := v.id.preresolved.enum.foldl (λ (m : MData) ⟨i, n⟩, m.setName (Name.anonymous.mkNumeral i) n) m, pure $ Expr.mdata m e | @app := let v := view app stx in Expr.app <$> toPexpr v.fn <*> toPexpr v.Arg | @lambda := do let lam := view lambda stx, binders.View.simple bnder ← pure lam.binders | error stx "ill-formed lambda", (bi, id, type) ← pure bnder.toBinderInfo, Expr.lam (mangleIdent id) bi <$> toPexpr type <*> toPexpr lam.body | @pi := do let v := view pi stx, binders.View.simple bnder ← pure v.binders | error stx "ill-formed pi", (bi, id, type) ← pure bnder.toBinderInfo, Expr.pi (mangleIdent id) bi <$> toPexpr type <*> toPexpr v.range | @sort := match view sort stx with | sort.View.Sort _ := pure $ Expr.sort Level.zero | sort.View.Type _ := pure $ Expr.sort $ Level.succ Level.zero | @sortApp := do let v := view sortApp stx, match view sort v.fn with | sort.View.Sort _ := Expr.sort <$> toLevel v.Arg | sort.View.Type _ := (Expr.sort ∘ Level.succ) <$> toLevel v.Arg | @anonymousConstructor := do let v := view anonymousConstructor stx, p ← toPexpr $ mkApp (review hole {}) (v.args.map SepBy.Elem.View.item), pure $ Expr.mkAnnotation `anonymousConstructor p | @hole := pure $ Expr.mvar Name.anonymous dummy | @«have» := do let v := view «have» stx, let id := (mangleIdent <$> optIdent.View.id <$> v.id).getOrElse `this, let proof := match v.proof with | haveProof.View.Term hpt := hpt.Term | haveProof.View.from hpf := hpf.from.proof, lam ← Expr.lam id BinderInfo.default <$> toPexpr v.prop <*> toPexpr v.body, Expr.app (Expr.mkAnnotation `have lam) <$> toPexpr proof | @«show» := do let v := view «show» stx, prop ← toPexpr v.prop, proof ← toPexpr v.from.proof, pure $ Expr.mkAnnotation `show $ Expr.app (Expr.lam `this BinderInfo.default prop $ Expr.bvar 0) proof | @«let» := do let v := view «let» stx, letLhs.View.id {id := id, binders := [], type := some ty} ← pure v.lhs | error stx "ill-formed let", Expr.elet (mangleIdent id) <$> toPexpr ty.type <*> toPexpr v.value <*> toPexpr v.body | @projection := do let v := view projection stx, let val := match v.proj with | projectionSpec.View.id id := DataValue.ofName id.val | projectionSpec.View.num n := DataValue.ofNat n.toNat, Expr.mdata (MData.empty.insert `fieldNotation val) <$> toPexpr v.Term | @explicit := do let v := view explicit stx, let ann := match v.mod with | explicitModifier.View.explicit _ := `@ | explicitModifier.View.partialExplicit _ := `@@, Expr.mkAnnotation ann <$> toPexpr (review identUnivs v.id) | @inaccessible := do let v := view inaccessible stx, Expr.mkAnnotation `innaccessible <$> toPexpr v.Term -- sic | @borrowed := do let v := view borrowed stx, Expr.mkAnnotation `borrowed <$> toPexpr v.Term | @number := do let v := view number stx, pure $ Expr.lit $ Literal.natVal v.toNat | @stringLit := do let v := view stringLit stx, pure $ Expr.lit $ Literal.strVal (v.value.getOrElse "NOTAString") | @choice := do last::rev ← List.reverse <$> args.mmap (λ a, toPexpr a) | error stx "ill-formed choice", pure $ Expr.mdata (MData.empty.setNat `choice args.length) $ rev.reverse.foldr Expr.app last | @structInst := do let v := view structInst stx, -- order should be: fields*, sources*, catchall? let (fields, other) := v.items.span (λ it, ↑match SepBy.Elem.View.item it with | structInstItem.View.field _ := true | _ := false), let (sources, catchall) := other.span (λ it, ↑match SepBy.Elem.View.item it with | structInstItem.View.source {source := some _} := true | _ := false), catchall ← match catchall with | [] := pure false | [{item := structInstItem.View.source _}] := pure true | {item := it}::_ := error (review structInstItem it) $ "unexpected item in structure instance notation", fields ← fields.mmap (λ f, match SepBy.Elem.View.item f with | structInstItem.View.field f := Expr.mdata (MData.empty.setName `field $ mangleIdent f.id) <$> toPexpr f.val | _ := error stx "toPexpr: unreachable"), sources ← sources.mmap (λ src, match SepBy.Elem.View.item src with | structInstItem.View.source {source := some src} := toPexpr src | _ := error stx "toPexpr: unreachable"), sources ← match v.with with | none := pure sources | some src := do { src ← toPexpr src.source, pure $ sources ++ [src]}, let m := MData.empty.setNat "structure instance" fields.length, let m := m.setBool `catchall catchall, let m := m.setName `struct $ (mangleIdent <$> structInstType.View.id <$> v.type).getOrElse Name.anonymous, let dummy := Expr.sort Level.zero, pure $ Expr.mdata m $ (fields ++ sources).foldr Expr.app dummy | @«match» := do let v := view «match» stx, eqns ← (v.equations.map SepBy.Elem.View.item).mmap $ λ (eqn : matchEquation.View), do { lhs ← eqn.lhs.mmap $ λ l, toPexpr l.item, rhs ← toPexpr eqn.rhs, pure (`_matchFn, lhs, rhs) }, type ← toPexpr $ getOptType v.type, let eqns := mkEqns type eqns, Expr.mdata mdata e ← pure eqns | error stx "toPexpr: unreachable", let eqns := Expr.mdata (mdata.setBool `match true) e, Expr.mkApp eqns <$> v.scrutinees.mmap (λ scr, toPexpr scr.item) | _ := error stx $ "toPexpr: unexpected Node: " ++ toString k.name, match k with | @app := pure e -- no Position | _ := do cfg ← read, match stx.getPos with | some pos := let pos := cfg.fileMap.toPosition pos in pure $ Expr.mdata ((MData.empty.setNat `column pos.column).setNat `row pos.line) e | none := pure e | stx := error stx $ "toPexpr: unexpected: " ++ toString stx /-- Returns the active namespace, that is, the concatenation of all active `namespace` commands. -/ def getNamespace : ElaboratorM Name := do sc ← currentScope, pure $ match sc.nsStack with | ns::_ := ns | _ := Name.anonymous def oldElabCommand (stx : Syntax) (cmd : Expr) : ElaboratorM Unit := do cfg ← read, let pos := cfg.fileMap.toPosition $ stx.getPos.getOrElse (default _), let cmd := match cmd with | Expr.mdata m e := Expr.mdata ((m.setNat `column pos.column).setNat `row pos.line) e | e := e, st ← get, sc ← currentScope, ns ← getNamespace, let (st', msgs) := elaborateCommand cfg.filename cmd { ns := ns, univs := sc.univs.entries.reverse, vars := sc.vars.entries.reverse, includeVars := sc.includeVars.toList, Options := sc.Options, ..st}, match st' with | some st' := do modifyCurrentScope $ λ sc, {sc with univs := OrderedRBMap.ofList st'.univs, vars := OrderedRBMap.ofList st'.vars, includeVars := RBTree.ofList st'.includeVars, Options := st'.Options, }, modify $ λ st, {..st', ..st} | none := pure (), -- error modify $ λ st, {st with messages := st.messages ++ msgs} def namesToPexpr (ns : List Name) : Expr := Expr.mkCapp `_ $ ns.map (λ n, Expr.const n []) def attrsToPexpr (attrs : List (SepBy.Elem.View attrInstance.View (Option SyntaxAtom))) : ElaboratorM Expr := Expr.mkCapp `_ <$> attrs.mmap (λ attr, Expr.mkCapp attr.item.Name.val <$> attr.item.args.mmap toPexpr) def declModifiersToPexpr (mods : declModifiers.View) : ElaboratorM Expr := do let mdata : MData := {}, let mdata := match mods.docComment with | some {doc := some doc, ..} := mdata.setString `docString doc.val | _ := mdata, let mdata := match mods.visibility with | some (visibility.View.private _) := mdata.setBool `private true | some (visibility.View.protected _) := mdata.setBool `protected true | _ := mdata, let mdata := mdata.setBool `noncomputable mods.noncomputable.isSome, let mdata := mdata.setBool `unsafe mods.unsafe.isSome, Expr.mdata mdata <$> attrsToPexpr (match mods.attrs with | some attrs := attrs.attrs | none := []) def identUnivParamsToPexpr (id : identUnivParams.View) : Expr := Expr.const (mangleIdent id.id) $ match id.univParams with | some params := params.params.map (Level.Param ∘ mangleIdent) | none := [] /-- Execute `elab` and reset local Scope (universes, ...) after it has finished. -/ def locally (elab : ElaboratorM Unit) : ElaboratorM Unit := do sc ← currentScope, elab, modifyCurrentScope $ λ _, sc def simpleBindersToPexpr (bindrs : List simpleBinder.View) : ElaboratorM Expr := Expr.mkCapp `_ <$> bindrs.mmap (λ b, do let (bi, id, type) := b.toBinderInfo, let id := mangleIdent id, type ← toPexpr type, pure $ Expr.local id id type bi) def elabDefLike (stx : Syntax) (mods : declModifiers.View) (dl : defLike.View) (kind : Nat) : ElaboratorM Unit := match dl with | {sig := {params := bracketedBinders.View.simple bbs}, ..} := do let mdata := MData.empty.setName `command `defs, mods ← declModifiersToPexpr mods, let kind := Expr.lit $ Literal.natVal kind, match dl.oldUnivParams with | some uparams := modifyCurrentScope $ λ sc, {sc with univs := (uparams.ids.map mangleIdent).foldl (λ m id, OrderedRBMap.insert m id (Level.Param id)) sc.univs} | none := pure (), -- do we actually need this?? let uparams := namesToPexpr $ match dl.oldUnivParams with | some uparams := uparams.ids.map mangleIdent | none := [], let id := mangleIdent dl.Name.id, let type := getOptType dl.sig.type, type ← toPexpr type, let fns := Expr.mkCapp `_ [Expr.local id id type BinderInfo.auxDecl], val ← match dl.val with | declVal.View.simple val := toPexpr val.body | declVal.View.emptyMatch _ := pure $ mkEqns type [] | declVal.View.match eqns := do { eqns ← eqns.mmap (λ (eqn : equation.View), do lhs ← eqn.lhs.mmap toPexpr, rhs ← toPexpr eqn.rhs, pure (id, lhs, rhs) ), pure $ mkEqns type eqns }, params ← simpleBindersToPexpr bbs, oldElabCommand stx $ Expr.mdata mdata $ Expr.mkCapp `_ [mods, kind, uparams, fns, params, val] | _ := error stx "elabDefLike: unexpected input" def inferModToPexpr (mod : Option inferModifier.View) : Expr := Expr.lit $ Literal.natVal $ match mod with | none := 0 | some $ inferModifier.View.relaxed _ := 1 | some $ inferModifier.View.strict _ := 2 def Declaration.elaborate : Elaborator := λ stx, locally $ do let Decl := view «Declaration» stx, match Decl.inner with | Declaration.inner.View.«axiom» c@{sig := {params := bracketedBinders.View.simple [], type := type}, ..} := do let mdata := MData.empty.setName `command `«axiom», -- CommentTo(Kha): It was `constant` here mods ← declModifiersToPexpr Decl.modifiers, let id := identUnivParamsToPexpr c.Name, type ← toPexpr type.type, oldElabCommand stx $ Expr.mdata mdata $ Expr.mkCapp `_ [mods, id, type] | Declaration.inner.View.defLike dl := do -- The numeric literals below should reflect the enum values -- enum class declCmdKind { Theorem, Definition, OpaqueConst, Example, Instance, Var, Abbreviation }; let kind := match dl.kind with | defLike.kind.View.theorem _ := 0 | defLike.kind.View.def _ := 1 | defLike.kind.View.«constant» _ := 2 | defLike.kind.View.abbreviation _ := 6 | defLike.kind.View.«abbrev» _ := 6, elabDefLike stx Decl.modifiers dl kind -- these are almost macros for `def`, Except the Elaborator handles them specially at a few places -- based on the kind | Declaration.inner.View.example ex := elabDefLike stx Decl.modifiers { kind := defLike.kind.View.def, Name := {id := Name.anonymous}, sig := {..ex.sig}, ..ex} 3 | Declaration.inner.View.instance i := elabDefLike stx Decl.modifiers { kind := defLike.kind.View.def, Name := i.Name.getOrElse {id := Name.anonymous}, sig := {..i.sig}, ..i} 4 | Declaration.inner.View.inductive ind@{«class» := none, sig := {params := bracketedBinders.View.simple bbs}, ..} := do let mdata := MData.empty.setName `command `inductives, mods ← declModifiersToPexpr Decl.modifiers, attrs ← attrsToPexpr (match Decl.modifiers.attrs with | some attrs := attrs.attrs | none := []), let mutAttrs := Expr.mkCapp `_ [attrs], match ind.oldUnivParams with | some uparams := modifyCurrentScope $ λ sc, {sc with univs := (uparams.ids.map mangleIdent).foldl (λ m id, OrderedRBMap.insert m id (Level.Param id)) sc.univs} | none := pure (), let uparams := namesToPexpr $ match ind.oldUnivParams with | some uparams := uparams.ids.map mangleIdent | none := [], let id := mangleIdent ind.Name.id, let type := getOptType ind.sig.type, type ← toPexpr type, let indL := Expr.local id id type BinderInfo.default, let inds := Expr.mkCapp `_ [indL], params ← simpleBindersToPexpr bbs, introRules ← ind.introRules.mmap (λ (r : introRule.View), do ({params := bracketedBinders.View.simple [], type := some ty}) ← pure r.sig | error stx "Declaration.elaborate: unexpected input", type ← toPexpr ty.type, let Name := mangleIdent r.Name, pure $ Expr.local Name Name type BinderInfo.default), let introRules := Expr.mkCapp `_ introRules, let introRules := Expr.mkCapp `_ [introRules], let inferKinds := ind.introRules.map $ λ (r : introRule.View), inferModToPexpr r.inferMod, let inferKinds := Expr.mkCapp `_ inferKinds, let inferKinds := Expr.mkCapp `_ [inferKinds], oldElabCommand stx $ Expr.mdata mdata $ Expr.mkCapp `_ [mods, mutAttrs, uparams, inds, params, introRules, inferKinds] | Declaration.inner.View.structure s@{keyword := structureKw.View.structure _, sig := {params := bracketedBinders.View.simple bbs}, ..} := do let mdata := MData.empty.setName `command `structure, mods ← declModifiersToPexpr Decl.modifiers, match s.oldUnivParams with | some uparams := modifyCurrentScope $ λ sc, {sc with univs := (uparams.ids.map mangleIdent).foldl (λ m id, OrderedRBMap.insert m id (Level.Param id)) sc.univs} | none := pure (), let uparams := namesToPexpr $ match s.oldUnivParams with | some uparams := uparams.ids.map mangleIdent | none := [], let Name := mangleIdent s.Name.id, let Name := Expr.local Name Name dummy BinderInfo.default, let type := getOptType s.sig.type, type ← toPexpr type, params ← simpleBindersToPexpr bbs, let parents := match s.extends with | some ex := ex.parents | none := [], parents ← parents.mmap (toPexpr ∘ SepBy.Elem.View.item), let parents := Expr.mkCapp `_ parents, let mk := match s.ctor with | some ctor := mangleIdent ctor.Name | none := `mk, let mk := Expr.local mk mk dummy BinderInfo.default, let infer := inferModToPexpr (s.ctor >>= structureCtor.View.inferMod), fieldBlocks ← s.fieldBlocks.mmap (λ bl, do (bi, content) ← match bl with | structureFieldBlock.View.explicit {content := structExplicitBinderContent.View.notation _} := error stx "Declaration.elaborate: unexpected input" | structureFieldBlock.View.explicit {content := structExplicitBinderContent.View.other c} := pure (BinderInfo.default, c) | structureFieldBlock.View.implicit {content := c} := pure (BinderInfo.implicit, c) | structureFieldBlock.View.strictImplicit {content := c} := pure (BinderInfo.strictImplicit, c) | structureFieldBlock.View.instImplicit {content := c} := pure (BinderInfo.instImplicit, c), let bi := Expr.local `_ `_ dummy bi, let ids := namesToPexpr $ content.ids.map mangleIdent, let kind := inferModToPexpr content.inferMod, let type := getOptType content.sig.type, type ← toPexpr type, pure $ Expr.mkCapp `_ [bi, ids, kind, type]), let fieldBlocks := Expr.mkCapp `_ fieldBlocks, oldElabCommand stx $ Expr.mdata mdata $ Expr.mkCapp `_ [mods, uparams, Name, params, parents, type, mk, infer, fieldBlocks] | _ := error stx "Declaration.elaborate: unexpected input" def variables.elaborate : Elaborator := λ stx, do let mdata := MData.empty.setName `command `variables, let v := view «variables» stx, vars ← match v.binders with | bracketedBinders.View.simple bbs := bbs.mfilter $ λ b, do let (bi, id, type) := b.toBinderInfo, if type.isOfKind bindingAnnotationUpdate then do sc ← currentScope, let id := mangleIdent id, match sc.vars.find id with | some (_, v) := modifyCurrentScope $ λ sc, {sc with vars := sc.vars.insert id {v with BinderInfo := bi}} | none := error (Syntax.ident id) "", pure false else pure true | _ := error stx "variables.elaborate: unexpected input", vars ← simpleBindersToPexpr vars, oldElabCommand stx $ Expr.mdata mdata vars def include.elaborate : Elaborator := λ stx, do let v := view «include» stx, -- TODO(Sebastian): error checking modifyCurrentScope $ λ sc, {sc with includeVars := v.ids.foldl (λ vars v, vars.insert $ mangleIdent v) sc.includeVars} -- TODO: RBMap.remove /- def omit.elaborate : Elaborator := λ stx, do let v := View «omit» stx, modify $ λ st, {st with localState := {sc with includeVars := v.ids.foldl (λ vars v, vars.remove $ mangleIdent v) sc.includeVars}} -/ def Module.header.elaborate : Elaborator := λ stx, do let header := view Module.header stx, match header with | {«prelude» := some _, imports := []} := pure () | _ := error stx "not implemented: imports" def precToNat : Option precedence.View → Nat | (some prec) := prec.Term.toNat | none := 0 -- TODO(Sebastian): Command parsers like `structure` will need access to these def CommandParserConfig.registerNotationTokens (spec : NotationSpec.View) (cfg : CommandParserConfig) : Except String CommandParserConfig := do spec.rules.mfoldl (λ (cfg : CommandParserConfig) r, match r.symbol with | notationSymbol.View.quoted {symbol := some a, prec := prec, ..} := pure {cfg with tokens := cfg.tokens.insert a.val.trim {«prefix» := a.val.trim, lbp := precToNat prec}} | _ := throw "registerNotationTokens: unreachable") cfg def CommandParserConfig.registerNotationParser (k : SyntaxNodeKind) (nota : notation.View) (cfg : CommandParserConfig) : Except String CommandParserConfig := do -- build and register Parser ps ← nota.spec.rules.mmap (λ r : rule.View, do psym ← match r.symbol with | notationSymbol.View.quoted {symbol := some a ..} := pure (symbol a.val : termParser) | _ := throw "registerNotationParser: unreachable", ptrans ← match r.transition with | some (transition.View.binder b) := pure $ some $ Term.binderIdent.Parser | some (transition.View.binders b) := pure $ some $ Term.binders.Parser | some (transition.View.Arg {action := none, ..}) := pure $ some Term.Parser | some (transition.View.Arg {action := some {kind := actionKind.View.prec prec}, ..}) := pure $ some $ Term.Parser prec.toNat | some (transition.View.Arg {action := some {kind := actionKind.View.scoped sc}, ..}) := pure $ some $ Term.Parser $ precToNat sc.prec | none := pure $ none | _ := throw "registerNotationParser: unimplemented", pure $ psym::ptrans.toMonad ), firstRule::_ ← pure nota.spec.rules | throw "registerNotationParser: unreachable", firstTk ← match firstRule.symbol with | notationSymbol.View.quoted {symbol := some a ..} := pure a.val.trim | _ := throw "registerNotationParser: unreachable", let ps := ps.bind id, cfg ← match nota.local, nota.spec.prefixArg with | none, none := pure {cfg with leadingTermParsers := cfg.leadingTermParsers.insert firstTk $ Parser.Combinators.node k ps} | some _, none := pure {cfg with localLeadingTermParsers := cfg.localLeadingTermParsers.insert firstTk $ Parser.Combinators.node k ps} | none, some _ := pure {cfg with trailingTermParsers := cfg.trailingTermParsers.insert firstTk $ Parser.Combinators.node k (getLeading::ps.map coe)} | some _, some _ := pure {cfg with localTrailingTermParsers := cfg.localTrailingTermParsers.insert firstTk $ Parser.Combinators.node k (getLeading::ps.map coe)}, pure cfg /-- Recreate `ElaboratorState.parserCfg` from the Elaborator State and the initial config, effectively treating it as a cache. -/ def updateParserConfig : ElaboratorM Unit := do st ← get, sc ← currentScope, cfg ← read, let ccfg := cfg.initialParserCfg.toCommandParserConfig, ccfg ← st.reservedNotations.mfoldl (λ ccfg rnota, match CommandParserConfig.registerNotationTokens rnota.spec ccfg with | Except.ok ccfg := pure ccfg | Except.error e := error (review reserveNotation rnota) e) ccfg, ccfg ← (st.notations ++ sc.notations).mfoldl (λ ccfg nota, match CommandParserConfig.registerNotationTokens nota.nota.spec ccfg >>= CommandParserConfig.registerNotationParser nota.kind nota.nota with | Except.ok ccfg := pure ccfg | Except.error e := error (review «notation» nota.nota) e) ccfg, set {st with parserCfg := {cfg.initialParserCfg with toCommandParserConfig := ccfg}} def postprocessNotationSpec (spec : NotationSpec.View) : NotationSpec.View := -- default leading tokens to `max` -- NOTE: should happen after copying precedences from reserved notation match spec with | {prefixArg := none, rules := r@{symbol := notationSymbol.View.quoted sym@{prec := none, ..}, ..}::rs} := {spec with rules := {r with symbol := notationSymbol.View.quoted {sym with prec := some {Term := precedenceTerm.View.lit $ precedenceLit.View.num $ number.View.ofNat maxPrec} }}::rs} | _ := spec def reserveNotation.elaborate : Elaborator := λ stx, do let v := view reserveNotation stx, let v := {v with spec := postprocessNotationSpec v.spec}, -- TODO: sanity checks? modify $ λ st, {st with reservedNotations := v::st.reservedNotations}, updateParserConfig def matchPrecedence : Option precedence.View → Option precedence.View → Bool | none (some rp) := true | (some sp) (some rp) := sp.Term.toNat = rp.Term.toNat | _ _ := false /-- Check if a notation is compatible with a reserved notation, and if so, copy missing precedences in the notation from the reserved notation. -/ def matchSpec (spec reserved : NotationSpec.View) : Option NotationSpec.View := do guard $ spec.prefixArg.isSome = reserved.prefixArg.isSome, rules ← (spec.rules.zip reserved.rules).mmap $ λ ⟨sr, rr⟩, do { notationSymbol.View.quoted sq@{symbol := some sa, ..} ← pure sr.symbol | failure, notationSymbol.View.quoted rq@{symbol := some ra, ..} ← pure rr.symbol | failure, guard $ sa.val.trim = ra.val.trim, guard $ matchPrecedence sq.prec rq.prec, st ← match sr.transition, rr.transition with | some (transition.View.binder sb), some (transition.View.binder rb) := guard (matchPrecedence sb.prec rb.prec) *> pure rr.transition | some (transition.View.binders sb), some (transition.View.binders rb) := guard (matchPrecedence sb.prec rb.prec) *> pure rr.transition | some (transition.View.Arg sarg), some (transition.View.Arg rarg) := do sact ← match action.View.kind <$> sarg.action, action.View.kind <$> rarg.action with | some (actionKind.View.prec sp), some (actionKind.View.prec rp) := guard (sp.toNat = rp.toNat) *> pure sarg.action | none, some (actionKind.View.prec rp) := pure rarg.action | _, _ := failure, pure $ some $ transition.View.Arg {sarg with action := sact} | none, none := pure none | _, _ := failure, pure $ {rule.View . symbol := notationSymbol.View.quoted rq, transition := st} }, pure $ {spec with rules := rules} def notation.elaborateAux : notation.View → ElaboratorM notation.View := λ nota, do st ← get, -- check reserved notations matched ← pure $ st.reservedNotations.filterMap $ λ rnota, matchSpec nota.spec rnota.spec, nota ← match matched with | [matched] := pure {nota with spec := matched} | [] := pure nota | _ := error (review «notation» nota) "invalid notation, matches multiple reserved notations", -- TODO: sanity checks pure {nota with spec := postprocessNotationSpec nota.spec} -- TODO(Sebastian): better kind names, Module prefix? def mkNotationKind : ElaboratorM SyntaxNodeKind := do st ← get, set {st with notationCounter := st.notationCounter + 1}, pure {name := (`_notation).mkNumeral st.notationCounter} /-- Register a notation in the Expander. Unlike with notation parsers, there is no harm in keeping local notation macros registered after closing a section. -/ def registerNotationMacro (nota : notation.View) : ElaboratorM NotationMacro := do k ← mkNotationKind, let m : NotationMacro := ⟨k, nota⟩, let transf := mkNotationTransformer m, modify $ λ st, {st with expanderCfg := {st.expanderCfg with transformers := st.expanderCfg.transformers.insert k.name transf}}, pure m def notation.elaborate : Elaborator := λ stx, do let nota := view «notation» stx, -- HACK: ignore List Literal notation using :fold let usesFold := nota.spec.rules.any $ λ r, match r.transition with | some (transition.View.Arg {action := some {kind := actionKind.View.fold _, ..}, ..}) := true | _ := false, if usesFold then do { cfg ← read, modify $ λ st, {st with messages := st.messages.add {filename := cfg.filename, pos := ⟨1,0⟩, severity := MessageSeverity.warning, text := "ignoring notation using 'fold' action"}} } else do { nota ← notation.elaborateAux nota, m ← registerNotationMacro nota, match nota.local with | some _ := modifyCurrentScope $ λ sc, {sc with notations := m::sc.notations} | none := modify $ λ st, {st with notations := m::st.notations}, updateParserConfig } def universe.elaborate : Elaborator := λ stx, do let univ := view «universe» stx, let id := mangleIdent univ.id, sc ← currentScope, match sc.univs.find id with | none := modifyCurrentScope $ λ sc, {sc with univs := sc.univs.insert id (Level.Param id)} | some _ := error stx $ "a universe named '" ++ toString id ++ "' has already been declared in this Scope" def attribute.elaborate : Elaborator := λ stx, do let attr := view «attribute» stx, let mdata := MData.empty.setName `command `attribute, let mdata := mdata.setBool `local $ attr.local.isSome, attrs ← attrsToPexpr attr.attrs, ids ← attr.ids.mmap (λ id, match id.preresolved with | [] := error (Syntax.ident id) $ "unknown identifier '" ++ toString id.val ++ "'" | [c] := pure $ Expr.const c [] | _ := error (Syntax.ident id) "invalid 'attribute' command, identifier is ambiguous"), let ids := Expr.mkCapp `_ ids, oldElabCommand stx $ Expr.mdata mdata $ Expr.app attrs ids def check.elaborate : Elaborator := λ stx, do let v := view check stx, let mdata := MData.empty.setName `command `#check, e ← toPexpr v.Term, oldElabCommand stx $ Expr.mdata mdata e def open.elaborate : Elaborator := λ stx, do let v := view «open» stx, -- TODO: do eager sanity checks (namespace does not exist, etc.) modifyCurrentScope $ λ sc, {sc with openDecls := sc.openDecls ++ v.spec} def export.elaborate : Elaborator := λ stx, do let v := view «export» stx, ns ← getNamespace, -- TODO: do eager sanity checks (namespace does not exist, etc.) modify $ λ st, {st with exportDecls := st.exportDecls ++ v.spec.map (λ spec, ⟨ns, spec⟩)} def initQuot.elaborate : Elaborator := λ stx, oldElabCommand stx $ Expr.mdata (MData.empty.setName `command `initQuot) dummy def setOption.elaborate : Elaborator := λ stx, do let v := view «setOption» stx, let opt := v.opt.val, sc ← currentScope, let opts := sc.Options, -- TODO(Sebastian): check registered Options let opts := match v.val with | optionValue.View.Bool b := opts.setBool opt (match b with boolOptionValue.View.True _ := true | _ := false) | optionValue.View.String lit := match lit.value with | some s := opts.setString opt s | none := opts -- Parser already failed | optionValue.View.num lit := opts.setNat opt lit.toNat, modifyCurrentScope $ λ sc, {sc with Options := opts} /-- List of commands: recursively elaborate each command. -/ def noKind.elaborate : Elaborator := λ stx, do some n ← pure stx.asNode | error stx "noKind.elaborate: unreachable", n.args.mfor command.elaborate def end.elaborate : Elaborator := λ cmd, do let v := view «end» cmd, st ← get, -- NOTE: bottom-most (Module) Scope cannot be closed sc::sc'::scps ← pure st.scopes | error cmd "invalid 'end', there is no open Scope to end", let endName := mangleIdent $ v.Name.getOrElse Name.anonymous, when (endName ≠ sc.header) $ error cmd $ "invalid end of " ++ sc.cmd ++ ", expected Name '" ++ toString sc.header ++ "'", set {st with scopes := sc'::scps}, -- local notations may have vanished updateParserConfig def section.elaborate : Elaborator := λ cmd, do let sec := view «section» cmd, let header := mangleIdent $ sec.Name.getOrElse Name.anonymous, sc ← currentScope, modify $ λ st, {st with scopes := {sc with cmd := "section", header := header}::st.scopes} def namespace.elaborate : Elaborator := λ cmd, do let v := view «namespace» cmd, let header := mangleIdent v.Name, sc ← currentScope, ns ← getNamespace, let sc' := {sc with cmd := "namespace", header := header, nsStack := (ns ++ header)::sc.nsStack}, modify $ λ st, {st with scopes := sc'::st.scopes} def eoi.elaborate : Elaborator := λ cmd, do st ← get, when (st.scopes.length > 1) $ error cmd "invalid end of input, expected 'end'" -- TODO(Sebastian): replace with attribute def elaborators : RBMap Name Elaborator Name.quickLt := RBMap.fromList [ (Module.header.name, Module.header.elaborate), (notation.name, notation.elaborate), (reserveNotation.name, reserveNotation.elaborate), (universe.name, universe.elaborate), (noKind.name, noKind.elaborate), (end.name, end.elaborate), (section.name, section.elaborate), (namespace.name, namespace.elaborate), (variables.name, variables.elaborate), (include.name, include.elaborate), --(omit.name, omit.elaborate), (Declaration.name, Declaration.elaborate), (attribute.name, attribute.elaborate), (open.name, open.elaborate), (export.name, export.elaborate), (check.name, check.elaborate), (initQuot.name, initQuot.elaborate), (setOption.name, setOption.elaborate), (Module.eoi.name, eoi.elaborate) ] _ -- TODO: optimize def isOpenNamespace (sc : Scope) : Name → Bool | Name.anonymous := true | ns := -- check surrounding namespaces ns ∈ sc.nsStack ∨ -- check opened namespaces sc.openDecls.any (λ od, od.id.val = ns) ∨ -- TODO: check active exports false -- TODO: `hiding`, `as`, `renaming` def matchOpenSpec (n : Name) (spec : openSpec.View) : Option Name := let matchesOnly := match spec.only with | none := true | some only := n = only.id.val ∨ only.ids.any (λ id, n = id.val) in if matchesOnly then some (spec.id.val ++ n) else none def resolveContext : Name → ElaboratorM (List Name) | n := do st ← get, sc ← currentScope, pure $ -- TODO(Sebastian): check the interaction betwen preresolution and section variables match sc.vars.find n with | some (_, v) := [v.uniqName] | _ := -- global resolution -- check surrounding namespaces first -- TODO: check for `protected` match sc.nsStack.filter (λ ns, st.env.contains (ns ++ n)) with | ns::_ := [ns ++ n] -- prefer innermost namespace | _ := -- check environment directly (let unrooted := n.replacePrefix `_root_ Name.anonymous in match st.env.contains unrooted with | true := [unrooted] | _ := []) ++ -- check opened namespaces (let ns' := sc.openDecls.filterMap (matchOpenSpec n) in ns'.filter (λ n', st.env.contains n')) ++ -- check active exports -- TODO: optimize -- TODO: Lean 3 activates an export in `foo` even on `open foo (specificThing)`, but does that make sense? (let eds' := st.exportDecls.filter (λ ed, isOpenNamespace sc ed.inNs) in let ns' := eds'.filterMap (λ ed, matchOpenSpec n ed.spec) in ns'.filter (λ n', st.env.contains n')) -- TODO: projection notation partial def preresolve : Syntax → ElaboratorM Syntax | (Syntax.ident id) := do let n := mangleIdent id, ns ← resolveContext n, pure $ Syntax.ident {id with preresolved := ns ++ id.preresolved} | (Syntax.rawNode n) := do args ← n.args.mmap preresolve, pure $ Syntax.rawNode {n with args := args} | stx := pure stx def mkState (cfg : ElaboratorConfig) (env : environment) (opts : Options) : ElaboratorState := { parserCfg := cfg.initialParserCfg, expanderCfg := {transformers := Expander.builtinTransformers, ..cfg}, env := env, ngen := ⟨`_ngen.fixme, 0⟩, scopes := [{cmd := "MODULE", header := `MODULE, Options := opts}]} def processCommand (cfg : ElaboratorConfig) (st : ElaboratorState) (cmd : Syntax) : ElaboratorState := let st := {st with messages := MessageLog.empty} in let r := @ExceptT.run _ Id _ $ flip StateT.run st $ flip ReaderT.run cfg $ RecT.run (command.elaborate cmd) (λ _, error cmd "Elaborator.run: recursion depth exceeded") (λ cmd, do some n ← pure cmd.asNode | error cmd $ "not a command: " ++ toString cmd, some elab ← pure $ elaborators.find n.kind.name | error cmd $ "unknown command: " ++ toString n.kind.name, cmd' ← preresolve cmd, elab cmd') in match r with | Except.ok ((), st) := st | Except.error e := {st with messages := st.messages.add e} end Elaborator end Lean
f7c3ad0f416e87b8f3319d44c6d949372a3a0d68
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1745.lean
853896cd7517dd6dc4868630ce021f24674a0e2b
[ "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
29
lean
def foo: list nat := [ 1,2, ]
9600da4828d95892a5e2b8e21ba05e4470e3935c
367134ba5a65885e863bdc4507601606690974c1
/src/data/pnat/prime.lean
df6f0675dac73da2ff221fab54d2246cd1409fb8
[ "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
7,471
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Neil Strickland -/ import data.nat.prime import data.pnat.basic /-! # Primality and GCD on pnat This file extends the theory of `ℕ+` with `gcd`, `lcm` and `prime` functions, analogous to those on `nat`. -/ namespace nat.primes instance coe_pnat : has_coe nat.primes ℕ+ := ⟨λ p, ⟨(p : ℕ), p.property.pos⟩⟩ theorem coe_pnat_nat (p : nat.primes) : ((p : ℕ+) : ℕ) = p := rfl theorem coe_pnat_inj (p q : nat.primes) : (p : ℕ+) = (q : ℕ+) → p = q := λ h, begin replace h : ((p : ℕ+) : ℕ) = ((q : ℕ+) : ℕ) := congr_arg subtype.val h, rw [coe_pnat_nat, coe_pnat_nat] at h, exact subtype.eq h, end end nat.primes namespace pnat open nat /-- The greatest common divisor (gcd) of two positive natural numbers, viewed as positive natural number. -/ def gcd (n m : ℕ+) : ℕ+ := ⟨nat.gcd (n : ℕ) (m : ℕ), nat.gcd_pos_of_pos_left (m : ℕ) n.pos⟩ /-- The least common multiple (lcm) of two positive natural numbers, viewed as positive natural number. -/ def lcm (n m : ℕ+) : ℕ+ := ⟨nat.lcm (n : ℕ) (m : ℕ), by { let h := mul_pos n.pos m.pos, rw [← gcd_mul_lcm (n : ℕ) (m : ℕ), mul_comm] at h, exact pos_of_dvd_of_pos (dvd.intro (nat.gcd (n : ℕ) (m : ℕ)) rfl) h }⟩ @[simp] theorem gcd_coe (n m : ℕ+) : ((gcd n m) : ℕ) = nat.gcd n m := rfl @[simp] theorem lcm_coe (n m : ℕ+) : ((lcm n m) : ℕ) = nat.lcm n m := rfl theorem gcd_dvd_left (n m : ℕ+) : (gcd n m) ∣ n := dvd_iff.2 (nat.gcd_dvd_left (n : ℕ) (m : ℕ)) theorem gcd_dvd_right (n m : ℕ+) : (gcd n m) ∣ m := dvd_iff.2 (nat.gcd_dvd_right (n : ℕ) (m : ℕ)) theorem dvd_gcd {m n k : ℕ+} (hm : k ∣ m) (hn : k ∣ n) : k ∣ gcd m n := dvd_iff.2 (@nat.dvd_gcd (m : ℕ) (n : ℕ) (k : ℕ) (dvd_iff.1 hm) (dvd_iff.1 hn)) theorem dvd_lcm_left (n m : ℕ+) : n ∣ lcm n m := dvd_iff.2 (nat.dvd_lcm_left (n : ℕ) (m : ℕ)) theorem dvd_lcm_right (n m : ℕ+) : m ∣ lcm n m := dvd_iff.2 (nat.dvd_lcm_right (n : ℕ) (m : ℕ)) theorem lcm_dvd {m n k : ℕ+} (hm : m ∣ k) (hn : n ∣ k) : lcm m n ∣ k := dvd_iff.2 (@nat.lcm_dvd (m : ℕ) (n : ℕ) (k : ℕ) (dvd_iff.1 hm) (dvd_iff.1 hn)) theorem gcd_mul_lcm (n m : ℕ+) : (gcd n m) * (lcm n m) = n * m := subtype.eq (nat.gcd_mul_lcm (n : ℕ) (m : ℕ)) lemma eq_one_of_lt_two {n : ℕ+} : n < 2 → n = 1 := begin intro h, apply le_antisymm, swap, apply pnat.one_le, change n < 1 + 1 at h, rw pnat.lt_add_one_iff at h, apply h end section prime /-! ### Prime numbers -/ /-- Primality predicate for `ℕ+`, defined in terms of `nat.prime`. -/ def prime (p : ℕ+) : Prop := (p : ℕ).prime lemma prime.one_lt {p : ℕ+} : p.prime → 1 < p := nat.prime.one_lt lemma prime_two : (2 : ℕ+).prime := nat.prime_two lemma dvd_prime {p m : ℕ+} (pp : p.prime) : (m ∣ p ↔ m = 1 ∨ m = p) := by { rw pnat.dvd_iff, rw nat.dvd_prime pp, simp } lemma prime.ne_one {p : ℕ+} : p.prime → p ≠ 1 := by { intro pp, intro contra, apply nat.prime.ne_one pp, rw pnat.coe_eq_one_iff, apply contra } @[simp] lemma not_prime_one : ¬ (1: ℕ+).prime := nat.not_prime_one lemma prime.not_dvd_one {p : ℕ+} : p.prime → ¬ p ∣ 1 := λ pp : p.prime, by {rw dvd_iff, apply nat.prime.not_dvd_one pp} lemma exists_prime_and_dvd {n : ℕ+} : 2 ≤ n → (∃ (p : ℕ+), p.prime ∧ p ∣ n) := begin intro h, cases nat.exists_prime_and_dvd h with p hp, existsi (⟨p, nat.prime.pos hp.left⟩ : ℕ+), rw dvd_iff, apply hp end end prime section coprime /-! ### Coprime numbers and gcd -/ /-- Two pnats are coprime if their gcd is 1. -/ def coprime (m n : ℕ+) : Prop := m.gcd n = 1 @[simp] lemma coprime_coe {m n : ℕ+} : nat.coprime ↑m ↑n ↔ m.coprime n := by { unfold coprime, unfold nat.coprime, rw ← coe_inj, simp } lemma coprime.mul {k m n : ℕ+} : m.coprime k → n.coprime k → (m * n).coprime k := by { repeat {rw ← coprime_coe}, rw mul_coe, apply nat.coprime.mul } lemma coprime.mul_right {k m n : ℕ+} : k.coprime m → k.coprime n → k.coprime (m * n) := by { repeat {rw ← coprime_coe}, rw mul_coe, apply nat.coprime.mul_right } lemma gcd_comm {m n : ℕ+} : m.gcd n = n.gcd m := by { apply eq, simp only [gcd_coe], apply nat.gcd_comm } lemma gcd_eq_left_iff_dvd {m n : ℕ+} : m ∣ n ↔ m.gcd n = m := by { rw dvd_iff, rw nat.gcd_eq_left_iff_dvd, rw ← coe_inj, simp } lemma gcd_eq_right_iff_dvd {m n : ℕ+} : m ∣ n ↔ n.gcd m = m := by { rw gcd_comm, apply gcd_eq_left_iff_dvd, } lemma coprime.gcd_mul_left_cancel (m : ℕ+) {n k : ℕ+} : k.coprime n → (k * m).gcd n = m.gcd n := begin intro h, apply eq, simp only [gcd_coe, mul_coe], apply nat.coprime.gcd_mul_left_cancel, simpa end lemma coprime.gcd_mul_right_cancel (m : ℕ+) {n k : ℕ+} : k.coprime n → (m * k).gcd n = m.gcd n := begin rw mul_comm, apply coprime.gcd_mul_left_cancel, end lemma coprime.gcd_mul_left_cancel_right (m : ℕ+) {n k : ℕ+} : k.coprime m → m.gcd (k * n) = m.gcd n := begin intro h, iterate 2 {rw gcd_comm, symmetry}, apply coprime.gcd_mul_left_cancel _ h, end lemma coprime.gcd_mul_right_cancel_right (m : ℕ+) {n k : ℕ+} : k.coprime m → m.gcd (n * k) = m.gcd n := begin rw mul_comm, apply coprime.gcd_mul_left_cancel_right, end @[simp] lemma one_gcd {n : ℕ+} : gcd 1 n = 1 := by { rw ← gcd_eq_left_iff_dvd, apply one_dvd } @[simp] lemma gcd_one {n : ℕ+} : gcd n 1 = 1 := by { rw gcd_comm, apply one_gcd } @[symm] lemma coprime.symm {m n : ℕ+} : m.coprime n → n.coprime m := by { unfold coprime, rw gcd_comm, simp } @[simp] lemma one_coprime {n : ℕ+} : (1 : ℕ+).coprime n := one_gcd @[simp] lemma coprime_one {n : ℕ+} : n.coprime 1 := coprime.symm one_coprime lemma coprime.coprime_dvd_left {m k n : ℕ+} : m ∣ k → k.coprime n → m.coprime n := by { rw dvd_iff, repeat {rw ← coprime_coe}, apply nat.coprime.coprime_dvd_left } lemma coprime.factor_eq_gcd_left {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n) : a = (a * b).gcd m := begin rw gcd_eq_left_iff_dvd at am, conv_lhs {rw ← am}, symmetry, apply coprime.gcd_mul_right_cancel a, apply coprime.coprime_dvd_left bn cop.symm, end lemma coprime.factor_eq_gcd_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n) : a = (b * a).gcd m := begin rw mul_comm, apply coprime.factor_eq_gcd_left cop am bn, end lemma coprime.factor_eq_gcd_left_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n) : a = m.gcd (a * b) := begin rw gcd_comm, apply coprime.factor_eq_gcd_left cop am bn, end lemma coprime.factor_eq_gcd_right_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n) : a = m.gcd (b * a) := begin rw gcd_comm, apply coprime.factor_eq_gcd_right cop am bn, end lemma coprime.gcd_mul (k : ℕ+) {m n : ℕ+} (h: m.coprime n) : k.gcd (m * n) = k.gcd m * k.gcd n := begin rw ← coprime_coe at h, apply eq, simp only [gcd_coe, mul_coe], apply nat.coprime.gcd_mul k h end lemma gcd_eq_left {m n : ℕ+} : m ∣ n → m.gcd n = m := by { rw dvd_iff, intro h, apply eq, simp only [gcd_coe], apply nat.gcd_eq_left h } lemma coprime.pow {m n : ℕ+} (k l : ℕ) (h : m.coprime n) : (m ^ k).coprime (n ^ l) := begin rw ← coprime_coe at *, simp only [pow_coe], apply nat.coprime.pow, apply h end end coprime end pnat
2cbfb251a29625d0be0cd7578e1eeb4d64adfbc1
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/quadratic_form/prod.lean
ff99ce8080efc64ef13d182b1c27ef1ed5d95fb4
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,979
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.quadratic_form.basic /-! # Quadratic form on product and pi types ## Main definitions * `quadratic_form.prod Q₁ Q₂`: the quadratic form constructed elementwise on a product * `quadratic_form.pi Q`: the quadratic form constructed elementwise on a pi type ## Main results * `quadratic_form.equivalent.prod`, `quadratic_form.equivalent.pi`: quadratic forms are equivalent if their components are equivalent * `quadratic_form.nonneg_prod_iff`, `quadratic_form.nonneg_pi_iff`: quadratic forms are positive- semidefinite if and only if their components are positive-semidefinite. * `quadratic_form.pos_def_prod_iff`, `quadratic_form.pos_def_pi_iff`: quadratic forms are positive- definite if and only if their components are positive-definite. ## Implementation notes Many of the lemmas in this file could be generalized into results about sums of positive and non-negative elements, and would generalize to any map `Q` where `Q 0 = 0`, not just quadratic forms specifically. -/ universes u v w variables {ι : Type*} {R : Type*} {M₁ M₂ N₁ N₂ : Type*} {Mᵢ Nᵢ : ι → Type*} variables [ring R] variables [add_comm_group M₁] [add_comm_group M₂] [add_comm_group N₁] [add_comm_group N₂] variables [module R M₁] [module R M₂] [module R N₁] [module R N₂] variables [Π i, add_comm_group (Mᵢ i)] [Π i, add_comm_group (Nᵢ i)] variables [Π i, module R (Mᵢ i)] [Π i, module R (Nᵢ i)] namespace quadratic_form /-- Construct a quadratic form on a product of two modules from the quadratic form on each module. -/ @[simps] def prod (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) : quadratic_form R (M₁ × M₂) := Q₁.comp (linear_map.fst _ _ _) + Q₂.comp (linear_map.snd _ _ _) /-- An isometry between quadratic forms generated by `quadratic_form.prod` can be constructed from a pair of isometries between the left and right parts. -/ @[simps to_linear_equiv] def isometry.prod {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₁' : quadratic_form R N₁} {Q₂' : quadratic_form R N₂} (e₁ : Q₁.isometry Q₁') (e₂ : Q₂.isometry Q₂') : (Q₁.prod Q₂).isometry (Q₁'.prod Q₂'):= { map_app' := λ x, congr_arg2 (+) (e₁.map_app x.1) (e₂.map_app x.2), to_linear_equiv := linear_equiv.prod e₁.to_linear_equiv e₂.to_linear_equiv} lemma equivalent.prod {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₁' : quadratic_form R N₁} {Q₂' : quadratic_form R N₂} (e₁ : Q₁.equivalent Q₁') (e₂ : Q₂.equivalent Q₂') : (Q₁.prod Q₂).equivalent (Q₁'.prod Q₂'):= nonempty.map2 isometry.prod e₁ e₂ /-- If a product is anisotropic then its components must be. The converse is not true. -/ lemma anisotropic_of_prod {R} [ordered_ring R] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (h : (Q₁.prod Q₂).anisotropic) : Q₁.anisotropic ∧ Q₂.anisotropic := begin simp_rw [anisotropic, prod_to_fun, prod.forall, prod.mk_eq_zero] at h, split, { intros x hx, refine (h x 0 _).1, rw [hx, zero_add, map_zero] }, { intros x hx, refine (h 0 x _).2, rw [hx, add_zero, map_zero] }, end lemma nonneg_prod_iff {R} [ordered_ring R] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} : (∀ x, 0 ≤ (Q₁.prod Q₂) x) ↔ (∀ x, 0 ≤ Q₁ x) ∧ (∀ x, 0 ≤ Q₂ x) := begin simp_rw [prod.forall, prod_to_fun], split, { intro h, split, { intro x, simpa only [add_zero, map_zero] using h x 0 }, { intro x, simpa only [zero_add, map_zero] using h 0 x } }, { rintros ⟨h₁, h₂⟩ x₁ x₂, exact add_nonneg (h₁ x₁) (h₂ x₂), }, end lemma pos_def_prod_iff {R} [ordered_ring R] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} : (Q₁.prod Q₂).pos_def ↔ Q₁.pos_def ∧ Q₂.pos_def := begin simp_rw [pos_def_iff_nonneg, nonneg_prod_iff], split, { rintros ⟨⟨hle₁, hle₂⟩, ha⟩, obtain ⟨ha₁, ha₂⟩ := anisotropic_of_prod ha, refine ⟨⟨hle₁, ha₁⟩, ⟨hle₂, ha₂⟩⟩, }, { rintro ⟨⟨hle₁, ha₁⟩, ⟨hle₂, ha₂⟩⟩, refine ⟨⟨hle₁, hle₂⟩, _⟩, rintro ⟨x₁, x₂⟩ (hx : Q₁ x₁ + Q₂ x₂ = 0), rw [add_eq_zero_iff' (hle₁ x₁) (hle₂ x₂), ha₁.eq_zero_iff, ha₂.eq_zero_iff] at hx, rwa [prod.mk_eq_zero], } end lemma pos_def.prod {R} [ordered_ring R] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (h₁ : Q₁.pos_def) (h₂ : Q₂.pos_def) : (Q₁.prod Q₂).pos_def := pos_def_prod_iff.mpr ⟨h₁, h₂⟩ open_locale big_operators /-- Construct a quadratic form on a family of modules from the quadratic form on each module. -/ def pi [fintype ι] (Q : Π i, quadratic_form R (Mᵢ i)) : quadratic_form R (Π i, Mᵢ i) := ∑ i, (Q i).comp (linear_map.proj i : _ →ₗ[R] Mᵢ i) @[simp] lemma pi_apply [fintype ι] (Q : Π i, quadratic_form R (Mᵢ i)) (x : Π i, Mᵢ i) : pi Q x = ∑ i, Q i (x i) := sum_apply _ _ _ /-- An isometry between quadratic forms generated by `quadratic_form.prod` can be constructed from a pair of isometries between the left and right parts. -/ @[simps to_linear_equiv] def isometry.pi [fintype ι] {Q : Π i, quadratic_form R (Mᵢ i)} {Q' : Π i, quadratic_form R (Nᵢ i)} (e : Π i, (Q i).isometry (Q' i)) : (pi Q).isometry (pi Q') := { map_app' := λ x, by simp only [pi_apply, linear_equiv.Pi_congr_right_apply, linear_equiv.to_fun_eq_coe, isometry.coe_to_linear_equiv, isometry.map_app], to_linear_equiv := linear_equiv.Pi_congr_right (λ i, (e i : Mᵢ i ≃ₗ[R] Nᵢ i))} lemma equivalent.pi [fintype ι] {Q : Π i, quadratic_form R (Mᵢ i)} {Q' : Π i, quadratic_form R (Nᵢ i)} (e : ∀ i, (Q i).equivalent (Q' i)) : (pi Q).equivalent (pi Q') := ⟨isometry.pi (λ i, classical.choice (e i))⟩ /-- If a family is anisotropic then its components must be. The converse is not true. -/ lemma anisotropic_of_pi [fintype ι] {R} [ordered_ring R] [Π i, module R (Mᵢ i)] {Q : Π i, quadratic_form R (Mᵢ i)} (h : (pi Q).anisotropic) : ∀ i, (Q i).anisotropic := begin simp_rw [anisotropic, pi_apply, function.funext_iff, pi.zero_apply] at h, intros i x hx, classical, have := h (pi.single i x) _ i, { rw pi.single_eq_same at this, exact this, }, apply finset.sum_eq_zero, intros j _, by_cases hji : j = i, { subst hji, rw [pi.single_eq_same, hx] }, { rw [pi.single_eq_of_ne hji, map_zero] }, end lemma nonneg_pi_iff [fintype ι] {R} [ordered_ring R] [Π i, module R (Mᵢ i)] {Q : Π i, quadratic_form R (Mᵢ i)} : (∀ x, 0 ≤ pi Q x) ↔ (∀ i x, 0 ≤ Q i x) := begin simp_rw [pi, sum_apply, comp_apply, linear_map.proj_apply], dsimp only, split, -- TODO: does this generalize to a useful lemma independent of `quadratic_form`? { intros h i x, classical, convert h (pi.single i x) using 1, rw [finset.sum_eq_single_of_mem i (finset.mem_univ _) (λ j _ hji, _), pi.single_eq_same], rw [pi.single_eq_of_ne hji, map_zero], }, { rintros h x, exact finset.sum_nonneg (λ i hi, h i (x i)), }, end lemma pos_def_pi_iff [fintype ι] {R} [ordered_ring R] [Π i, module R (Mᵢ i)] {Q : Π i, quadratic_form R (Mᵢ i)} : (pi Q).pos_def ↔ (∀ i, (Q i).pos_def) := begin simp_rw [pos_def_iff_nonneg, nonneg_pi_iff], split, { rintros ⟨hle, ha⟩, intro i, exact ⟨hle i, anisotropic_of_pi ha i⟩, }, { intro h, refine ⟨λ i, (h i).1, λ x hx, funext $ λ i, (h i).2 _ _⟩, rw [pi_apply, finset.sum_eq_zero_iff_of_nonneg (λ j hj, _)] at hx, { exact hx _ (finset.mem_univ _) }, exact (h j).1 _ } end end quadratic_form
c46b7e67c061c836a2e9096a92dbe21b92b75d7f
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/polynomial/degree/basic.lean
42798a9feed68edd241d03d7a5fe39e0c6d1732b
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
31,223
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.coeff /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} section semiring variables [semiring R] {p q r : polynomial R} /-- `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 R) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial R, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial R) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial R) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial R) := leading_coeff p = (1 : R) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : polynomial R} (hp : p.monic) : leading_coeff p = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial R) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial R) = 0 := rfl 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 lemma degree_eq_iff_nat_degree_eq {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : polynomial R} {n : ℕ} (hn : n > 0) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : polynomial R} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { rw hp, exact bot_le }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq [semiring S] {q : polynomial S} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff 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 : coeff 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 : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := @option.cases_on _ (λ d, d.get_or_else 0 ≠ n → d ≠ n) p.degree (λ _ h, option.no_confusion h) (λ n' h, mt option.some_inj.mp h) theorem nat_degree_le_of_degree_le {n : ℕ} (H : degree p ≤ n) : nat_degree p ≤ n := show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with | none, H := zero_le _ | (some d), H := with_bot.coe_le_coe.1 H end lemma nat_degree_le_nat_degree (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := begin by_cases hp : p = 0, { rw [hp, nat_degree_zero], exact zero_le _ }, by_cases hq : q = 0, { rw [hq, degree_zero, le_bot_iff, degree_eq_bot] at hpq, cc }, rwa [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_le_coe] at hpq end @[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; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial R) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial R) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, monomial, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : polynomial R} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : polynomial R} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial R) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite (n < 1 + nat_degree p) I _ (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), C (p.coeff i) * X^i := begin ext n, simp only [add_comm, coeff_X_pow, coeff_C_mul, finset.mem_range, finset.sum_mul_boole, finset_sum_coeff, ite_le_nat_degree_coeff], end /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := begin rw finsupp.sum, apply finset.sum_bij_ne_zero (λ n _ _, n), { intros k h₁ h₂, simp only [mem_range], calc k ≤ p.nat_degree : _ ... < n : w, rw finsupp.mem_support_iff at h₁, exact le_nat_degree_of_ne_zero h₁, }, { intros, assumption }, { intros b hb hb', refine ⟨b, _, hb', rfl⟩, rw finsupp.mem_support_iff, contrapose! hb', convert h b, }, { intros, refl } end /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ -- See also `as_sum`. lemma sum_over_range [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) theorem degree_C_mul_X_pow_le (r : R) (n : ℕ) : degree (C r * X^n) ≤ n := begin rw [← single_eq_C_mul_X], refine finset.sup_le (λ b hb, _), rw list.eq_of_mem_singleton (finsupp.support_single_subset hb), exact le_refl _ end theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial R) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:R) n theorem degree_X_le : degree (X : polynomial R) ≤ 1 := by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:R) 1 lemma nat_degree_X_le : (X : polynomial R).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_one : degree (1 : polynomial R) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial R) = 1 := begin unfold X degree monomial single finsupp.support, rw if_neg (one_ne_zero : (1 : R) ≠ 0), refl end @[simp] lemma nat_degree_X : (X : polynomial R).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : polynomial R} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] @[simp] lemma C_eq_int_cast (n : ℤ) : C ↑n = (n : polynomial R) := (C : R →+* _).map_int_cast n @[simp] lemma degree_neg (p : polynomial R) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : polynomial R) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_int_cast, nat_degree_C] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : polynomial R) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : polynomial R) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : polynomial R} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_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 (coeff p 0) := begin refine ext (λ n, _), cases n, { simp }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] } end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial R) = 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)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] 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 [coeff_add, coeff_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_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_of_degree_lt $ lt_of_le_of_lt degree_C_le hp 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, ← coeff_add], exact coeff_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 R) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert 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 ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset ι) (f : ι → polynomial R) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : 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 R) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff 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 (coeff p i * coeff 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 R) : ∀ n, degree (p ^ n) ≤ n •ℕ (degree p) | 0 := by rw [pow_zero, zero_nsmul]; 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_nsmul; exact add_le_add (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact @finsupp.single_eq_same _ _ _ n a } end @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial R) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial R) := leading_coeff_C _ lemma monic.ne_zero_of_zero_ne_one (h : (0:R) ≠ 1) {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { contrapose! h, rwa [h] at hp } lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : polynomial R} (hp : p.monic) : p ≠ 0 := hp.ne_zero_of_zero_ne_one zero_ne_one lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this, coeff_add, zero_add] 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 only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial R) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma nat_degree_mul' (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₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] 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' 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' h, coeff_mul_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₁, h $ by rw [pow_succ, h₁, mul_zero], 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' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n •ℕ (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], 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' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial R) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : R) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial R) * 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] theorem leading_coeff_mul_X_pow {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma nat_degree_mul_le {p q : polynomial R} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial R)) : (∀ p q : polynomial R, p = q) ∧ (∀ a b : R, 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 zero_le_degree_iff {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := ⟨λ h0p hp0, absurd h0p (by rw [hp0, degree_zero]; exact dec_trivial), λ hp0, le_of_not_gt (λ h, by simp [gt, degree_eq_bot, *] at *)⟩ lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := if hp0 : p = 0 then by simp [hp0] else by rw [degree_eq_nat_degree hp0, ← with_bot.coe_zero, with_bot.coe_le_coe, nat.le_zero_iff] theorem degree_le_iff_coeff_zero (f : polynomial R) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nonzero.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma eq_C_of_nat_degree_le_zero {p : polynomial R} (h : nat_degree p ≤ 0) : p = C (coeff p 0) := begin refine polynomial.ext (λ n, _), cases n, { simp }, { have : nat_degree p < nat.succ n := lt_of_le_of_lt h (nat.succ_pos _), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_nat_degree_lt this] } end lemma nat_degree_pos_iff_degree_pos {p : polynomial R} : 0 < nat_degree p ↔ 0 < degree p := ⟨ λ h, ((degree_eq_iff_nat_degree_eq_of_pos h).mpr rfl).symm ▸ (with_bot.some_lt_some.mpr h), by { unfold nat_degree, cases degree p, { rintros ⟨_, ⟨⟩, _⟩ }, { exact with_bot.some_lt_some.mp } } ⟩ end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial R) ^ n) = n | 0 := by simp only [pow_zero, degree_one]; refl | (n+1) := have h : leading_coeff (X : polynomial R) * 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' h, degree_X, degree_X_pow, add_comm]; refl theorem not_is_unit_X : ¬ is_unit (X : polynomial R) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { rw [← coeff_one_zero, ← hgf], simp } end nonzero_semiring section ring variables [ring R] {p q : polynomial R} lemma degree_sub_le (p q : polynomial R) : degree (p - q) ≤ max (degree p) (degree q) := degree_neg q ▸ degree_add_le p (-q) 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⟩ lemma nat_degree_X_sub_C_le {r : R} : (X - C r).nat_degree ≤ 1 := nat_degree_le_of_degree_le $ le_trans (degree_sub_le _ _) $ max_le degree_X_le $ le_trans degree_C_le $ with_bot.coe_le_coe.2 zero_le_one end ring section nonzero_ring variables [nontrivial R] [ring R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X R], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C (c : R) : next_coeff (X - C c) = - c := by simp [next_coeff_of_pos_nat_degree] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : polynomial R) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial R) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial R) ^ 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 : R) : (X : polynomial R) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial R) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn a; exact dec_trivial) theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : polynomial R) ▸ X_pow_sub_C_ne_zero zero_lt_one r lemma nat_degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).nat_degree = n := by { apply nat_degree_eq_of_degree_eq_some, simp [degree_X_pow_sub_C hn], } end nonzero_ring section integral_domain variables [integral_domain R] {p q : polynomial R} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow (p : polynomial R) (n : ℕ) : degree (p ^ n) = n •ℕ (degree p) := by induction n; [simp only [pow_zero, degree_one, zero_nsmul], simp only [*, pow_succ, succ_nsmul, degree_mul]] @[simp] lemma leading_coeff_mul (p q : polynomial R) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` is an `integral_domain`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : polynomial R →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : polynomial R) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := leading_coeff_hom.map_pow p n end integral_domain end polynomial
b95c4badd880cd93c0c679d1834010a7f0d2bf15
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Lean/Elab/TermApp.lean
08b9dfc1e283183501d05d34419fc18f16a05ad6
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,899
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.Elab.Term namespace Lean namespace Elab namespace Term /-- Auxiliary inductive datatype for combining unelaborated syntax and already elaborated expressions. It is used to elaborate applications. -/ inductive Arg | stx (val : Syntax) | expr (val : Expr) instance Arg.inhabited : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩ instance Arg.hasToString : HasToString Arg := ⟨fun arg => match arg with | Arg.stx val => toString val | Arg.expr val => toString val⟩ /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg := (name : Name) (val : Arg) instance NamedArg.hasToString : HasToString NamedArg := ⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩ instance NamedArg.inhabited : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩ /-- Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument with the same name. -/ def addNamedArg (ref : Syntax) (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do when (namedArgs.any $ fun namedArg' => namedArg.name == namedArg'.name) $ throwError ref ("argument '" ++ toString namedArg.name ++ "' was already set"); pure $ namedArgs.push namedArg /-- Consume parameters of the form `(x : A := val)` and `(x : A . tactic)` -/ private def consumeDefaultParams (ref : Syntax) : Expr → Expr → TermElabM Expr | eType, e => -- TODO pure e private def synthesizeAppInstMVars (ref : Syntax) (instMVars : Array MVarId) : TermElabM Unit := instMVars.forM $ fun mvarId => unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId SyntheticMVarKind.typeClass private def elabArg (ref : Syntax) (arg : Arg) (expectedType : Expr) : TermElabM Expr := match arg with | Arg.expr val => do valType ← inferType ref val; ensureHasType ref expectedType valType val | Arg.stx val => do val ← elabTerm val expectedType; valType ← inferType ref val; ensureHasType ref expectedType valType val private partial def elabAppArgsAux (ref : Syntax) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : Nat → Array NamedArg → Array MVarId → Expr → Expr → TermElabM Expr | argIdx, namedArgs, instMVars, eType, e => do let finalize : Unit → TermElabM Expr := fun _ => do { -- all user explicit arguments have been consumed e ← if explicit then pure e else consumeDefaultParams ref eType e; e ← ensureHasType ref expectedType? eType e; synthesizeAppInstMVars ref instMVars; pure e }; eType ← whnfForall ref eType; match eType with | Expr.forallE n d b c => match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let arg := namedArgs.get! idx; let namedArgs := namedArgs.eraseIdx idx; argElab ← elabArg ref arg.val d; elabAppArgsAux argIdx namedArgs instMVars (b.instantiate1 argElab) (mkApp e argElab) | none => let processExplictArg : Unit → TermElabM Expr := fun _ => do { if h : argIdx < args.size then do argElab ← elabArg ref (args.get ⟨argIdx, h⟩) d; elabAppArgsAux (argIdx + 1) namedArgs instMVars (b.instantiate1 argElab) (mkApp e argElab) else if namedArgs.isEmpty then finalize () else throwError ref ("explicit parameter '" ++ n ++ "' is missing, unused named arguments " ++ toString (namedArgs.map $ fun narg => narg.name)) }; if explicit then processExplictArg () else match c.binderInfo with | BinderInfo.implicit => do a ← mkFreshExprMVar ref d; elabAppArgsAux argIdx namedArgs instMVars (b.instantiate1 a) (mkApp e a) | BinderInfo.instImplicit => do a ← mkFreshExprMVar ref d MetavarKind.synthetic; elabAppArgsAux argIdx namedArgs (instMVars.push a.mvarId!) (b.instantiate1 a) (mkApp e a) | _ => processExplictArg () | _ => if namedArgs.isEmpty && argIdx == args.size then finalize () else -- TODO: try `HasCoeToFun` throwError ref "too many arguments" private def elabAppArgs (ref : Syntax) (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do fType ← inferType ref f; fType ← instantiateMVars ref fType; tryPostponeIfMVar fType; let argIdx := 0; let instMVars := #[]; elabAppArgsAux ref args expectedType? explicit argIdx namedArgs instMVars fType f /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (ref : Syntax) (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError ref $ msg ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType private def resolveLValAux (ref : Syntax) (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := match eType.getAppFn, lval with | Expr.const structName _ _, LVal.fieldIdx idx => do when (idx == 0) $ throwError ref "invalid projection, index must be greater than 0"; env ← getEnv; unless (isStructureLike env structName) $ throwLValError ref e eType "invalid projection, structure expected"; let fieldNames := getStructureFields env structName; if h : idx - 1 < fieldNames.size then if isStructure env structName then pure $ LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩) else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ pure $ LValResolution.projIdx structName (idx - 1) else throwLValError ref e eType ("invalid projection, structure has only " ++ toString fieldNames.size ++ " field(s)") | Expr.const structName _ _, LVal.fieldName fieldName => do env ← getEnv; let searchEnv (fullName : Name) : TermElabM LValResolution := do { match env.find? fullName with | some _ => pure $ LValResolution.const structName fullName | none => throwLValError ref e eType $ "invalid field notation, '" ++ fieldName ++ "' is not a valid \"field\" because environment does not contain '" ++ fullName ++ "'" }; -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do { let fullName := structName ++ fieldName; currNamespace ← getCurrNamespace; let localName := fullName.replacePrefix currNamespace Name.anonymous; lctx ← getLCtx; match lctx.findFromUserName? localName with | some localDecl => if localDecl.binderInfo == BinderInfo.auxDecl then /- LVal notation is being used to make a "local" recursive call. -/ pure $ LValResolution.localRec structName fullName localDecl.toExpr else searchEnv fullName | none => searchEnv fullName }; if isStructure env structName then match findField? env structName fieldName with | some baseStructName => pure $ LValResolution.projFn baseStructName structName fieldName | none => searchCtx () else searchCtx () | Expr.const structName _ _, LVal.getOp idx => do env ← getEnv; let fullName := mkNameStr structName "getOp"; match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError ref e eType $ "invalid [..] notation because environment does not contain '" ++ fullName ++ "'" | _, LVal.getOp idx => throwLValError ref e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError ref e eType "invalid field notation, type is not of the form (C ...) where C is a constant" private partial def resolveLValLoop (ref : Syntax) (e : Expr) (lval : LVal) : Expr → Array Elab.Exception → TermElabM LValResolution | eType, previousExceptions => do eType ← whnfCore ref eType; tryPostponeIfMVar eType; catch (resolveLValAux ref e eType lval) (fun ex => match ex with | Exception.postpone => throw ex | Exception.error ex => do eType? ← unfoldDefinition? ref eType; match eType? with | some eType => resolveLValLoop eType (previousExceptions.push ex) | none => do previousExceptions.forM $ fun ex => logMessage ex; throw (Exception.error ex)) private def resolveLVal (ref : Syntax) (e : Expr) (lval : LVal) : TermElabM LValResolution := do eType ← inferType ref e; resolveLValLoop ref e lval eType #[] private partial def mkBaseProjections (ref : Syntax) (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do env ← getEnv; match getPathToBaseStructure? env baseStructName structName with | none => throwError ref "failed to access field in parent structure" | some path => path.foldlM (fun e projFunName => do projFn ← mkConst ref projFunName; elabAppArgs ref projFn #[{ name := `self, val := Arg.expr e }] #[] none false) e /- Auxiliary method for field notation. It tries to add `e` to `args` as the first explicit parameter which takes an element of type `(C ...)` where `C` is `baseName`. `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (ref : Syntax) (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) : Nat → Array NamedArg → Expr → TermElabM (Array Arg) | i, namedArgs, Expr.forallE n d b c => if !c.binderInfo.isExplicit then addLValArg i namedArgs b else /- If there is named argument with name `n`, then we should skip. -/ match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let namedArgs := namedArgs.eraseIdx idx; addLValArg i namedArgs b | none => do if d.consumeMData.isAppOf baseName then pure $ args.insertAt i (Arg.expr e) else if i < args.size then addLValArg (i+1) namedArgs b else throwError ref $ "invalid field notation, insufficient number of arguments for '" ++ fullName ++ "'" | _, _, fType => throwError ref $ "invalid field notation, function '" ++ fullName ++ "' does not have explicit argument with type (" ++ baseName ++ " ...)" private def elabAppLValsAux (ref : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs ref f namedArgs args expectedType? explicit | f, lval::lvals => do lvalRes ← resolveLVal ref f lval; match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f; elabAppLValsAux f lvals | LValResolution.projFn baseStructName structName fieldName => do f ← mkBaseProjections ref baseStructName structName f; projFn ← mkConst ref (baseStructName ++ fieldName); if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[{ name := `self, val := Arg.expr f }] #[] none false; elabAppLValsAux f lvals | LValResolution.const baseName constName => do projFn ← mkConst ref constName; if lvals.isEmpty then do projFnType ← inferType ref projFn; args ← addLValArg ref baseName constName f args 0 namedArgs projFnType; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.localRec baseName fullName fvar => if lvals.isEmpty then do fvarType ← inferType ref fvar; args ← addLValArg ref baseName fullName f args 0 namedArgs fvarType; elabAppArgs ref fvar namedArgs args expectedType? explicit else do f ← elabAppArgs ref fvar #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.getOp fullName idx => do getOpFn ← mkConst ref fullName; if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; namedArgs ← addNamedArg ref namedArgs { name := `idx, val := Arg.stx idx }; elabAppArgs ref getOpFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] none false; elabAppLValsAux f lvals private def elabAppLVals (ref : Syntax) (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do when (!lvals.isEmpty && explicit) $ throwError ref "invalid use of field notation with `@` modifier"; elabAppLValsAux ref namedArgs args expectedType? explicit f lvals def elabExplicitUniv (stx : Syntax) : TermElabM (List Level) := do let lvls := stx.getArg 1; lvls.foldSepRevArgsM (fun stx lvls => do lvl ← elabLevel stx; pure (lvl::lvls)) [] private partial def elabAppFn (ref : Syntax) : Syntax → List LVal → Array NamedArg → Array Arg → Option Expr → Bool → Array TermElabResult → TermElabM (Array TermElabResult) | f, lvals, namedArgs, args, expectedType?, explicit, acc => if f.getKind == choiceKind then f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit acc) acc else match_syntax f with | `(@$id:id) => elabAppFn id lvals namedArgs args expectedType? true acc | `($(e).$idx:fieldIdx) => let idx := idx.isFieldIdx?.get!; elabAppFn (f.getArg 0) (LVal.fieldIdx idx :: lvals) namedArgs args expectedType? explicit acc | `($(e).$field:ident) => let newLVals := field.getId.components.map (fun n => LVal.fieldName (toString n)); elabAppFn (f.getArg 0) (newLVals ++ lvals) namedArgs args expectedType? explicit acc | `($e[$idx]) => elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit acc -- TODO: replace `*` with new `?` optional modifier | `($id:ident$us:explicitUniv*) => -- Remark: `id.<namedPattern>` should already have been expanded match id with | Syntax.ident _ _ n preresolved => do us ← if us.isEmpty then pure [] else elabExplicitUniv (us.get! 0); funLVals ← resolveName f n preresolved us; funLVals.foldlM (fun acc ⟨f, fields⟩ => do let lvals' := fields.map LVal.fieldName; s ← observing $ elabAppLVals ref f (lvals' ++ lvals) namedArgs args expectedType? explicit; pure $ acc.push s) acc | _ => throwUnexpectedSyntax id "identifier" | _ => do f ← elabTerm f none; s ← observing $ elabAppLVals ref f lvals namedArgs args expectedType? explicit; pure $ acc.push s private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult := candidates.filter $ fun c => match c with | EStateM.Result.ok _ _ => true | _ => false private def toMessageData (msg : Message) (stx : Syntax) : TermElabM MessageData := do strPos ← getPos stx; pos ← getPosition strPos; if pos == msg.pos then pure msg.data else pure $ toString msg.pos.line ++ ":" ++ toString msg.pos.column ++ " " ++ msg.data private def mergeFailures {α} (failures : Array TermElabResult) (stx : Syntax) : TermElabM α := do msgs ← failures.mapM $ fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error ex s => toMessageData ex stx; throwError stx ("overloaded, errors " ++ MessageData.ofArray msgs) private def elabAppAux (ref : Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) : TermElabM Expr := do /- TODO: if `f` contains `choice` or overloaded symbols, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we should postpone until `?m` is assigned. Another (more expensive) option is: execute, and if successes > 1, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we postpone `elabAppAux`. It is more expensive because we would have to re-elaborate the whole thing after we assign `?m`. We **can't** continue from `TermElabResult` since they contain a snapshot of the state, and state has changed. -/ candidates ← elabAppFn ref f [] namedArgs args expectedType? false #[]; if candidates.size == 1 then applyResult $ candidates.get! 0 else let successes := getSuccess candidates; if successes.size == 1 then applyResult $ successes.get! 0 else if successes.size > 1 then do lctx ← getLCtx; opts ← getOptions; let msgs : Array MessageData := successes.map $ fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := s.env, mctx := s.mctx, lctx := lctx, opts := opts } e | _ => unreachable!; throwError f ("ambiguous, possible interpretations " ++ MessageData.ofArray msgs) else mergeFailures candidates f private partial def expandApp : Syntax → TermElabM (Syntax × Array NamedArg × Array Arg) | stx => match_syntax stx with | `($fn ($id := $arg)) => do (stx, namedArgs, args) ← expandApp fn; namedArgs ← addNamedArg id namedArgs { name := id.getId, val := Arg.stx arg }; pure (stx, namedArgs, args) | `($fn $arg) => do (stx, namedArgs, args) ← expandApp fn; let args := args.push $ Arg.stx arg; pure (stx, namedArgs, args) | _ => pure (stx, #[], #[]) @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => do (f, namedArgs, args) ← expandApp stx.val; elabAppAux stx.val f namedArgs args expectedType? @[builtinTermElab «id»] def elabId : TermElab := elabApp @[builtinTermElab explicit] def elabExplicit : TermElab := elabApp @[builtinTermElab choice] def elabChoice : TermElab := elabApp @[builtinTermElab proj] def elabProj : TermElab := elabApp @[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabApp @[builtinTermElab sortApp] def elabSortApp : TermElab := fun stx _ => do u ← elabLevel (stx.getArg 1); if (stx.getArg 0).getKind == `Lean.Parser.Term.sort then do pure $ mkSort u else pure $ mkSort (mkLevelSucc u) @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.app; pure () end Term end Elab end Lean
3691e49b28eb05ef337cc000478d2bfa41f5627c
a19a4fce1e5677f4d20cbfdf60c04b6386ab8210
/library/init/wf.lean
979e586e841f8afe1c47f550d8db6fca9ba8a4f9
[ "Apache-2.0" ]
permissive
nthomas103/lean
9c341a316e7d9faa00546462f90a8aa402e17eac
04eaf184a92606a56e54d0d6c8d59437557263fc
refs/heads/master
1,586,061,106,806
1,454,640,115,000
1,454,641,279,000
51,127,143
0
0
null
1,454,648,683,000
1,454,648,683,000
null
UTF-8
Lean
false
false
4,386
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.relation init.tactic inductive acc {A : Type} (R : A → A → Prop) : A → Prop := intro : ∀x, (∀ y, R y x → acc R y) → acc R x namespace acc variables {A : Type} {R : A → A → Prop} definition inv {x y : A} (H₁ : acc R x) (H₂ : R y x) : acc R y := acc.rec_on H₁ (λ x₁ ac₁ iH H₂, ac₁ y H₂) H₂ -- dependent elimination for acc protected definition drec [recursor] {C : Π (a : A), acc R a → Type} (h₁ : Π (x : A) (acx : Π (y : A), R y x → acc R y), (Π (y : A) (ryx : R y x), C y (acx y ryx)) → C x (acc.intro x acx)) {a : A} (h₂ : acc R a) : C a h₂ := begin refine acc.rec _ h₂ h₂, intro x acx ih h₂, exact h₁ x acx (λ y ryx, ih y ryx (acx y ryx)) end end acc inductive well_founded [class] {A : Type} (R : A → A → Prop) : Prop := intro : (∀ a, acc R a) → well_founded R namespace well_founded definition apply [coercion] {A : Type} {R : A → A → Prop} (wf : well_founded R) : ∀a, acc R a := take a, well_founded.rec_on wf (λp, p) a section parameters {A : Type} {R : A → A → Prop} local infix `≺`:50 := R hypothesis [Hwf : well_founded R] theorem recursion {C : A → Type} (a : A) (H : Πx, (Πy, y ≺ x → C y) → C x) : C a := acc.rec_on (Hwf a) (λ x₁ ac₁ iH, H x₁ iH) theorem induction {C : A → Prop} (a : A) (H : ∀x, (∀y, y ≺ x → C y) → C x) : C a := recursion a H variable {C : A → Type} variable F : Πx, (Πy, y ≺ x → C y) → C x definition fix_F (x : A) (a : acc R x) : C x := acc.rec_on a (λ x₁ ac₁ iH, F x₁ iH) theorem fix_F_eq (x : A) (r : acc R x) : fix_F F x r = F x (λ (y : A) (p : y ≺ x), fix_F F y (acc.inv r p)) := begin induction r using acc.drec, reflexivity -- proof is trivial due to proof irrelevance end end variables {A : Type} {C : A → Type} {R : A → A → Prop} -- Well-founded fixpoint definition fix [Hwf : well_founded R] (F : Πx, (Πy, R y x → C y) → C x) (x : A) : C x := fix_F F x (Hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fix_eq [Hwf : well_founded R] (F : Πx, (Πy, R y x → C y) → C x) (x : A) : fix F x = F x (λy h, fix F y) := fix_F_eq F x (Hwf x) end well_founded open well_founded -- Empty relation is well-founded definition empty.wf {A : Type} : well_founded empty_relation := well_founded.intro (λ (a : A), acc.intro a (λ (b : A) (lt : false), false.rec _ lt)) -- Subrelation of a well-founded relation is well-founded namespace subrelation section parameters {A : Type} {R Q : A → A → Prop} parameters (H₁ : subrelation Q R) parameters (H₂ : well_founded R) definition accessible {a : A} (ac : acc R a) : acc Q a := using H₁, begin induction ac with x ax ih, constructor, exact λ (y : A) (lt : Q y x), ih y (H₁ lt) end definition wf : well_founded Q := well_founded.intro (λ a, accessible (H₂ a)) end end subrelation -- The inverse image of a well-founded relation is well-founded namespace inv_image section parameters {A B : Type} {R : B → B → Prop} parameters (f : A → B) parameters (H : well_founded R) private definition acc_aux {b : B} (ac : acc R b) : ∀ x, f x = b → acc (inv_image R f) x := begin induction ac with x acx ih, intro z e, constructor, intro y lt, subst x, exact ih (f y) lt y rfl end definition accessible {a : A} (ac : acc R (f a)) : acc (inv_image R f) a := acc_aux ac a rfl definition wf : well_founded (inv_image R f) := well_founded.intro (λ a, accessible (H (f a))) end end inv_image -- The transitive closure of a well-founded relation is well-founded namespace tc section parameters {A : Type} {R : A → A → Prop} local notation `R⁺` := tc R definition accessible {z} (ac: acc R z) : acc R⁺ z := begin induction ac with x acx ih, constructor, intro y rel, induction rel with a b rab a b c rab rbc ih₁ ih₂, {exact ih a rab}, {exact acc.inv (ih₂ acx ih) rab} end definition wf (H : well_founded R) : well_founded R⁺ := well_founded.intro (λ a, accessible (H a)) end end tc
c3517769f873eedb52493cf7b12156fc8200d62a
63abd62053d479eae5abf4951554e1064a4c45b4
/test/lint.lean
e05d72363a1c5e4fc2d57365daa2fb79fc13cf95
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
4,343
lean
import tactic.lint import algebra.ring.basic def foo1 (n m : ℕ) : ℕ := n + 1 def foo2 (n m : ℕ) : m = m := by refl lemma foo3 (n m : ℕ) : ℕ := n - m lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances lemma foo.bar (ε > 0) : ε = ε := rfl -- >/≥ is allowed in binders (and in fact, in all hypotheses) -- section -- local attribute [instance, priority 1001] classical.prop_decidable -- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) -- end open tactic meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d run_cmd do let t := name × list ℕ, e ← get_env, let l := e.filter (λ d, e.in_current_file d.to_name ∧ ¬ d.is_auto_or_internal e), l2 ← fold_over_with_cond l (return ∘ check_unused_arguments), guard $ l2.length = 4, let l2 : list t := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ (⟨`foo1, [2]⟩ : t) ∈ l2, guard $ (⟨`foo2, [1]⟩ : t) ∈ l2, guard $ (⟨`foo.foo, [2]⟩ : t) ∈ l2, guard $ (⟨`foo.bar, [2]⟩ : t) ∈ l2, l2 ← fold_over_with_cond l linter.def_lemma.test, guard $ l2.length = 2, let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3, l3 ← fold_over_with_cond l linter.dup_namespace.test, guard $ l3.length = 1, guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo, l4 ← fold_over_with_cond l linter.ge_or_gt.test, guard $ l4.length = 1, guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo, -- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4, (_, s) ← lint ff, guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string, (_, s2) ← lint tt, guard $ s.to_string ≠ s2.to_string, skip /- check customizability and nolint -/ meta def dummy_check (d : declaration) : tactic (option string) := return $ if d.to_name.last = "foo" then some "gotcha!" else none meta def linter.dummy_linter : linter := { test := dummy_check, auto_decls := ff, no_errors_found := "found nothing", errors_found := "found something" } @[nolint dummy_linter] def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) run_cmd do (_, s) ← lint tt lint_verbosity.medium [`linter.dummy_linter] tt, guard $ "/- found something: -/\n#print foo.foo /- gotcha! -/\n".is_suffix_of s.to_string def incorrect_type_class_argument_test {α : Type} (x : α) [x = x] [decidable_eq α] [group α] : unit := () run_cmd do d ← get_decl `incorrect_type_class_argument_test, x ← linter.incorrect_type_class_argument.test d, guard $ x = some "These are not classes. argument 3: [_inst_1 : x = x]" section def impossible_instance_test {α β : Type} [add_group α] : has_add α := infer_instance local attribute [instance] impossible_instance_test run_cmd do d ← get_decl `impossible_instance_test, x ← linter.impossible_instance.test d, guard $ x = some "Impossible to infer argument 2: {β : Type}" def dangerous_instance_test {α β γ : Type} [ring α] [add_comm_group β] [has_coe α β] [has_inv γ] : has_add β := infer_instance local attribute [instance] dangerous_instance_test run_cmd do d ← get_decl `dangerous_instance_test, x ← linter.dangerous_instance.test d, guard $ x = some "The following arguments become metavariables. argument 1: {α : Type}, argument 3: {γ : Type}" end section def foo_has_mul {α} [has_mul α] : has_mul α := infer_instance local attribute [instance, priority 1] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 20 d, guard $ s = "type-class inference timed out" local attribute [instance, priority 10000] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end /- test of `apply_to_fresh_variables` -/ run_cmd do e ← mk_const `id, e2 ← apply_to_fresh_variables e, type_check e2, `(@id %%α %%a) ← instantiate_mvars e2, expr.sort (level.succ $ level.mvar u) ← infer_type α, skip
6f4a24d0bf8731ef15a6172098b7992d6d03b570
05b503addd423dd68145d68b8cde5cd595d74365
/src/topology/order.lean
db9c7e2f6cefb8e43d2db0f962ba6b46916c50c3
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,676
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.basic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `α` are ordered, by reverse inclusion. That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂` if every set open in `t₂` is also open in `t₁`. (One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.) Any function `f : α → β` induces `induced f : topological_space β → topological_space α` and `coinduced f : topological_space α → topological_space β`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂. * A map f : (α, t) → (β, u) is continuous iff t ≤ induced f u (`continuous_iff_le_induced`) iff coinduced f t ≤ u (`continuous_iff_coinduced_le`). Topologies on α form a complete lattice, with ⊥ the discrete topology and ⊤ the indiscrete topology. For a function f : α → β, (coinduced f, induced f) is a Galois connection between topologies on α and topologies on β. ## Implementation notes There is a Galois insertion between topologies on α (with the inclusion ordering) and all collections of sets in α. The complete lattice structure on topologies on α is defined as the reverse of the one obtained via this Galois insertion. ## Tags finer, coarser, induced topology, coinduced topology -/ open set filter classical open_locale classical topological_space universes u v w namespace topological_space variables {α : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ g, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) := by rw nhds_def; exact le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, begin revert as, clear_, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat ... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) /-- Construct a topology on α given the filter of neighborhoods of each point of α. -/ protected def mk_of_nhds (n : α → filter α) : topological_space α := { is_open := λs, ∀a∈s, s ∈ n a, is_open_univ := assume x h, univ_mem_sets, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : α → filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') : @nhds α (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb, have h₁ : {b | s ∈ n b} ∈ 𝓝 a, { refine mem_nhds_sets (assume b (hb : s ∈ n b), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_sets_of_superset ht h }, exact mem_sets_of_superset h₁ h₀ }, { rcases (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {α : Type u} {β : Type v} /-- The inclusion ordering on topologies on α. We use it to get a complete lattice instance via the Galois insertion method, but the partial order that we will eventually impose on `topological_space α` is the reverse one. -/ def tmp_order : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } local attribute [instance] tmp_order /- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/ private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ _, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm /-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part sends a collection of subsets of α to the topology they generate, and whose upper part sends a topology to its collection of open subsets. -/ def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) : topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ := (gi_generate_from _).gc.monotone_l h /-- The complete lattice of topological spaces, but built on the inclusion ordering. -/ def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice /-- The ordering on topologies on the type `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (topological_space α) := { le := λ t s, s.is_open ≤ t.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, le_trans h₂ h₁ } lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} : t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} := generate_from_le_iff_subset_is_open /-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremem is the topology whose open sets are those sets open in every member of the collection. -/ instance : complete_lattice (topological_space α) := @order_dual.complete_lattice _ tmp_complete_lattice /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `⊥`. -/ class discrete_topology (α : Type*) [t : topological_space α] : Prop := (eq_bot : t = ⊥) @[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) : is_open s := (discrete_topology.eq_bot α).symm ▸ trivial @[simp] lemma is_closed_discrete [topological_space α] [discrete_topology α] (s : set α) : is_closed s := (discrete_topology.eq_bot α).symm ▸ trivial lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f := λs hs, is_open_discrete _ lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure := begin refine le_antisymm _ (@pure_le_nhds α ⊥), assume a s hs, exact @mem_nhds_sets α ⊥ a s trivial hs end lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure := (discrete_topology.eq_bot α).symm ▸ nhds_bot α lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) : t₁ ≤ t₂ := assume s, show @is_open α t₂ s → @is_open α t₁ s, by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha } lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ := bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x) end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s, is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩, is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩; exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩, exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) := ⟨assume ⟨t, ht, heq⟩, ⟨-t, is_closed_compl_iff.2 ht, by simp only [preimage_compl, heq, compl_compl]⟩, assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp only [preimage_compl, heq.symm]⟩⟩ /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} : @is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.rfl variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma coinduced_le_iff_le_induced {f : α → β } {tα : topological_space α} {tβ : topological_space β} : tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f := iff.intro (assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht) (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) lemma gc_coinduced_induced (f : α → β) : galois_connection (topological_space.coinduced f) (topological_space.induced f) := assume f g, coinduced_le_iff_le_induced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_coinduced_induced g).monotone_u h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ := (gc_coinduced_induced g).u_top @[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g := (gc_coinduced_induced g).u_inf @[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).induced g = (⨅i, (t i).induced g) := (gc_coinduced_induced g).u_infi @[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ := (gc_coinduced_induced f).l_bot @[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f := (gc_coinduced_induced f).l_sup @[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) := (gc_coinduced_induced f).l_supr lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ @[priority 100] instance subsingleton.discrete_topology [topological_space α] [subsingleton α] : discrete_topology α := ⟨eq_bot_of_singletons_open $ λ x, subsingleton.set_cases is_open_empty is_open_univ ({x} : set α)⟩ instance : topological_space empty := ⊥ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space unit := ⊥ instance : discrete_topology unit := ⟨rfl⟩ instance : topological_space bool := ⊥ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space ℕ := ⊥ instance : discrete_topology ℕ := ⟨rfl⟩ instance : topological_space ℤ := ⊥ instance : discrete_topology ℤ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : t ≤ generate_from g := le_generate_from_iff_subset_is_open.2 h lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} : (generate_from b).induced f = topological_space.generate_from (preimage f '' b) := le_antisymm (le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs, generate_open.basic _ $ mem_image_of_mem _ hs) /-- This construction is left adjoint to the operation sending a topology on `α` to its neighborhood filter at a fixed point `a : α`. -/ protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : galois_connection (topological_space.nhds_adjoint a) (λt, @nhds α t a) := assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ } lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi lemma nhds_Inf {s : set (topological_space α)} {a : α} : @nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {γ : Type*} {f : α → β} {ι : Sort*} lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ := iff.rfl lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ := iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_coinduced_le.2 $ le_generate_from h lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := assume s h, ⟨_, h, rfl⟩ lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := assume s ⟨t, ht, s_eq⟩, s_eq ▸ h t ht lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := assume s h, h lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := assume s hs, h s hs lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := assume s h, h₁ _ (h₂ s h) lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := assume s h, h₂ s (h₁ s h) lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f := assume s h, ⟨h₁ s h, h₂ s h⟩ lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_left lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f := continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f := continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f := continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f := continuous_Sup_rng ⟨i, rfl⟩ h lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f := continuous_iff_coinduced_le.2 $ le_inf (continuous_iff_coinduced_le.1 h₁) (continuous_iff_coinduced_le.1 h₂) lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_left lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) : cont t t₂ f → cont (Inf t₁) t₂ f := continuous_le_dom $ Inf_le h₁ lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} (h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f := continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} : cont (t₁ i) t₂ f → cont (infi t₁) t₂ f := continuous_le_dom $ infi_le _ _ lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} (h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i lemma continuous_bot {t : tspace β} : cont ⊥ t f := continuous_iff_le_induced.2 $ bot_le lemma continuous_top {t : tspace α} : cont t ⊤ f := continuous_iff_coinduced_le.2 $ le_top /- 𝓝 in the induced topology -/ theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) : s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s := begin simp only [mem_nhds_sets_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq], split, { rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩, exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ }, rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩, exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ end theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) : @nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) := filter_eq $ by ext s; rw mem_nhds_induced; rw mem_comap_sets lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) : tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) := ⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩ theorem map_nhds_induced_of_surjective [T : topological_space α] {f : β → α} (hf : function.surjective f) (a : β) : map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end constructions section induced open topological_space variables {α : Type*} {β : Type*} variables [t : topological_space β] {f : α → β} theorem is_open_induced_eq {s : set α} : @_root_.is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} := iff.rfl theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma map_nhds_induced_eq {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap h] lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} (hf : ∀x y, f x = f y → x = y) : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := have comap f (𝓝 (f a) ⊓ principal (f '' s)) ≠ ⊥ ↔ 𝓝 (f a) ⊓ principal (f '' s) ≠ ⊥, from ⟨assume h₁ h₂, h₁ $ h₂.symm ▸ comap_bot, assume h, forall_sets_nonempty_iff_ne_bot.mp $ assume s₁ ⟨s₂, hs₂, (hs : f ⁻¹' s₂ ⊆ s₁)⟩, have f '' s ∈ 𝓝 (f a) ⊓ principal (f '' s), from mem_inf_sets_of_right $ by simp [subset.refl], have s₂ ∩ f '' s ∈ 𝓝 (f a) ⊓ principal (f '' s), from inter_mem_sets hs₂ this, let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := nonempty_of_mem_sets h this in ⟨_, hs $ by rwa [←ha₂] at hb₁⟩⟩, calc a ∈ @closure α (topological_space.induced f t) s ↔ (@nhds α (topological_space.induced f t) a) ⊓ principal s ≠ ⊥ : by rw [closure_eq_nhds]; refl ... ↔ comap f (𝓝 (f a)) ⊓ principal (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced, preimage_image_eq _ hf] ... ↔ comap f (𝓝 (f a) ⊓ principal (f '' s)) ≠ ⊥ : by rw [comap_inf, ←comap_principal] ... ↔ _ : by rwa [closure_eq_nhds] end induced section sierpinski variables {α : Type*} [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from h _ is_open_singleton_true, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ end sierpinski section infi variables {α : Type u} {ι : Type v} {t : ι → topological_space α} lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s := begin -- s defines a map from α to Prop, which is continuous iff s is open. suffices : @continuous _ _ (⨆ i, t i) _ s ↔ ∀ i, @continuous _ _ (t i) _ s, { simpa only [continuous_Prop] using this }, simp only [continuous_iff_le_induced, supr_le_iff] end lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s := is_open_supr_iff end infi
c180476937493605f5e3153416c7c8ffa1dc5460
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/anneaux/cpge_anneaux_8.lean
330b119f78ab18f02765d8c20d33459da382b6cd
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
153
lean
import data.real.basic import data.complex.basic theorem cpge_anneaux_8 (f : ring_hom ℂ ℂ) : (∀ x : ℂ, f x = x) ∨ (f = complex.conj) := sorry
cf0e624e06c0bb5a90e424185b36eaa3b761826c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Attributes.lean
4bb6f0247f10df3aa8daa0e5cb0f68638ae7abf8
[ "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
3,121
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.Elab.Util namespace Lean.Elab structure Attribute where kind : AttributeKind := AttributeKind.global name : Name stx : Syntax := Syntax.missing deriving Inhabited instance : ToFormat Attribute where format attr := let kindStr := match attr.kind with | AttributeKind.global => "" | AttributeKind.local => "local " | AttributeKind.scoped => "scoped " Format.bracket "@[" f!"{kindStr}{attr.name}{toString attr.stx}" "]" /-- ``` attrKind := leading_parser optional («scoped» <|> «local») ``` -/ def toAttributeKind (attrKindStx : Syntax) : MacroM AttributeKind := do if attrKindStx[0].isNone then return AttributeKind.global else if attrKindStx[0][0].getKind == ``Lean.Parser.Term.scoped then if (← Macro.getCurrNamespace).isAnonymous then throw <| Macro.Exception.error (← getRef) "scoped attributes must be used inside namespaces" return AttributeKind.scoped else return AttributeKind.local def mkAttrKindGlobal : Syntax := mkNode ``Lean.Parser.Term.attrKind #[mkNullNode] def elabAttr [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadInfoTree m] [MonadLiftT IO m] (attrInstance : Syntax) : m Attribute := do /- attrInstance := ppGroup $ leading_parser attrKind >> attrParser -/ let attrKind ← liftMacroM <| toAttributeKind attrInstance[0] let attr := attrInstance[1] let attr ← liftMacroM <| expandMacros attr let attrName ← if attr.getKind == ``Parser.Attr.simple then pure attr[0].getId.eraseMacroScopes else match attr.getKind with | .str _ s => pure <| Name.mkSimple s | _ => throwErrorAt attr "unknown attribute" let .ok _impl := getAttributeImpl (← getEnv) attrName | throwError "unknown attribute [{attrName}]" /- The `AttrM` does not have sufficient information for expanding macros in `args`. So, we expand them before here before we invoke the attributer handlers implemented using `AttrM`. -/ return { kind := attrKind, name := attrName, stx := attr } def elabAttrs [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLog m] [MonadInfoTree m] [MonadLiftT IO m] (attrInstances : Array Syntax) : m (Array Attribute) := do let mut attrs := #[] for attr in attrInstances do try attrs := attrs.push (← withRef attr do elabAttr attr) catch ex => logException ex return attrs -- leading_parser "@[" >> sepBy1 attrInstance ", " >> "]" def elabDeclAttrs [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLog m] [MonadInfoTree m] [MonadLiftT IO m] (stx : Syntax) : m (Array Attribute) := elabAttrs stx[1].getSepArgs end Lean.Elab
bb3a1d969e1b4444da2f8bbcf58ab004e758a8e8
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/order/bounded_lattice.lean
49be897f7a4c14a7159d7485fd4270374d4db08b
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,686
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import order.lattice import data.option.basic import tactic.pi_instances set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot attribute [pattern] has_bot.bot has_top.top /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := assume h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := begin haveI := classical.dec_eq α, haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff, by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)] end lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := assume ha, hb $ top_unique $ ha ▸ hab end order_top lemma strict_mono.top_preimage_top' [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := assume h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)] end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h end order_bot lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Bounded lattices -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨assume : a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], assume : a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this } ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop := { le := λa b, a → b, le_refl := assume _, id, le_trans := assume a b c f g, g ∘ f, le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := assume a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := assume a b c H, or_iff_not_imp_left.2 $ λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩, top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } noncomputable instance Prop.linear_order : linear_order Prop := { le_total := by intros p q; change (p → q) ∨ (q → p); tauto!, decidable_le := classical.dec_rel _, .. (_ : partial_order Prop) } @[simp] lemma le_iff_imp {p q : Prop} : p ≤ q ↔ (p → q) := iff.rfl section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := assume a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := assume a b h, or.imp (m_p h) (m_q h) end logic instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) := { bot := λ _, ⊥, bot_le := λ x a, bot_le, .. pi.partial_order } /- Function lattices -/ instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) : (⊥ : Π i, α i) i = ⊥ := rfl instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) : (⊤ : Π i, α i) i = ⊤ := rfl instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] : semilattice_sup (Π i, α i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] : semilattice_inf (Π i, α i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] : semilattice_inf_bot (Π i, α i) := by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] : semilattice_inf_top (Π i, α i) := by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] : semilattice_sup_bot (Π i, α i) := by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] : semilattice_sup_top (Π i, α i) := by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] : bounded_lattice (Π i, α i) := { .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot } lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊥ : α) := eq_bot_mono le_top (eq.symm hα) lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊤ : α) := eq_top_mono bot_le hα lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) : subsingleton α := ⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩ lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) : subsingleton α := subsingleton_of_top_le_bot (ge_of_eq hα) /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_eliminator] def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) : Π (n : with_bot α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [preorder α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h @[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} : a.get_or_else ⊥ ≤ b ↔ a ≤ b := by cases a; simp [none_eq_bot, some_eq_coe] instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤) | none x := is_true $ λ a h, option.no_confusion h | (some x) (some y) := if h : x ≤ y then is_true (some_le_some.2 h) else is_false $ by simp * | (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩ instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, decidable_le := with_bot.decidable_le, decidable_lt := with_bot.decidable_lt, ..with_bot.partial_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ assume a b, match a, b with | a, none := assume h : a < ⊥, (not_lt_bot h).elim | none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_eliminator] def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) : Π (n : with_top α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem le_none [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem some_lt_none [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none theorem coe_lt_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b) | (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe] | none := by simp [none_eq_top, coe_lt_top] lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) := λ x y, @with_bot.decidable_le (order_dual α) _ _ y x instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) := λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, decidable_le := with_top.decidable_le, decidable_lt := with_top.decidable_lt, ..with_top.partial_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ assume a b, match a, b with | none, a := assume h : ⊤ < a, (not_top_lt h).elim | some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/ protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/ protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/ protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/ protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/ protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/ protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := assume a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := assume a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod section disjoint section semilattice_inf_bot variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } end semilattice_inf_bot section bounded_lattice variables [bounded_lattice α] {a : α} @[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff] @[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff] end bounded_lattice section bounded_distrib_lattice variables [bounded_distrib_lattice α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ end bounded_distrib_lattice end disjoint /-! ### `is_compl` predicate -/ /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := ⟨λ hz, h.disjoint.mono_left hz, λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩ lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := disjoint_iff.trans h.inf_left_eq_bot_iff lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq
883713e489562c663433a5a9987703d522558a7e
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Environment.lean
e87f555bbb8592ef0e7e8d8ceb2c9a9dcb851afb
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
34,938
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 Std.Data.HashMap import Lean.ImportingFlag import Lean.Data.SMap import Lean.Declaration import Lean.LocalContext import Lean.Util.Path import Lean.Util.FindExpr import Lean.Util.Profile namespace Lean /- Opaque environment extension state. -/ constant EnvExtensionStateSpec : PointedType.{0} def EnvExtensionState : Type := EnvExtensionStateSpec.type instance : Inhabited EnvExtensionState where default := EnvExtensionStateSpec.val def ModuleIdx := Nat instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat) abbrev ConstMap := SMap Name ConstantInfo structure Import where module : Name runtimeOnly : Bool := false instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩ /-- A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk. Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean files are compacted regions. -/ def CompactedRegion := USize @[extern "lean_compacted_region_is_memory_mapped"] constant CompactedRegion.isMemoryMapped : CompactedRegion → Bool /-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/ @[extern "lean_compacted_region_free"] unsafe constant CompactedRegion.free : CompactedRegion → IO Unit /- Environment fields that are not used often. -/ structure EnvironmentHeader where trustLevel : UInt32 := 0 quotInit : Bool := false mainModule : Name := arbitrary imports : Array Import := #[] -- direct imports regions : Array CompactedRegion := #[] -- compacted regions of all imported modules moduleNames : Array Name := #[] -- names of all imported modules deriving Inhabited open Std (HashMap) structure Environment where const2ModIdx : HashMap Name ModuleIdx constants : ConstMap extensions : Array EnvExtensionState header : EnvironmentHeader := {} deriving Inhabited namespace Environment def addAux (env : Environment) (cinfo : ConstantInfo) : Environment := { env with constants := env.constants.insert cinfo.name cinfo } @[export lean_environment_find] def find? (env : Environment) (n : Name) : Option ConstantInfo := /- It is safe to use `find'` because we never overwrite imported declarations. -/ env.constants.find?' n def contains (env : Environment) (n : Name) : Bool := env.constants.contains n def imports (env : Environment) : Array Import := env.header.imports def allImportedModuleNames (env : Environment) : Array Name := env.header.moduleNames @[export lean_environment_set_main_module] def setMainModule (env : Environment) (m : Name) : Environment := { env with header := { env.header with mainModule := m } } @[export lean_environment_main_module] def mainModule (env : Environment) : Name := env.header.mainModule @[export lean_environment_mark_quot_init] private def markQuotInit (env : Environment) : Environment := { env with header := { env.header with quotInit := true } } @[export lean_environment_quot_init] private def isQuotInit (env : Environment) : Bool := env.header.quotInit @[export lean_environment_trust_level] private def getTrustLevel (env : Environment) : UInt32 := env.header.trustLevel def getModuleIdxFor? (env : Environment) (declName : Name) : Option ModuleIdx := env.const2ModIdx.find? declName def isConstructor (env : Environment) (declName : Name) : Bool := match env.find? declName with | ConstantInfo.ctorInfo _ => true | _ => false def getModuleIdx? (env : Environment) (moduleName : Name) : Option ModuleIdx := env.header.moduleNames.findIdx? (. == moduleName) end Environment inductive KernelException where | unknownConstant (env : Environment) (name : Name) | alreadyDeclared (env : Environment) (name : Name) | declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr) | declHasMVars (env : Environment) (name : Name) (expr : Expr) | declHasFVars (env : Environment) (name : Name) (expr : Expr) | funExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr) | exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr) | appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr) | invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr) | other (msg : String) namespace Environment /- Type check given declaration and add it to the environment -/ @[extern "lean_add_decl"] constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment /- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/ @[extern "lean_compile_decl"] constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do let env ← addDecl env decl compileDecl env opt decl end Environment /- Interface for managing environment extensions. -/ structure EnvExtensionInterface where ext : Type → Type inhabitedExt {σ} : Inhabited σ → Inhabited (ext σ) registerExt {σ} (mkInitial : IO σ) : IO (ext σ) setState {σ} (e : ext σ) (env : Environment) : σ → Environment modifyState {σ} (e : ext σ) (env : Environment) : (σ → σ) → Environment getState {σ} [Inhabited σ] (e : ext σ) (env : Environment) : σ mkInitialExtStates : IO (Array EnvExtensionState) ensureExtensionsSize : Environment → IO Environment instance : Inhabited EnvExtensionInterface where default := { ext := id inhabitedExt := id ensureExtensionsSize := fun env => pure env registerExt := fun mk => mk setState := fun _ env _ => env modifyState := fun _ env _ => env getState := fun ext _ => ext mkInitialExtStates := pure #[] } /- Unsafe implementation of `EnvExtensionInterface` -/ namespace EnvExtensionInterfaceUnsafe structure Ext (σ : Type) where idx : Nat mkInitial : IO σ deriving Inhabited private builtin_initialize envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState)) ← IO.mkRef #[] /-- User-defined environment extensions are declared using the `initialize` command. This command is just syntax sugar for the `init` attribute. When we `import` lean modules, the vector stored at `envExtensionsRef` may increase in size because of user-defined environment extensions. When this happens, we must adjust the size of the `env.extensions`. This method is invoked when processing `import`s. -/ partial def ensureExtensionsArraySize (env : Environment) : IO Environment := do loop env.extensions.size env where loop (i : Nat) (env : Environment) : IO Environment := do let envExtensions ← envExtensionsRef.get if h : i < envExtensions.size then let s ← envExtensions[i].mkInitial let env := { env with extensions := env.extensions.push s } loop (i + 1) env else return env private def invalidExtMsg := "invalid environment extension has been accessed" unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment := if h : ext.idx < env.extensions.size then { env with extensions := env.extensions.set ⟨ext.idx, h⟩ (unsafeCast s) } else panic! invalidExtMsg @[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment := if ext.idx < env.extensions.size then { env with extensions := env.extensions.modify ext.idx fun s => let s : σ := unsafeCast s let s : σ := f s unsafeCast s } else panic! invalidExtMsg unsafe def getState {σ} [Inhabited σ] (ext : Ext σ) (env : Environment) : σ := if h : ext.idx < env.extensions.size then let s : EnvExtensionState := env.extensions.get ⟨ext.idx, h⟩ unsafeCast s else panic! invalidExtMsg unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do unless (← initializing) do throw (IO.userError "failed to register environment, extensions can only be registered during initialization") let exts ← envExtensionsRef.get let idx := exts.size let ext : Ext σ := { idx := idx, mkInitial := mkInitial, } envExtensionsRef.modify fun exts => exts.push (unsafeCast ext) pure ext def mkInitialExtStates : IO (Array EnvExtensionState) := do let exts ← envExtensionsRef.get exts.mapM fun ext => ext.mkInitial unsafe def imp : EnvExtensionInterface := { ext := Ext ensureExtensionsSize := ensureExtensionsArraySize inhabitedExt := fun _ => ⟨arbitrary⟩ registerExt := registerExt setState := setState modifyState := modifyState getState := getState mkInitialExtStates := mkInitialExtStates } end EnvExtensionInterfaceUnsafe @[implementedBy EnvExtensionInterfaceUnsafe.imp] constant EnvExtensionInterfaceImp : EnvExtensionInterface def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ private def ensureExtensionsArraySize (env : Environment) : IO Environment := EnvExtensionInterfaceImp.ensureExtensionsSize env namespace EnvExtension instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f def getState {σ : Type} [Inhabited σ] (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env end EnvExtension /- Environment extensions can only be registered during initialization. Reasons: 1- Our implementation assumes the number of extensions does not change after an environment object is created. 2- We do not use any synchronization primitive to access `envExtensionsRef`. -/ def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates @[export lean_mk_empty_environment] def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do let initializing ← IO.initializing if initializing then throw (IO.userError "environment objects cannot be created during initialization") let exts ← mkInitialExtensionStates pure { const2ModIdx := {}, constants := {}, header := { trustLevel := trustLevel }, extensions := exts } structure PersistentEnvExtensionState (α : Type) (σ : Type) where importedEntries : Array (Array α) -- entries per imported module state : σ structure ImportM.Context where env : Environment opts : Options abbrev ImportM := ReaderT Lean.ImportM.Context IO /- An environment extension with support for storing/retrieving entries from a .olean file. - α is the type of the entries that are stored in .olean files. - β is the type of values used to update the state. - σ is the actual state. Remark: for most extensions α and β coincide. Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as ``` def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) ``` without using `IO`. We have many functions like `addAlias`. `α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example, closures which we currently cannot store in files. -/ structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) where toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ) name : Name addImportedFn : Array (Array α) → ImportM σ addEntryFn : σ → β → σ exportEntriesFn : σ → Array α statsFn : σ → Format /- Opaque persistent environment extension entry. -/ constant EnvExtensionEntrySpec : PointedType.{0} def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type instance : Inhabited EnvExtensionEntry := ⟨EnvExtensionEntrySpec.val⟩ instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) := ⟨{importedEntries := #[], state := arbitrary }⟩ instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) where default := { toEnvExtension := arbitrary, name := arbitrary, addImportedFn := fun _ => arbitrary, addEntryFn := fun s _ => s, exportEntriesFn := fun _ => #[], statsFn := fun _ => Format.nil } namespace PersistentEnvExtension def getModuleEntries {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α := (ext.toEnvExtension.getState env).importedEntries.get! m def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment := ext.toEnvExtension.modifyState env fun s => let state := ext.addEntryFn s.state b; { s with state := state } def getState {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) : σ := (ext.toEnvExtension.getState env).state def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := s } def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := f (ps.state) } end PersistentEnvExtension builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[] structure PersistentEnvExtensionDescr (α β σ : Type) where name : Name mkInitial : IO σ addImportedFn : Array (Array α) → ImportM σ addEntryFn : σ → β → σ exportEntriesFn : σ → Array α statsFn : σ → Format := fun _ => Format.nil unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do let pExts ← persistentEnvExtensionsRef.get if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used") let ext ← registerEnvExtension do let initial ← descr.mkInitial let s : PersistentEnvExtensionState α σ := { importedEntries := #[], state := initial } pure s let pExt : PersistentEnvExtension α β σ := { toEnvExtension := ext, name := descr.name, addImportedFn := descr.addImportedFn, addEntryFn := descr.addEntryFn, exportEntriesFn := descr.exportEntriesFn, statsFn := descr.statsFn } persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt) return pExt @[implementedBy registerPersistentEnvExtensionUnsafe] constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) /- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/ def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ) @[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ := as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState structure SimplePersistentEnvExtensionDescr (α σ : Type) where name : Name addEntryFn : σ → α → σ addImportedFn : Array (Array α) → σ toArrayFn : List α → Array α := fun es => es.toArray def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) := registerPersistentEnvExtension { name := descr.name, mkInitial := pure ([], descr.addImportedFn #[]), addImportedFn := fun as => pure ([], descr.addImportedFn as), addEntryFn := fun s e => match s with | (entries, s) => (e::entries, descr.addEntryFn s e), exportEntriesFn := fun s => descr.toArrayFn s.1.reverse, statsFn := fun s => format "number of local entries: " ++ format s.1.length } namespace SimplePersistentEnvExtension instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) := inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ))) def getEntries {α σ : Type} [Inhabited σ] (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α := (PersistentEnvExtension.getState ext env).1 def getState {α σ : Type} [Inhabited σ] (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ := (PersistentEnvExtension.getState ext env).2 def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s)) def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s)) end SimplePersistentEnvExtension /-- Environment extension for tagging declarations. Declarations must only be tagged in the module where they were declared. -/ def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n, toArrayFn := fun es => es.toArray.qsort Name.quickLt } namespace TagDeclarationExtension instance : Inhabited TagDeclarationExtension := inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet)) def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment := ext.addEntry env n def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool := match env.getModuleIdxFor? n with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt | none => (ext.getState env).contains n end TagDeclarationExtension /-- Environment extension for mapping declarations to values. -/ def MapDeclarationExtension (α : Type) := SimplePersistentEnvExtension (Name × α) (NameMap α) def mkMapDeclarationExtension [Inhabited α] (name : Name) : IO (MapDeclarationExtension α) := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n.1 n.2 , toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1) } namespace MapDeclarationExtension instance : Inhabited (MapDeclarationExtension α) := inferInstanceAs (Inhabited (SimplePersistentEnvExtension ..)) def insert (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) (val : α) : Environment := ext.addEntry env (declName, val) def find? [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Option α := match env.getModuleIdxFor? declName with | some modIdx => match (ext.getModuleEntries env modIdx).binSearch (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) with | some e => some e.2 | none => none | none => (ext.getState env).find? declName def contains [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Bool := match env.getModuleIdxFor? declName with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) | none => (ext.getState env).contains declName end MapDeclarationExtension /- Content of a .olean file. We use `compact.cpp` to generate the image of this object in disk. -/ structure ModuleData where imports : Array Import constants : Array ConstantInfo entries : Array (Name × Array EnvExtensionEntry) instance : Inhabited ModuleData := ⟨{imports := arbitrary, constants := arbitrary, entries := arbitrary }⟩ @[extern "lean_save_module_data"] constant saveModuleData (fname : @& System.FilePath) (mod : @& Name) (data : @& ModuleData) : IO Unit @[extern "lean_read_module_data"] constant readModuleData (fname : @& System.FilePath) : IO (ModuleData × CompactedRegion) /-- Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in particular, `env` should be the last reference to any `Environment` derived from these imports. -/ @[noinline, export lean_environment_free_regions] unsafe def Environment.freeRegions (env : Environment) : IO Unit := /- NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field. Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in compacted regions, is freed after the regions. In the currently produced IR, we indeed see: ``` def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj := let x_3 : obj := proj[3] x_1; inc x_3; dec x_1; ... ``` TODO: statically check for this. -/ env.header.regions.forM CompactedRegion.free def mkModuleData (env : Environment) : IO ModuleData := do let pExts ← persistentEnvExtensionsRef.get let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold (fun i result => let state := (pExts.get! i).getState env let exportEntriesFn := (pExts.get! i).exportEntriesFn let extName := (pExts.get! i).name result.push (extName, exportEntriesFn state)) #[] pure { imports := env.header.imports, constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[], entries := entries } @[export lean_write_module] def writeModule (env : Environment) (fname : System.FilePath) : IO Unit := do saveModuleData fname env.mainModule (← mkModuleData env) private partial def getEntriesFor (mod : ModuleData) (extId : Name) (i : Nat) : Array EnvExtensionEntry := if i < mod.entries.size then let curr := mod.entries.get! i; if curr.1 == extId then curr.2 else getEntriesFor mod extId (i+1) else #[] private def setImportedEntries (env : Environment) (mods : Array ModuleData) (startingAt : Nat := 0) : IO Environment := do let mut env := env let pExtDescrs ← persistentEnvExtensionsRef.get for mod in mods do for extDescr in pExtDescrs[startingAt:] do let entries := getEntriesFor mod extDescr.name 0 env ← extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.push entries } return env /- "Forward declaration" needed for updating the attribute table with user-defined attributes. User-defined attributes are declared using the `initialize` command. The `initialize` command is just syntax sugar for the `init` attribute. The `init` attribute is initialized after the `attributeExtension` is initialized. We cannot change the order since the `init` attribute is an attribute, and requires this extension. The `attributeExtension` initializer uses `attributeMapRef` to initialize the attribute mapping. When we a new user-defined attribute declaration is imported, `attributeMapRef` is updated. Later, we set this method with code that adds the user-defined attributes that were imported after we initialized `attributeExtension`. -/ builtin_initialize updateEnvAttributesRef : IO.Ref (Environment → IO Environment) ← IO.mkRef (fun env => pure env) private partial def finalizePersistentExtensions (env : Environment) (mods : Array ModuleData) (opts : Options) : IO Environment := do loop 0 env where loop (i : Nat) (env : Environment) : IO Environment := do -- Recall that the size of the array stored `persistentEnvExtensionRef` may increase when we import user-defined environment extensions. let pExtDescrs ← persistentEnvExtensionsRef.get if h : i < pExtDescrs.size then let extDescr := pExtDescrs[i] let s := extDescr.toEnvExtension.getState env let prevSize := (← persistentEnvExtensionsRef.get).size let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts } let mut env ← extDescr.toEnvExtension.setState env { s with state := newState } env ← ensureExtensionsArraySize env if (← persistentEnvExtensionsRef.get).size > prevSize then -- This branch is executed when `pExtDescrs[i]` is the extension associated with the `init` attribute, and -- a user-defined persistent extension is imported. -- Thus, we invoke `setImportedEntries` to update the array `importedEntries` with the entries for the new extensions. env ← setImportedEntries env mods prevSize -- See comment at `updateEnvAttributesRef` env ← (← updateEnvAttributesRef.get) env loop (i + 1) env else return env structure ImportState where moduleNameSet : NameSet := {} moduleNames : Array Name := #[] moduleData : Array ModuleData := #[] regions : Array CompactedRegion := #[] @[export lean_import_modules] partial def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" opts do withImporting do let (_, s) ← importMods imports |>.run {} let mut numConsts := 0 for mod in s.moduleData do numConsts := numConsts + mod.constants.size let mut modIdx : Nat := 0 let mut const2ModIdx : HashMap Name ModuleIdx := Std.mkHashMap (capacity := numConsts) let mut constantMap : HashMap Name ConstantInfo := Std.mkHashMap (capacity := numConsts) for mod in s.moduleData do for cinfo in mod.constants do const2ModIdx := const2ModIdx.insert cinfo.name modIdx match constantMap.insert' cinfo.name cinfo with | (constantMap', replaced) => constantMap := constantMap' if replaced then throw (IO.userError s!"import failed, environment already contains '{cinfo.name}'") modIdx := modIdx + 1 let constants : ConstMap := SMap.fromHashMap constantMap false let exts ← mkInitialExtensionStates let env : Environment := { const2ModIdx := const2ModIdx, constants := constants, extensions := exts, header := { quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module trustLevel := trustLevel, imports := imports.toArray, regions := s.regions, moduleNames := s.moduleNames } } let env ← setImportedEntries env s.moduleData let env ← finalizePersistentExtensions env s.moduleData opts pure env where importMods : List Import → StateRefT ImportState IO Unit | [] => pure () | i::is => do if i.runtimeOnly || (← get).moduleNameSet.contains i.module then importMods is else do modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module } let mFile ← findOLean i.module unless (← mFile.pathExists) do throw $ IO.userError s!"object file '{mFile}' of module {i.module} does not exist" let (mod, region) ← readModuleData mFile importMods mod.imports.toList modify fun s => { s with moduleData := s.moduleData.push mod regions := s.regions.push region moduleNames := s.moduleNames.push i.module } importMods is /-- Create environment object from imports and free compacted regions after calling `act`. No live references to the environment object or imported objects may exist after `act` finishes. -/ unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do let env ← importModules imports opts trustLevel try x env finally env.freeRegions builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSSet ← registerSimplePersistentEnvExtension { name := `namespaces, addImportedFn := fun as => mkStateFromImportedEntries NameSSet.insert NameSSet.empty as |>.switch, addEntryFn := fun s n => s.insert n } namespace Environment def registerNamespace (env : Environment) (n : Name) : Environment := if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n def isNamespace (env : Environment) (n : Name) : Bool := (namespacesExt.getState env).contains n def getNamespaceSet (env : Environment) : NameSSet := namespacesExt.getState env private def isNamespaceName : Name → Bool | Name.str Name.anonymous _ _ => true | Name.str p _ _ => isNamespaceName p | _ => false private def registerNamePrefixes : Environment → Name → Environment | env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env | env, _ => env @[export lean_environment_add] def add (env : Environment) (cinfo : ConstantInfo) : Environment := let env := registerNamePrefixes env cinfo.name env.addAux cinfo @[export lean_display_stats] def displayStats (env : Environment) : IO Unit := do let pExtDescrs ← persistentEnvExtensionsRef.get IO.println ("direct imports: " ++ toString env.header.imports); IO.println ("number of imported modules: " ++ toString env.header.regions.size); IO.println ("number of memory-mapped modules: " ++ toString (env.header.regions.filter (·.isMemoryMapped) |>.size)); IO.println ("number of consts: " ++ toString env.constants.size); IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1); IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2); IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets); IO.println ("trust level: " ++ toString env.header.trustLevel); IO.println ("number of extensions: " ++ toString env.extensions.size); pExtDescrs.forM $ fun extDescr => do IO.println ("extension '" ++ toString extDescr.name ++ "'") let s := extDescr.toEnvExtension.getState env let fmt := extDescr.statsFn s.state unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state))) IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0)) @[extern "lean_eval_const"] unsafe constant evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α := throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected") /-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`. This function is still unsafe because it cannot guarantee that `typeName` is in fact the name of the type `α`. -/ unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α := match env.find? constName with | none => throw ("unknown constant '" ++ toString constName ++ "'") | some info => match info.type with | Expr.const c _ _ => if c != typeName then throwUnexpectedType typeName constName else env.evalConst α opts constName | _ => throwUnexpectedType typeName constName def hasUnsafe (env : Environment) (e : Expr) : Bool := let c? := e.find? $ fun e => match e with | Expr.const c _ _ => match env.find? c with | some cinfo => cinfo.isUnsafe | none => false | _ => false; c?.isSome end Environment namespace Kernel /- Kernel API -/ /-- Kernel isDefEq predicate. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_is_def_eq"] constant isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool /-- Kernel WHNF function. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_whnf"] constant whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Expr end Kernel class MonadEnv (m : Type → Type) where getEnv : m Environment modifyEnv : (Environment → Environment) → m Unit export MonadEnv (getEnv modifyEnv) instance (m n) [MonadLift m n] [MonadEnv m] : MonadEnv n where getEnv := liftM (getEnv : m Environment) modifyEnv := fun f => liftM (modifyEnv f : m Unit) /-- If `env` does not contain a declaration with name `declName ++ elemSuffix`, then return `declName`. Otherwise, find the smallest positive `Nat` `i` such that `declName ++ suffix.appendIndexAfter i ++ elemSuffix` is not the name of a declaration in the given environment. -/ partial def mkBaseNameFor (env : Environment) (declName : Name) (elemSuffix : Name) (suffix : Name) : Name := if !env.contains (declName ++ elemSuffix) then declName else go 1 where go (idx : Nat) : Name := let baseName := declName ++ suffix.appendIndexAfter idx if !env.contains (baseName ++ elemSuffix) then baseName else go (idx + 1) end Lean
1deca8db6ef486267a537e3108de37b7bd06ff90
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/adjunction/default.lean
857a80d17b1b63edf7833522aaaf6f9ac5624058
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
85
lean
import category_theory.adjunction.limits import category_theory.adjunction.opposites
42e1bdd37a3fdac0bf5c2cbf58ef90503b394372
63abd62053d479eae5abf4951554e1064a4c45b4
/src/group_theory/semidirect_product.lean
202d83c4d5323c2c9868b3c3ef8443141724a18c
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
9,065
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.equiv.mul_add import logic.function.basic import group_theory.subgroup /-! # Semidirect product This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and `inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure semidirect_product (φ : G →* mul_aut N) := (left : N) (right : G) attribute [pp_using_anonymous_constructor] semidirect_product notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ namespace semidirect_product variables {N G} {φ : G →* mul_aut N} private def one_aux : N ⋊[φ] G := ⟨1, 1⟩ private def mul_aux (a b : N ⋊[φ] G) : N ⋊[φ] G := ⟨a.1 * φ a.2 b.1, a.right * b.right⟩ private def inv_aux (a : N ⋊[φ] G) : N ⋊[φ] G := let i := a.2⁻¹ in ⟨φ i a.1⁻¹, i⟩ private lemma mul_assoc_aux (a b c : N ⋊[φ] G) : mul_aux (mul_aux a b) c = mul_aux a (mul_aux b c) := by simp [mul_aux, mul_assoc, mul_equiv.map_mul] private lemma mul_one_aux (a : N ⋊[φ] G) : mul_aux a one_aux = a := by cases a; simp [mul_aux, one_aux] private lemma one_mul_aux (a : N ⋊[φ] G) : mul_aux one_aux a = a := by cases a; simp [mul_aux, one_aux] private lemma mul_left_inv_aux (a : N ⋊[φ] G) : mul_aux (inv_aux a) a = one_aux := by simp only [mul_aux, inv_aux, one_aux, ← mul_equiv.map_mul, mul_left_inv]; simp instance : group (N ⋊[φ] G) := { one := one_aux, inv := inv_aux, mul := mul_aux, mul_assoc := mul_assoc_aux, one_mul := one_mul_aux, mul_one := mul_one_aux, mul_left_inv := mul_left_inv_aux } instance : inhabited (N ⋊[φ] G) := ⟨1⟩ @[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl @[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl @[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl @[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl @[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl @[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl /-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/ def inl : N →* N ⋊[φ] G := { to_fun := λ n, ⟨n, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl @[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ := inl_injective.eq_iff /-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/ def inr : G →* N ⋊[φ] G := { to_fun := λ g, ⟨1, g⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl @[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ := inr_injective.eq_iff lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ := by ext; simp lemma inl_aut_inv (g : G) (n : N) : (inl ((φ g)⁻¹ n) : N ⋊[φ] G) = inr g⁻¹ * inl n * inr g := by rw [← monoid_hom.map_inv, inl_aut, inv_inv] @[simp] lemma mk_eq_inl_mul_inr (g : G) (n : N) : (⟨n, g⟩ : N ⋊[φ] G) = inl n * inr g := by ext; simp @[simp] lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/ def right_hom : N ⋊[φ] G →* G := { to_fun := semidirect_product.right, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl @[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 := by ext; simp [right_hom] @[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ := by ext; simp [right_hom] @[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 := by simp [right_hom] @[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g := by simp [right_hom] lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) := function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩ lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.to_monoid_hom_apply] at this, simp [this, mul_assoc] end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma lift_unique (F : N ⋊[φ] G →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end /-- Two maps out of the semidirect product are equal if they're equal after composition with both `inl` and `inr` -/ lemma hom_ext {f g : (N ⋊[φ] G) →* H} (hl : f.comp inl = g.comp inl) (hr : f.comp inr = g.comp inr) : f = g := by { rw [lift_unique f, lift_unique g], simp only * } end lift section map variables {N₁ : Type*} {G₁ : Type*} [group N₁] [group G₁] {φ₁ : G₁ →* mul_aut N₁} /-- Define a map from `N ⋊[φ] G` to `N₁ ⋊[φ₁] G₁` given maps `N →* N₁` and `G →* G₁` that satisfy a commutativity condition `∀ n g, f₁ (φ g n) = φ₁ (f₂ g) (f₁ n)`. -/ def map (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* N₁ ⋊[φ₁] G₁ := { to_fun := λ x, ⟨f₁ x.1, f₂ x.2⟩, map_one' := by simp, map_mul' := λ x y, begin replace h := monoid_hom.ext_iff.1 (h x.right) y.left, ext; simp * at *, end } variables (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) @[simp] lemma map_left (g : N ⋊[φ] G) : (map f₁ f₂ h g).left = f₁ g.left := rfl @[simp] lemma map_right (g : N ⋊[φ] G) : (map f₁ f₂ h g).right = f₂ g.right := rfl @[simp] lemma right_hom_comp_map : right_hom.comp (map f₁ f₂ h) = f₂.comp right_hom := rfl @[simp] lemma map_inl (n : N) : map f₁ f₂ h (inl n) = inl (f₁ n) := by simp [map] @[simp] lemma map_comp_inl : (map f₁ f₂ h).comp inl = inl.comp f₁ := by ext; simp @[simp] lemma map_inr (g : G) : map f₁ f₂ h (inr g) = inr (f₂ g) := by simp [map] @[simp] lemma map_comp_inr : (map f₁ f₂ h).comp inr = inr.comp f₂ := by ext; simp [map] end map end semidirect_product
47e5adfb1782ff1d201b50f33a2ed5929a860b57
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Data/Json/Basic.lean
19f0a5001babe854e58aad099a7ff31c36d10c2d
[ "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
4,737
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Std.Data.RBTree namespace Lean -- mantissa * 10^-exponent structure JsonNumber := (mantissa : Int) (exponent : Nat) protected def JsonNumber.decEq : (a b : JsonNumber) → Decidable (a = b) | ⟨m1, e1⟩, ⟨m2, e2⟩ => match decEq m1 m2 with | isTrue hm => match decEq e1 e2 with | isTrue he => isTrue $ by rw [hm, he]; rfl | isFalse he => isFalse (fun h => JsonNumber.noConfusion h (fun hm he2 => he he2)) | isFalse hm => isFalse (fun h => JsonNumber.noConfusion h (fun hm2 he => hm hm2)) instance : DecidableEq JsonNumber := JsonNumber.decEq namespace JsonNumber protected def fromNat (n : Nat) : JsonNumber := ⟨n, 0⟩ protected def fromInt (n : Int) : JsonNumber := ⟨n, 0⟩ instance : Coe Nat JsonNumber := ⟨JsonNumber.fromNat⟩ instance : Coe Int JsonNumber := ⟨JsonNumber.fromInt⟩ private partial def countDigitsAux (n digits : Nat) : Nat := if n ≤ 9 then digits else countDigitsAux (n/10) (digits+1) private def countDigits (n : Nat) : Nat := countDigitsAux n 1 protected def toString : JsonNumber → String | ⟨m, 0⟩ => m.repr | ⟨m, e⟩ => let s : Bool := m ≥ 0 let m := m.natAbs -- if there are too many zeroes after the decimal, we -- use exponents to compress the representation. -- this is mostly done for memory usage reasons: -- the size of the representation would otherwise -- grow exponentially in the value of exponent. let exp := 9 + (countDigits m : Int) - (e : Int) let exp := if exp < 0 then exp else 0 let f := 10 ^ (e - exp.natAbs) let left := m / f let right := (f : Int) + m % f let rightUntrimmed := right.repr.mkIterator.next.remainingToString (if s then "" else "-") ++ left.repr ++ "." ++ (rightUntrimmed.toSubstring.dropRightWhile (fun c => c = '0')).toString ++ (if exp = 0 then "" else "e" ++ exp.repr) -- shift a JsonNumber by a specified amount of places to the left protected def shiftl : JsonNumber → Nat → JsonNumber -- if s ≤ e, then 10 ^ (s - e) = 1, and hence the mantissa remains unchanged. -- otherwise, the expression pads the mantissa with zeroes -- to accomodate for the remaining places to shift. | ⟨m, e⟩, s => ⟨m * (10 ^ (s - e) : Nat), e - s⟩ -- shift a JsonNumber by a specified amount of places to the right protected def shiftr : JsonNumber → Nat → JsonNumber | ⟨m, e⟩, s => ⟨m, e + s⟩ instance : ToString JsonNumber := ⟨JsonNumber.toString⟩ instance : Repr JsonNumber := ⟨fun ⟨m, e⟩ => "⟨" ++ m.repr ++ "," ++ e.repr ++ "⟩"⟩ end JsonNumber def strLt (a b : String) := Decidable.decide (a < b) open Std (RBNode RBNode.leaf) inductive Json := | null | bool (b : Bool) | num (n : JsonNumber) | str (s : String) | arr (elems : Array Json) -- uses RBNode instead of RBMap because RBMap is a def -- and thus currently cannot be used to define a type that -- is recursive in one of its parameters | obj (kvPairs : RBNode String (fun _ => Json)) namespace Json -- HACK(Marc): temporary ugliness until we can use RBMap for JSON objects def mkObj (o : List (String × Json)) : Json := obj (o.foldr (fun ⟨k, v⟩ acc => acc.insert strLt k v) RBNode.leaf) instance : Coe Nat Json := ⟨fun n => Json.num n⟩ instance : Coe Int Json := ⟨fun n => Json.num n⟩ instance : Coe String Json := ⟨Json.str⟩ instance : Coe Bool Json := ⟨Json.bool⟩ def getObj? : Json → Option (RBNode String (fun _ => Json)) | obj kvs => kvs | _ => none def getArr? : Json → Option (Array Json) | arr a => a | _ => none def getStr? : Json → Option String | str s => some s | _ => none def getNat? : Json → Option Nat | (n : Nat) => some n | _ => none def getInt? : Json → Option Int | (i : Int) => some i | _ => none def getBool? : Json → Option Bool | (b : Bool) => some b | _ => none def getNum? : Json → Option JsonNumber | num n => n | _ => none def getObjVal? : Json → String → Option Json | obj kvs, k => kvs.find strLt k | _ , _ => none def getArrVal? : Json → Nat → Option Json | arr a, i => a.get? i | _ , _ => none def getObjValD (j : Json) (k : String) : Json := (j.getObjVal? k).getD null inductive Structured := | arr (elems : Array Json) | obj (kvPairs : RBNode String (fun _ => Json)) instance : Coe (Array Json) Structured := ⟨Structured.arr⟩ instance : Coe (RBNode String (fun _ => Json)) Structured := ⟨Structured.obj⟩ end Json end Lean
45abb74f66e7ab558eaffac63e203dd491351e4a
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/algebra/archimedean.lean
87750a75073b56cb4568e461aafe6f46a8ecd22c
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,902
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Archimedean groups and fields. -/ import algebra.field_power import data.rat variables {α : Type*} /-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y` such that `0 < y` there exists a natural number `n` such that `x ≤ n •ℕ y`. -/ class archimedean (α) [ordered_add_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n •ℕ y) namespace linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] [archimedean α] /-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for `a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/ lemma exists_int_smul_near_of_pos {a : α} (ha : 0 < a) (g : α) : ∃ k, k •ℤ a ≤ g ∧ g < (k + 1) •ℤ a := begin let s : set ℤ := {n : ℤ | n •ℤ a ≤ g}, obtain ⟨k, hk : -g ≤ k •ℕ a⟩ := archimedean.arch (-g) ha, have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩, obtain ⟨k, hk⟩ := archimedean.arch g ha, have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ) := λ n hn, (gsmul_le_gsmul_iff ha).mp (le_trans hn hk : n •ℤ a ≤ k •ℤ a), obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne, refine ⟨m, hm, _⟩, by_contra H, linarith [hm' _ $ not_lt.mp H] end lemma exists_int_smul_near_of_pos' {a : α} (ha : 0 < a) (g : α) : ∃ k, 0 ≤ g - k •ℤ a ∧ g - k •ℤ a < a := begin obtain ⟨k, h1, h2⟩ := exists_int_smul_near_of_pos ha g, refine ⟨k, sub_nonneg.mpr h1, _⟩, have : g < k •ℤ a + 1 •ℤ a, by rwa ← add_gsmul a k 1, simpa [sub_lt_iff_lt_add'] end end linear_ordered_add_comm_group theorem exists_nat_gt [ordered_semiring α] [nontrivial α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ theorem exists_nat_ge [ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x ≤ n := begin nontriviality α, exact (exists_nat_gt x).imp (λ n, le_of_lt) end lemma add_one_pow_unbounded_of_pos [ordered_semiring α] [nontrivial α] [archimedean α] (x : α) {y : α} (hy : 0 < y) : ∃ n : ℕ, x < (y + 1) ^ n := have 0 ≤ 1 + y, from add_nonneg zero_le_one hy.le, let ⟨n, h⟩ := archimedean.arch x hy in ⟨n, calc x ≤ n •ℕ y : h ... = n * y : nsmul_eq_mul _ _ ... < 1 + n * y : lt_one_add _ ... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg hy.le hy.le) (mul_nonneg this this) (add_nonneg zero_le_two hy.le) _ ... = (y + 1) ^ n : by rw [add_comm]⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1) /-- Every x greater than or equal to 1 is between two successive natural-number powers of every y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field α] /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_int_pow_near'`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by rw [(fpow_neg y (↑N))]; exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN)⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (fpow_le_of_le (le_of_lt hy) (le_of_lt hlt)) (lt_of_le_of_lt hm hM))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_int_pow_near`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near' [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) := let ⟨m, hle, hlt⟩ := exists_int_pow_near (inv_pos.2 hx) hy in have hyp : 0 < y, from lt_trans zero_lt_one hy, ⟨-(m+1), by rwa [fpow_neg, inv_lt (fpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, fpow_neg, le_inv hx (fpow_pos_of_pos hyp _)]⟩ /-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/ lemma exists_pow_lt_of_lt_one [archimedean α] {x y : α} (hx : 0 < x) (hy : y < 1) : ∃ n : ℕ, y ^ n < x := begin by_cases y_pos : y ≤ 0, { use 1, simp only [pow_one], linarith, }, rw [not_le] at y_pos, rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩, exact ⟨q, by rwa [inv_pow', inv_lt_inv hx (pow_pos y_pos _)] at hq⟩ end /-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`. This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/ lemma exists_nat_pow_near_of_lt_one [archimedean α] {x : α} {y : α} (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) : ∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n := begin rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩) with ⟨n, hn, h'n⟩, refine ⟨n, _, _⟩, { rwa [inv_pow', inv_lt_inv xpos (pow_pos ypos _)] at h'n }, { rwa [inv_pow', inv_le_inv (pow_pos ypos _) xpos] at hn } end variables [floor_ring α] lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) : 0 ≤ x - ⌊x / y⌋ * y := begin conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← sub_mul, exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy) end lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) : x - ⌊x / y⌋ * y < y := sub_lt_iff_lt_add.2 begin conv in y {rw ← one_mul y}, conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← add_mul, exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _), end end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [nsmul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ /-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some cases we have a computable `floor` function. -/ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _ _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨nat_ceil q, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh, have n0 := nat.cast_pos.1 n0', rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases exists_nat_gt (1/ε) with n hn, use n, rw [div_lt_iff, ← div_lt_iff' hε], { apply hn.trans, simp [zero_lt_one] }, { exact n.cast_add_one_pos } end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 include α @[simp] theorem rat.cast_floor (x : ℚ) : by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ := begin haveI := archimedean.floor_ring α, apply le_antisymm, { rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int], apply floor_le }, { rw [le_floor, ← rat.cast_coe_int, rat.cast_le], apply floor_le } end end linear_ordered_field section variables [linear_ordered_field α] /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round [floor_ring α] (x : α) : ℤ := ⌊x + 1 / 2⌋ lemma abs_sub_round [floor_ring α] (x : α) : abs (x - round x) ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end variable [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ @[simp] theorem rat.cast_round (x : ℚ) : by haveI := archimedean.floor_ring α; exact round (x:α) = round x := have ((x + (1 : ℚ) / (2 : ℚ) : ℚ) : α) = x + 1 / 2, by simp, by rw [round, round, ← this, rat.cast_floor] end
6cab65e604412cf20afd2affce2402c830450c55
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/algebra/archimedean.lean
6d037a1d01d271ea1ff4980b7970a88afb723580
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
9,204
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Archimedean groups and fields. -/ import algebra.group_power data.rat data.int.order local infix ` • ` := add_monoid.smul variables {α : Type*} class floor_ring (α) extends linear_ordered_ring α := (floor : α → ℤ) (le_floor : ∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x) instance : floor_ring ℤ := { floor := id, le_floor := by simp, ..linear_ordered_comm_ring.to_linear_ordered_ring ℤ } instance : floor_ring ℚ := { floor := rat.floor, le_floor := @rat.le_floor, ..linear_ordered_comm_ring.to_linear_ordered_ring ℚ } section variable [floor_ring α] def floor : α → ℤ := floor_ring.floor notation `⌊` x `⌋` := floor x theorem le_floor : ∀ {z : ℤ} {x : α}, z ≤ ⌊x⌋ ↔ (z : α) ≤ x := floor_ring.le_floor theorem floor_lt {x : α} {z : ℤ} : ⌊x⌋ < z ↔ x < z := le_iff_le_iff_lt_iff_lt.1 le_floor theorem floor_le (x : α) : (⌊x⌋ : α) ≤ x := le_floor.1 (le_refl _) theorem floor_nonneg {x : α} : 0 ≤ ⌊x⌋ ↔ 0 ≤ x := by simpa using @le_floor _ _ 0 x theorem lt_succ_floor (x : α) : x < ⌊x⌋.succ := floor_lt.1 $ int.lt_succ_self _ theorem lt_floor_add_one (x : α) : x < ⌊x⌋ + 1 := by simpa [int.succ] using lt_succ_floor x theorem sub_one_lt_floor (x : α) : x - 1 < ⌊x⌋ := sub_lt_iff_lt_add.2 (lt_floor_add_one x) @[simp] theorem floor_coe (z : ℤ) : ⌊(z:α)⌋ = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] @[simp] theorem floor_zero : ⌊(0:α)⌋ = 0 := floor_coe 0 @[simp] theorem floor_one : ⌊(1:α)⌋ = 1 := by rw [← int.cast_one, floor_coe] theorem floor_mono {a b : α} (h : a ≤ b) : ⌊a⌋ ≤ ⌊b⌋ := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (x : α) (z : ℤ) : ⌊x + z⌋ = ⌊x⌋ + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] theorem floor_sub_int (x : α) (z : ℤ) : ⌊x - z⌋ = ⌊x⌋ - z := eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _) /-- `ceil x` is the smallest integer `z` such that `x ≤ z` -/ def ceil (x : α) : ℤ := -⌊-x⌋ notation `⌈` x `⌉` := ceil x theorem ceil_le {z : ℤ} {x : α} : ⌈x⌉ ≤ z ↔ x ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem lt_ceil {x : α} {z : ℤ} : z < ⌈x⌉ ↔ (z:α) < x := le_iff_le_iff_lt_iff_lt.1 ceil_le theorem le_ceil (x : α) : x ≤ ⌈x⌉ := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ⌈(z:α)⌉ = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : α} (h : a ≤ b) : ⌈a⌉ ≤ ⌈b⌉ := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (x : α) (z : ℤ) : ⌈x + z⌉ = ⌈x⌉ + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (x : α) (z : ℤ) : ⌈x - z⌉ = ⌈x⌉ - z := eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _) theorem ceil_lt_add_one (x : α) : (⌈x⌉ : α) < x + 1 := by rw [← lt_ceil, ← int.cast_one, ceil_add_int]; apply lt_add_one lemma ceil_pos {a : α} : 0 < ⌈a⌉ ↔ 0 < a := ⟨ λ h, have ⌊-a⌋ < 0, from neg_of_neg_pos h, pos_of_neg_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).1 $ not_le_of_gt this, λ h, have -a < 0, from neg_neg_of_pos h, neg_pos_of_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).2 $ not_le_of_gt this ⟩ lemma ceil_nonneg {q : ℚ} (hq : q ≥ 0) : ⌈q⌉ ≥ 0 := if h : q > 0 then le_of_lt $ ceil_pos.2 h else have h' : q = 0, from le_antisymm (le_of_not_lt h) hq, by simp [h'] end class archimedean (α) [ordered_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) theorem exists_nat_gt [linear_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by simpa using h) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_gt_one (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := have hy0 : 0 < y - 1 := sub_pos_of_lt hy1, let ⟨n, h⟩ := archimedean.arch x hy0 in ⟨n, calc x ≤ n • (y - 1) : h ... < 1 + n • (y - 1) : by rw add_comm; exact lt_add_one _ ... ≤ y ^ n : pow_ge_one_add_sub_mul (le_of_lt hy1) _⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by simp [h]⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by simp [neg_lt.1 h]⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, begin simp [add_monoid.smul_eq_mul], refine le_trans (int.le_to_nat _) _, simpa using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat), end⟩⟩ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← add_monoid.smul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by simp [h]⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨rat.nat_ceil q, lt_of_lt_of_le h $ by simpa using (@rat.cast_le α _ _ _).2 (rat.le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by simp [h]⟩ theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := let ⟨n, h⟩ := exists_nat_gt x⁻¹ in begin have n0 := nat.cast_pos.1 (lt_trans (inv_pos x0) h), refine ⟨n⁻¹, inv_pos (nat.cast_pos.2 n0), _⟩, simpa [rat.cast_inv_of_ne_zero, ne_of_gt n0] using (inv_lt x0 (nat.cast_pos.2 n0)).1 h end theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0 := nat.cast_pos.1 (lt_trans (inv_pos (sub_pos.2 h)) nh), simp [rat.cast_div_of_ne_zero, -int.cast_add, ne_of_gt n0], have n0' := (@nat.cast_pos α _ _).2 n0, refine ⟨(lt_div_iff n0').2 $ (le_iff_le_iff_lt_iff_lt.1 (zh _)).1 (lt_add_one _), _⟩, simp [div_lt_iff n0', -add_comm], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div_eq_inv] end include α @[simp] theorem rat.cast_floor (x : ℚ) : by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ := begin haveI := archimedean.floor_ring α, apply le_antisymm, { rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int], apply floor_le }, { rw [le_floor, ← rat.cast_coe_int, rat.cast_le], apply floor_le } end end linear_ordered_field section variables [discrete_linear_ordered_field α] [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : ε > 0) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ end instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by simp⟩
9e385cf38e46eff2a79a1caf1523b819f741c174
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/instructor/lectures/lecture_18.lean
5165a365cb9dd59d897b5f296194cd73b064eb68
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
7,528
lean
import data.set /- Up to now we have mostly used our intuition to understand operations on, and special values (empty and complete) of sets. Now, to prepare to state and prove theorems about sets, we will see how to formalize these ideas in predicate logic. We isolate our own definitions in a namespace so as not to conflict with the corresponding definitions from the Lean libraries. -/ namespace hidden /- We define the concept of a set of values of type α as nothing other than a predicate on values of this type. (Previously we've used T as a type parameter but lower case Greek letters are also often used for this purpose.) -/ def set (α : Type) := α → Prop /- And given any one-place predicate on α, we can view it as defining a set. -/ def set_of {α : Type} (p : α → Prop) : set α := p /- For the rest of this section, the following declaration allow us to use α and β as arguments without having to introduce them explicitly in each definition. The way it works is that if α appears in a definition, Lean will silently add "∀ {α : Type}" as an argument to the definition. -/ variables {α β : Type} /- Membership of a value a in a set s is defined by the proposition, s a, obtained by applying the membership predicate, s, to the value a. If the resulting proposition is true then a is in s. If (s a) is false, a's not in s. -/ def mem (a : α) (s : set α) := s a /- Note: The use of α in the previous definition causes Lean to insert a declaration, (α : Type), in the definition. So the definition is actually equivant to the following: def mem (α : Type) (a : α) (s : set α) := s a -/ /- a ∈ s is simply notation for the proposition (mem s a), which in turn is just (s a). See preceding definition. -/ notation a ∈ s := mem a s notation a ∉ s := ¬ (mem a s) /- We can now formally define what we mean when we say that a set, s₁, is a subset of a set, s₂: that if any value, a, is in s₁ then it is also in s₂. For example, s₁ = {1, 2} is a subset of s₂ = {1, 2, 3, 4} because any value being in s₁ implies that it is also in s₂. 1 is in s₁ and it is also in s₂, and the same goes for 2. Those are all the values in s₁, so for any value, if it's in s₁ it's also in s₂, so s₁ is a subset of s₂. -/ def subset (s₁ s₂ : set α) := ∀ ⦃a : α⦄, a ∈ s₁ → a ∈ s₂ /- You can read the curly braces in ⦃a : α⦄ as if they were ordinary {a : α} braces. They tell Lean to infer these arguments. There's a subtle technical differences that is not important here. -/ notation s₁ ⊆ s₂ := subset s₁ s₂ /- It is common in predicate logic to talk about all the subset of elements in a set, s, that satisfy a predicate, p. Here's a function that when given a predicate and a set (with the right types) returns the set (as a predicate, of coures) of elements in s that also satisfy p. -/ def sep (p : α → Prop) (s : set α) : set α := {a | a ∈ s ∧ p a} /- Exercise: Given the assumptions that evens and primes are sets of natural numbers, write an expression for the subset of evens that are also prime. -/ axioms (evens primes : ℕ → Prop) def even_primes : set ℕ := _ /- Exercises: 1) Express sep evens primes in English -- answer 2) Assume that evens really is the set of even natural numbers and primes is the set of prime numbers. What set of values is in even_primes? -/ /- The empty set of values of any given type is defined by the predicate that is false for each value of that type. Here we express this predicate as the function that, when given any value, a, of type α, returns false. The type of this function is α → false, and so it is, we now see clearly, a predicate. No value satisfies it, so it represents the set with no values, the empty set for the type, α. -/ def empty_set {α : Type} (a : α) := false #check @empty_set def empty_nat : set ℕ := empty_set /- To understand the preceding definition of empty_set takes a little help. It takes two arguments, the first, α, is a type, which is *implicit* (inferred from context), and the second is a value of -/ /- Here's another notation, new for you in this class. Read the λ as meaning ∀: in other words, given a value, a, of type, α, this function returns the proposition, false. λ is the symbol used to declare the arguments of a function. The overall expression, λ (a : α), false, is called a lambda expression, It denotes exactly the funciton that takes any a and returns the proposition, false (which, again, of course, is of type α → Prop), making it a predicate, and one that defined the empty set. FIX -/ def empty_set' : set α := λ (a : α), false -- The notation φ is used for empty set def φ := empty_set α #check empty_set α /- The complete, or *universal* set of values of a type α is defined similarly, but now we use a proposition that is true for every value, making every value of a given type a member of the set. -/ def univ : set α := λ a, true /- We can even start to define functions that look a little like "imperative" operations, mutator functions, on sets. Here we define an insert operation that takes a set and a value, both of the same type, and returns a new set with the members of the given set and the new value as its members. -/ def insert (a : α) (s : set α) : set α := {b | b = a ∨ b ∈ s} -- example def primes_and_15 := insert 15 primes /- A set with exactly one member value is called a *singleton* set. Here we define the singleton set containing a value a as a set of values all of which are equal to a. -/ def singleton (a : α) : (set α) := {b | b = a} /- Now we come to the standard operators on sets: union, intersection, etc. First the union of two sets, s₁ and s₂ is the set of values that satisfy the disjunction (or) of the individual sets. Thus a value is in the resulting set if and only if it's in one of the contributing sets. -/ def union (s₁ s₂ : set α) : set α := {a | a ∈ s₁ ∨ a ∈ s₂} notation s ∪ t := union s t /- Intersection is defined similarly but now an element is in the resulting set if and only if it's in both of the contributing sets. -/ def inter (s₁ s₂ : set α) : set α := {a | a ∈ s₁ ∧ a ∈ s₂} notation s ∩ t := inter s t /- The complement of a set of values of type α is the set of elements of this type that are not in the given set. -/ def compl (s : set α) : set α := {a | a ∉ s} /- Given sets, s and t, the difference, s \ t, is the set of elements in s that are not in t. You can think of this as "s take away t." It's analogous to the idea of subtraction, where, for example, 5 - 2 means 5 take away 2. -/ def diff (s t : set α) : set α := { v | v ∈ s ∧ v ∉ t} /- Powerset -/ def powerset (s : set α) : set (set α) := {t | t ⊆ s} -- Question: What's the type of t, here? -- notation 𝒫 s := powerset s /- Finally, here's a new concept for you, and one that foreshadows our upcoming discussion of functions. The image of a set, s, under a function f, is the set of values obtained by applying f to every value in s. -/ def image (f : α → β) (s : set α) : set β := {b | ∃ a, a ∈ s ∧ f a = b} /- The formal definition sort of goes to a next level of sophistication in the use of predicate logic. It says that the image of the set, s, "under" the function, f, is the set of values, b, such that there is (exists) some value, a ∈ s, f a = b. -/ end hidden
41c2d1948d8d179c96e43d64fe72641064317083
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/wildcardAlt.lean
1b47d2ffbd03d966f7ddb659aae9a877e882a22a
[ "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
507
lean
inductive Foo where | c1 (x : Nat) | c2 | c3 | c4 def bla : Foo → Nat | .c1 x => x + 1 | _ => 2 example (x : Foo) : bla x > 0 := by cases x with | _ => decide -- Error | c1 => decide example (x : Foo) : bla x > 0 := by induction x with | _ => decide -- Error | c1 => decide example (x : Foo) : bla x > 0 := by cases x with | c1 x => simp_arith [bla] | _ => decide example (x : Foo) : bla x > 0 := by induction x with | c1 x => simp_arith [bla] | _ => decide
e721497487462b0f5e2f8b7532449a676b930ed2
76df16d6c3760cb415f1294caee997cc4736e09b
/lean/src/tactic/focus_case.lean
868906c60efda17691f6f899caa80f4b2f233e5c
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
1,681,592,449,670
1,637,037,431,000
1,637,037,431,000
414,331,908
6
1
null
null
null
null
UTF-8
Lean
false
false
3,240
lean
import tactic.basic open tactic.interactive open tactic.interactive.case_tag.match_result setup_tactic_parser -- The case tactic is taken from https://github.com/leanprover-community/lean/pull/508 private meta def goals_with_matching_tag (ns : list name) : tactic (list (expr × case_tag) × list (expr × case_tag)) := do gs ← tactic.get_goals, (gs : list (expr × tactic.tag)) ← gs.mmap (λ g, do t ← tactic.get_tag g, pure (g, t)), pure $ gs.foldr (λ ⟨g, t⟩ ⟨exact_matches, suffix_matches⟩, match case_tag.parse t with | none := ⟨exact_matches, suffix_matches⟩ | some t := match case_tag.match_tag ns t with | exact_match := ⟨⟨g, t⟩ :: exact_matches, suffix_matches⟩ | fuzzy_match := ⟨exact_matches, ⟨g, t⟩ :: suffix_matches⟩ | no_match := ⟨exact_matches, suffix_matches⟩ end end) ([], []) private meta def goal_with_matching_tag (ns : list name) : tactic (expr × case_tag) := do ⟨exact_matches, suffix_matches⟩ ← goals_with_matching_tag ns, match exact_matches, suffix_matches with | [] , [] := tactic.fail format! "Invalid `case`: there is no goal tagged with suffix {ns}." | [] , [g] := pure g | [] , _ := let tags : list (list name) := suffix_matches.map (λ ⟨_, t⟩, t.case_names.reverse) in tactic.fail format! "Invalid `case`: there is more than one goal tagged with suffix {ns}.\nMatching tags: {tags}" | [g], _ := pure g | _ , _ := tactic.fail format! "Invalid `case`: there is more than one goal tagged with tag {ns}." end meta def case_core (args : parse case_parser) (tac : itactic) : tactic (list expr × list expr) := do original_goals ← tactic.get_goals, target_goals ← args.mmap (λ ⟨ns, ids⟩, do ⟨goal, tag⟩ ← goal_with_matching_tag ns, let ids := ids.get_or_else [], let num_ids := ids.length, goals ← tactic.get_goals, let other_goals := goals.filter (≠ goal), tactic.set_goals [goal], match tag with | (case_tag.pi _ num_args) := do tactic.intro_lst ids, when (num_ids < num_args) $ tactic.intron (num_args - num_ids) | (case_tag.hyps _ new_hyp_names) := do let num_new_hyps := new_hyp_names.length, when (num_ids > num_new_hyps) $ tactic.fail format! ("Invalid `case`: You gave {num_ids} names, but the case introduces " ++ "{num_new_hyps} new hypotheses."), let renamings := native.rb_map.of_list (new_hyp_names.zip ids), propagate_tags $ tactic.rename_many renamings tt tt end, goals ← tactic.get_goals, tactic.set_goals other_goals, match goals with | [g] := return g | _ := tactic.fail "Unexpected goals introduced by renaming" end), remaining_goals ← tactic.get_goals, tactic.set_goals target_goals, tac, unsolved_goals ← tactic.get_goals, tactic.set_goals original_goals, return (unsolved_goals, remaining_goals) @[interactive] meta def focus_case (args : parse case_parser) (tac : itactic) : tactic unit := do (unsolved_goals, remaining_goals) ← case_core args tac, tactic.set_goals (unsolved_goals ++ remaining_goals)
17d17170d8cdce9069359ee8b8d5a0adc471c472
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/13_More_Tactics.org.8.lean
bc386f52b0d355710df19d53e7af6ec077cbb312
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
196
lean
import standard variables (A : Type) (a b c d : A) example (H₁ : a = b) (H₂ : c = b) (H₃ : c = d) : a = d := by transitivity b; assumption; transitivity c; symmetry; assumption; assumption
47c9772c4d32dafb8321ffb5df2c13c43ade5999
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/measure_theory/integral/set_integral.lean
7c3e25aee859a9731e350add1a99dc9138e3906c
[ "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
44,879
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.integral.integrable_on import measure_theory.integral.bochner import order.filter.indicator_function /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `integral_union`, `integral_empty`, `integral_univ`. We use the property `integrable_on f s μ := integrable f (μ.restrict s)`, defined in `measure_theory.integrable_on`. We also defined in that same file a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l`. Finally, we prove a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that `∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. ## Notation We provide the following notations for expressing the integral of a function on a set : * `∫ a in s, f a ∂μ` is `measure_theory.integral (μ.restrict s) f` * `∫ a in s, f a` is `∫ a in s, f a ∂volume` Note that the set notations are defined in the file `measure_theory/integral/bochner`, but we reference them here because all theorems about set integrals are in this file. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter ennreal nnreal measure_theory variables {α β E F : Type*} [measurable_space α] namespace measure_theory section normed_group variables [normed_group E] [measurable_space E] {f g : α → E} {s t : set α} {μ ν : measure α} {l l' : filter α} [borel_space E] [second_countable_topology E] variables [complete_space E] [normed_space ℝ E] lemma set_integral_congr_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := integral_congr_ae ((ae_restrict_iff' hs).2 h) lemma set_integral_congr (hs : measurable_set s) (h : eq_on f g s) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := set_integral_congr_ae hs $ eventually_of_forall h lemma set_integral_congr_set_ae (hst : s =ᵐ[μ] t) : ∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ := by rw restrict_congr_set hst lemma integral_union (hst : disjoint s t) (hs : measurable_set s) (ht : measurable_set t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := by simp only [integrable_on, measure.restrict_union hst hs ht, integral_add_measure hfs hft] lemma integral_union_ae (hst : (s ∩ t : set α) =ᵐ[μ] (∅ : set α)) (hs : measurable_set s) (ht : measurable_set t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := begin have : s =ᵐ[μ] s \ t, { refine (hst.mem_iff.mono _).set_eq, simp }, rw [← diff_union_self, integral_union disjoint_diff.symm, set_integral_congr_set_ae this], exacts [hs.diff ht, ht, hfs.mono_set (diff_subset _ _), hft] end lemma integral_diff (hs : measurable_set s) (ht : measurable_set t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) (hts : t ⊆ s) : ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ - ∫ x in t, f x ∂μ := begin rw [eq_sub_iff_add_eq, ← integral_union, diff_union_of_subset hts], exacts [disjoint_diff.symm, hs.diff ht, ht, hfs.mono_set (diff_subset _ _), hft] end lemma integral_finset_bUnion {ι : Type*} (t : finset ι) {s : ι → set α} (hs : ∀ i ∈ t, measurable_set (s i)) (h's : pairwise_on ↑t (disjoint on s)) (hf : ∀ i ∈ t, integrable_on f (s i) μ) : ∫ x in (⋃ i ∈ t, s i), f x ∂ μ = ∑ i in t, ∫ x in s i, f x ∂ μ := begin induction t using finset.induction_on with a t hat IH hs h's, { simp }, { simp only [finset.coe_insert, finset.forall_mem_insert, set.pairwise_on_insert, finset.set_bUnion_insert] at hs hf h's ⊢, rw [integral_union _ hs.1 _ hf.1 (integrable_on_finset_Union.2 hf.2)], { rw [finset.sum_insert hat, IH hs.2 h's.1 hf.2] }, { simp only [disjoint_Union_right], exact (λ i hi, (h's.2 i hi (ne_of_mem_of_not_mem hi hat).symm).1) }, { exact finset.measurable_set_bUnion _ hs.2 } } end lemma integral_fintype_Union {ι : Type*} [fintype ι] {s : ι → set α} (hs : ∀ i, measurable_set (s i)) (h's : pairwise (disjoint on s)) (hf : ∀ i, integrable_on f (s i) μ) : ∫ x in (⋃ i, s i), f x ∂ μ = ∑ i, ∫ x in s i, f x ∂ μ := begin convert integral_finset_bUnion finset.univ (λ i hi, hs i) _ (λ i _, hf i), { simp }, { simp [pairwise_on_univ, h's] } end lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure] lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ] lemma integral_add_compl (hs : measurable_set s) (hfi : integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := by rw [← integral_union (@disjoint_compl_right (set α) _ _) hs hs.compl hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ] /-- For a function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ lemma integral_indicator (hs : measurable_set s) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := begin by_cases hf : ae_measurable f (μ.restrict s), swap, { rw integral_non_ae_measurable hf, rw [← ae_measurable_indicator_iff hs] at hf, exact integral_non_ae_measurable hf }, by_cases hfi : integrable_on f s μ, swap, { rwa [integral_undef, integral_undef], rwa integrable_indicator_iff hs }, calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ : (integral_add_compl hs (hfi.indicator hs)).symm ... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ : congr_arg2 (+) (integral_congr_ae (indicator_ae_eq_restrict hs)) (integral_congr_ae (indicator_ae_eq_restrict_compl hs)) ... = ∫ x in s, f x ∂μ : by simp end lemma tendsto_set_integral_of_monotone {ι : Type*} [encodable ι] [semilattice_sup ι] {s : ι → set α} {f : α → E} (hsm : ∀ i, measurable_set (s i)) (h_mono : monotone s) (hfi : integrable_on f (⋃ n, s n) μ) : tendsto (λ i, ∫ a in s i, f a ∂μ) at_top (𝓝 (∫ a in (⋃ n, s n), f a ∂μ)) := begin have hfi' : ∫⁻ x in ⋃ n, s n, ∥f x∥₊ ∂μ < ∞ := hfi.2, set S := ⋃ i, s i, have hSm : measurable_set S := measurable_set.Union hsm, have hsub : ∀ {i}, s i ⊆ S, from subset_Union s, rw [← with_density_apply _ hSm] at hfi', set ν := μ.with_density (λ x, ∥f x∥₊) with hν, refine metric.nhds_basis_closed_ball.tendsto_right_iff.2 (λ ε ε0, _), lift ε to ℝ≥0 using ε0.le, have : ∀ᶠ i in at_top, ν (s i) ∈ Icc (ν S - ε) (ν S + ε), from tendsto_measure_Union hsm h_mono (ennreal.Icc_mem_nhds hfi'.ne (ennreal.coe_pos.2 ε0).ne'), refine this.mono (λ i hi, _), rw [mem_closed_ball_iff_norm', ← integral_diff hSm (hsm i) hfi (hfi.mono_set hsub) hsub, ← coe_nnnorm, nnreal.coe_le_coe, ← ennreal.coe_le_coe], refine (ennnorm_integral_le_lintegral_ennnorm _).trans _, rw [← with_density_apply _ (hSm.diff (hsm _)), ← hν, measure_diff hsub hSm (hsm _)], exacts [tsub_le_iff_tsub_le.mp hi.1, (hi.2.trans_lt $ ennreal.add_lt_top.2 ⟨hfi', ennreal.coe_lt_top⟩).ne] end lemma has_sum_integral_Union {ι : Type*} [encodable ι] {s : ι → set α} {f : α → E} (hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s)) (hfi : integrable_on f (⋃ i, s i) μ) : has_sum (λ n, ∫ a in s n, f a ∂ μ) (∫ a in ⋃ n, s n, f a ∂μ) := begin have hfi' : ∀ i, integrable_on f (s i) μ, from λ i, hfi.mono_set (subset_Union _ _), simp only [has_sum, ← integral_finset_bUnion _ (λ i _, hm i) (hd.pairwise_on _) (λ i _, hfi' i)], rw Union_eq_Union_finset at hfi ⊢, exact tendsto_set_integral_of_monotone (λ t, t.measurable_set_bUnion (λ i _, hm i)) (λ t₁ t₂ h, bUnion_subset_bUnion_left h) hfi end lemma integral_Union {ι : Type*} [encodable ι] {s : ι → set α} {f : α → E} (hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s)) (hfi : integrable_on f (⋃ i, s i) μ) : (∫ a in (⋃ n, s n), f a ∂μ) = ∑' n, ∫ a in s n, f a ∂ μ := (has_sum.tsum_eq (has_sum_integral_Union hm hd hfi)).symm lemma set_integral_eq_zero_of_forall_eq_zero {f : α → E} (hf : measurable f) (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in t, f x ∂μ = 0 := begin refine integral_eq_zero_of_ae _, rw [eventually_eq, ae_restrict_iff (measurable_set_eq_fun hf measurable_zero)], refine eventually_of_forall (λ x hx, _), rw pi.zero_apply, exact ht_eq x hx, end private lemma set_integral_union_eq_left_of_disjoint {f : α → E} (hf : measurable f) (hfi : integrable f μ) (hs : measurable_set s) (ht : measurable_set t) (ht_eq : ∀ x ∈ t, f x = 0) (hs_disj : disjoint s t) : ∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ := by rw [integral_union hs_disj hs ht hfi.integrable_on hfi.integrable_on, set_integral_eq_zero_of_forall_eq_zero hf ht_eq, add_zero] lemma set_integral_union_eq_left {f : α → E} (hf : measurable f) (hfi : integrable f μ) (hs : measurable_set s) (ht : measurable_set t) (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ := begin let s_ := s \ {x | f x = 0}, have hs_ : measurable_set s_, from hs.diff (measurable_set_eq_fun hf measurable_const), let s0 := s ∩ {x | f x = 0}, have hs0 : measurable_set s0, from hs.inter (measurable_set_eq_fun hf measurable_const), have hs0_eq : ∀ x ∈ s0, f x = 0, by { intros x hx, simp_rw [s0, set.mem_inter_iff] at hx, exact hx.2, }, have h_s_union : s = s_ ∪ s0, from (set.diff_union_inter s _).symm, have h_s_disj : disjoint s_ s0, from (@disjoint_sdiff_self_left (set α) {x | f x = 0} s _).mono_right (set.inter_subset_right _ _), rw [h_s_union, set_integral_union_eq_left_of_disjoint hf hfi hs_ hs0 hs0_eq h_s_disj], have hst0_eq : ∀ x ∈ s0 ∪ t, f x = 0, { intros x hx, rw set.mem_union at hx, cases hx, { exact hs0_eq x hx, }, { exact ht_eq x hx, }, }, have hst_disj : disjoint s_ (s0 ∪ t), { rw [← set.sup_eq_union, disjoint_sup_right], exact ⟨h_s_disj, (@disjoint_sdiff_self_left (set α) {x | f x = 0} s _).mono_right ht_eq⟩, }, rw set.union_assoc, exact set_integral_union_eq_left_of_disjoint hf hfi hs_ (hs0.union ht) hst0_eq hst_disj, end lemma set_integral_neg_eq_set_integral_nonpos [linear_order E] [order_closed_topology E] {f : α → E} (hf : measurable f) (hfi : integrable f μ) : ∫ x in {x | f x < 0}, f x ∂μ = ∫ x in {x | f x ≤ 0}, f x ∂μ := begin have h_union : {x | f x ≤ 0} = {x | f x < 0} ∪ {x | f x = 0}, by { ext, simp_rw [set.mem_union_eq, set.mem_set_of_eq], exact le_iff_lt_or_eq, }, rw h_union, exact (set_integral_union_eq_left hf hfi (measurable_set_lt hf measurable_const) (measurable_set_eq_fun hf measurable_const) (λ x hx, hx)).symm, end lemma integral_norm_eq_pos_sub_neg {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) : ∫ x, ∥f x∥ ∂μ = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ := have h_meas : measurable_set {x | 0 ≤ f x}, from measurable_set_le measurable_const hf, calc ∫ x, ∥f x∥ ∂μ = ∫ x in {x | 0 ≤ f x}, ∥f x∥ ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ∥f x∥ ∂μ : by rw ← integral_add_compl h_meas hfi.norm ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ∥f x∥ ∂μ : begin congr' 1, refine set_integral_congr h_meas (λ x hx, _), dsimp only, rw [real.norm_eq_abs, abs_eq_self.mpr _], exact hx, end ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | 0 ≤ f x}ᶜ, f x ∂μ : begin congr' 1, rw ← integral_neg, refine set_integral_congr h_meas.compl (λ x hx, _), dsimp only, rw [real.norm_eq_abs, abs_eq_neg_self.mpr _], rw [set.mem_compl_iff, set.nmem_set_of_eq] at hx, linarith, end ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ : by { rw ← set_integral_neg_eq_set_integral_nonpos hf hfi, congr, ext1 x, simp, } lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c := by rw [integral_const, measure.restrict_apply_univ] @[simp] lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : measurable_set s) : ∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e := by rw [integral_indicator s_meas, ← set_integral_const] lemma set_integral_indicator_const_Lp {p : ℝ≥0∞} (hs : measurable_set s) (ht : measurable_set t) (hμt : μ t ≠ ∞) (x : E) : ∫ a in s, indicator_const_Lp p ht hμt x a ∂μ = (μ (t ∩ s)).to_real • x := calc ∫ a in s, indicator_const_Lp p ht hμt x a ∂μ = (∫ a in s, t.indicator (λ _, x) a ∂μ) : by rw set_integral_congr_ae hs (indicator_const_Lp_coe_fn.mono (λ x hx hxs, hx)) ... = (μ (t ∩ s)).to_real • x : by rw [integral_indicator_const _ ht, measure.restrict_apply ht] lemma integral_indicator_const_Lp {p : ℝ≥0∞} (ht : measurable_set t) (hμt : μ t ≠ ∞) (x : E) : ∫ a, indicator_const_Lp p ht hμt x a ∂μ = (μ t).to_real • x := calc ∫ a, indicator_const_Lp p ht hμt x a ∂μ = ∫ a in univ, indicator_const_Lp p ht hμt x a ∂μ : by rw integral_univ ... = (μ (t ∩ univ)).to_real • x : set_integral_indicator_const_Lp measurable_set.univ ht hμt x ... = (μ t).to_real • x : by rw inter_univ lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β} (hs : measurable_set s) (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := begin rw [measure.restrict_map hg hs, integral_map hg (hf.mono_measure _)], exact measure.map_mono g measure.restrict_le_self end lemma set_integral_map_of_closed_embedding [topological_space α] [borel_space α] {β} [measurable_space β] [topological_space β] [borel_space β] {g : α → β} {f : β → E} {s : set β} (hs : measurable_set s) (hg : closed_embedding g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := begin rw [measure.restrict_map hg.measurable hs, integral_map_of_closed_embedding hg], apply_instance, end lemma set_integral_map_equiv {β} [measurable_space β] (e : α ≃ᵐ β) (f : β → E) (s : set β) : ∫ y in s, f y ∂(measure.map e μ) = ∫ x in e ⁻¹' s, f (e x) ∂μ := by rw [e.restrict_map, integral_map_equiv] lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin rw ← measure.restrict_apply_univ at *, haveI : is_finite_measure (μ.restrict s) := ⟨‹_›⟩, exact norm_integral_le_of_norm_le_const hC end lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : ae_measurable f (μ.restrict s)) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin apply norm_set_integral_le_of_norm_le_const_ae hs, have A : ∀ᵐ (x : α) ∂μ, x ∈ s → ∥ae_measurable.mk f hfm x∥ ≤ C, { filter_upwards [hC, hfm.ae_mem_imp_eq_mk], assume a h1 h2 h3, rw [← h2 h3], exact h1 h3 }, have B : measurable_set {x | ∥(hfm.mk f) x∥ ≤ C} := hfm.measurable_mk.norm measurable_set_Iic, filter_upwards [hfm.ae_eq_mk, (ae_restrict_iff B).2 A], assume a h1 h2, rwa h1 end lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal] lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ∞) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : ae_measurable f (μ.restrict s)) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : ∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 := integral_eq_zero_iff_of_nonneg_ae hf hfi lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : 0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) := begin rw [integral_pos_iff_support_of_nonneg_ae hf hfi, restrict_apply_of_null_measurable_set], exact hfi.ae_measurable.null_measurable_set (measurable_set_singleton 0).compl end lemma set_integral_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → E} (hf_meas : @measurable _ _ m _ f) {s : set α} (hs : measurable_set[m] s) : ∫ x in s, f x ∂μ = ∫ x in s, f x ∂(μ.trim hm) := by rwa [integral_trim hm hf_meas, restrict_trim hm μ] end normed_group section mono variables {μ : measure α} {f g : α → ℝ} {s t : set α} (hf : integrable_on f s μ) (hg : integrable_on g s μ) lemma set_integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict s] g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := integral_mono_ae hf hg h lemma set_integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := set_integral_mono_ae_restrict hf hg (ae_restrict_of_ae h) lemma set_integral_mono_on (hs : measurable_set s) (h : ∀ x ∈ s, f x ≤ g x) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := set_integral_mono_ae_restrict hf hg (by simp [hs, eventually_le, eventually_inf_principal, ae_of_all _ h]) include hf hg -- why do I need this include, but we don't need it in other lemmas? lemma set_integral_mono_on_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := by { refine set_integral_mono_ae_restrict hf hg _, rwa [eventually_le, ae_restrict_iff' hs], } omit hf hg lemma set_integral_mono (h : f ≤ g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := integral_mono hf hg h lemma set_integral_mono_set (hfi : integrable f μ) (hf : 0 ≤ᵐ[μ] f) (hst : s ≤ᵐ[μ] t) : ∫ x in s, f x ∂μ ≤ ∫ x in t, f x ∂μ := begin repeat { rw integral_eq_lintegral_of_nonneg_ae (ae_restrict_of_ae hf) (hfi.1.mono_measure measure.restrict_le_self) }, rw ennreal.to_real_le_to_real (ne_of_lt $ (has_finite_integral_iff_of_real (ae_restrict_of_ae hf)).mp hfi.integrable_on.2) (ne_of_lt $ (has_finite_integral_iff_of_real (ae_restrict_of_ae hf)).mp hfi.integrable_on.2), exact (lintegral_mono_set' hst), end end mono section nonneg variables {μ : measure α} {f : α → ℝ} {s : set α} lemma set_integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict s] f) : 0 ≤ ∫ a in s, f a ∂μ := integral_nonneg_of_ae hf lemma set_integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict (ae_restrict_of_ae hf) lemma set_integral_nonneg (hs : measurable_set s) (hf : ∀ a, a ∈ s → 0 ≤ f a) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf)) lemma set_integral_nonneg_ae (hs : measurable_set s) (hf : ∀ᵐ a ∂μ, a ∈ s → 0 ≤ f a) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict $ by rwa [eventually_le, ae_restrict_iff' hs] lemma set_integral_le_nonneg {s : set α} (hs : measurable_set s) (hf : measurable f) (hfi : integrable f μ) : ∫ x in s, f x ∂μ ≤ ∫ x in {y | 0 ≤ f y}, f x ∂μ := begin rw [← integral_indicator hs, ← integral_indicator (measurable_set_le measurable_const hf)], exact integral_mono (hfi.indicator hs) (hfi.indicator (measurable_set_le measurable_const hf)) (indicator_le_indicator_nonneg s f), end lemma set_integral_nonpos_of_ae_restrict (hf : f ≤ᵐ[μ.restrict s] 0) : ∫ a in s, f a ∂μ ≤ 0 := integral_nonpos_of_ae hf lemma set_integral_nonpos_of_ae (hf : f ≤ᵐ[μ] 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict (ae_restrict_of_ae hf) lemma set_integral_nonpos (hs : measurable_set s) (hf : ∀ a, a ∈ s → f a ≤ 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf)) lemma set_integral_nonpos_ae (hs : measurable_set s) (hf : ∀ᵐ a ∂μ, a ∈ s → f a ≤ 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict $ by rwa [eventually_le, ae_restrict_iff' hs] lemma set_integral_nonpos_le {s : set α} (hs : measurable_set s) {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) : ∫ x in {y | f y ≤ 0}, f x ∂μ ≤ ∫ x in s, f x ∂μ := begin rw [← integral_indicator hs, ← integral_indicator (measurable_set_le hf measurable_const)], exact integral_mono (hfi.indicator (measurable_set_le hf measurable_const)) (hfi.indicator hs) (indicator_nonpos_le_indicator s f), end end nonneg section tendsto_mono variables {μ : measure α} [measurable_space E] [normed_group E] [borel_space E] [complete_space E] [normed_space ℝ E] [second_countable_topology E] {s : ℕ → set α} {f : α → E} lemma _root_.antitone.tendsto_set_integral (hsm : ∀ i, measurable_set (s i)) (h_anti : antitone s) (hfi : integrable_on f (s 0) μ) : tendsto (λi, ∫ a in s i, f a ∂μ) at_top (𝓝 (∫ a in (⋂ n, s n), f a ∂μ)) := begin let bound : α → ℝ := indicator (s 0) (λ a, ∥f a∥), have h_int_eq : (λ i, ∫ a in s i, f a ∂μ) = (λ i, ∫ a, (s i).indicator f a ∂μ), from funext (λ i, (integral_indicator (hsm i)).symm), rw h_int_eq, rw ← integral_indicator (measurable_set.Inter hsm), refine tendsto_integral_of_dominated_convergence bound _ _ _ _ _, { intro n, rw ae_measurable_indicator_iff (hsm n), exact (integrable_on.mono_set hfi (h_anti (zero_le n))).1 }, { rw ae_measurable_indicator_iff (measurable_set.Inter hsm), exact (integrable_on.mono_set hfi (set.Inter_subset s 0)).1, }, { rw integrable_indicator_iff (hsm 0), exact hfi.norm, }, { simp_rw norm_indicator_eq_indicator_norm, refine λ n, eventually_of_forall (λ x, _), exact indicator_le_indicator_of_subset (h_anti (zero_le n)) (λ a, norm_nonneg _) _ }, { filter_upwards [] λ a, le_trans (h_anti.tendsto_indicator _ _ _) (pure_le_nhds _) } end end tendsto_mono /-! ### Continuity of the set integral We prove that for any set `s`, the function `λ f : α →₁[μ] E, ∫ x in s, f x ∂μ` is continuous. -/ section continuous_set_integral variables [normed_group E] [measurable_space E] [second_countable_topology E] [borel_space E] {𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [normed_group F] [measurable_space F] [second_countable_topology F] [borel_space F] [normed_space 𝕜 F] {p : ℝ≥0∞} {μ : measure α} /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is additive. -/ lemma Lp_to_Lp_restrict_add (f g : Lp E p μ) (s : set α) : ((Lp.mem_ℒp (f + g)).restrict s).to_Lp ⇑(f + g) = ((Lp.mem_ℒp f).restrict s).to_Lp f + ((Lp.mem_ℒp g).restrict s).to_Lp g := begin ext1, refine (ae_restrict_of_ae (Lp.coe_fn_add f g)).mp _, refine (Lp.coe_fn_add (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s)) (mem_ℒp.to_Lp g ((Lp.mem_ℒp g).restrict s))).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp g).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (f+g)).restrict s)).mono (λ x hx1 hx2 hx3 hx4 hx5, _), rw [hx4, hx1, pi.add_apply, hx2, hx3, hx5, pi.add_apply], end /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map commutes with scalar multiplication. -/ lemma Lp_to_Lp_restrict_smul [opens_measurable_space 𝕜] (c : 𝕜) (f : Lp F p μ) (s : set α) : ((Lp.mem_ℒp (c • f)).restrict s).to_Lp ⇑(c • f) = c • (((Lp.mem_ℒp f).restrict s).to_Lp f) := begin ext1, refine (ae_restrict_of_ae (Lp.coe_fn_smul c f)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (c • f)).restrict s)).mp _, refine (Lp.coe_fn_smul c (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s))).mono (λ x hx1 hx2 hx3 hx4, _), rw [hx2, hx1, pi.smul_apply, hx3, hx4, pi.smul_apply], end /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is non-expansive. -/ lemma norm_Lp_to_Lp_restrict_le (s : set α) (f : Lp E p μ) : ∥((Lp.mem_ℒp f).restrict s).to_Lp f∥ ≤ ∥f∥ := begin rw [Lp.norm_def, Lp.norm_def, ennreal.to_real_le_to_real (Lp.snorm_ne_top _) (Lp.snorm_ne_top _)], refine (le_of_eq _).trans (snorm_mono_measure _ measure.restrict_le_self), { exact s, }, exact snorm_congr_ae (mem_ℒp.coe_fn_to_Lp _), end variables (α F 𝕜) /-- Continuous linear map sending a function of `Lp F p μ` to the same function in `Lp F p (μ.restrict s)`. -/ def Lp_to_Lp_restrict_clm [borel_space 𝕜] (μ : measure α) (p : ℝ≥0∞) [hp : fact (1 ≤ p)] (s : set α) : Lp F p μ →L[𝕜] Lp F p (μ.restrict s) := @linear_map.mk_continuous 𝕜 (Lp F p μ) (Lp F p (μ.restrict s)) _ _ _ _ _ ⟨λ f, mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s), λ f g, Lp_to_Lp_restrict_add f g s, λ c f, Lp_to_Lp_restrict_smul c f s⟩ 1 (by { intro f, rw one_mul, exact norm_Lp_to_Lp_restrict_le s f, }) variables {α F 𝕜} variables (𝕜) lemma Lp_to_Lp_restrict_clm_coe_fn [borel_space 𝕜] [hp : fact (1 ≤ p)] (s : set α) (f : Lp F p μ) : Lp_to_Lp_restrict_clm α F 𝕜 μ p s f =ᵐ[μ.restrict s] f := mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s) variables {𝕜} @[continuity] lemma continuous_set_integral [normed_space ℝ E] [complete_space E] (s : set α) : continuous (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ) := begin haveI : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩, have h_comp : (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ) = (integral (μ.restrict s)) ∘ (λ f, Lp_to_Lp_restrict_clm α E ℝ μ 1 s f), { ext1 f, rw [function.comp_apply, integral_congr_ae (Lp_to_Lp_restrict_clm_coe_fn ℝ s f)], }, rw h_comp, exact continuous_integral.comp (Lp_to_Lp_restrict_clm α E ℝ μ 1 s).continuous, end end continuous_set_integral end measure_theory open measure_theory asymptotics metric variables {ι : Type*} [measurable_space E] [normed_group E] /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.lift' powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma filter.tendsto.integral_sub_linear_is_o_ae [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} {l : filter α} [l.is_measurably_generated] {f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b)) (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {s : ι → set α} {li : filter ι} (hs : tendsto s li (l.lift' powerset)) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : is_o (λ i, ∫ x in s i, f x ∂μ - m i • b) m li := begin suffices : is_o (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • b) (λ s, (μ s).to_real) (l.lift' powerset), from (this.comp_tendsto hs).congr' (hsμ.mono $ λ a ha, ha ▸ rfl) hsμ, refine is_o_iff.2 (λ ε ε₀, _), have : ∀ᶠ s in l.lift' powerset, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε := eventually_lift'_powerset_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀), filter_upwards [hμ.eventually, (hμ.integrable_at_filter_of_tendsto_ae hfm h).eventually, hfm.eventually, this], simp only [mem_closed_ball, dist_eq_norm], intros s hμs h_integrable hfm h_norm, rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs), real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub ae_measurable_const) end /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a` within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li` provided that `s i` tends to `(𝓝[t] a).lift' powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_within_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (ha : continuous_within_at f t a) (ht : measurable_set t) (hfm : measurable_at_filter f (𝓝[t] a) μ) {s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝[t] a).lift' powerset)) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li := by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _; exact (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds_within a t) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).lift' powerset` along `li. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {f : α → E} (ha : continuous_at f a) (hfm : measurable_at_filter f (𝓝 a) μ) {s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝 a).lift' powerset)) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li := (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) hs m hsμ /-- If a function is continuous on an open set `s`, then it is measurable at the filter `𝓝 x` for all `x ∈ s`. -/ lemma continuous_on.measurable_at_filter [topological_space α] [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] {f : α → β} {s : set α} {μ : measure α} (hs : is_open s) (hf : continuous_on f s) : ∀ x ∈ s, measurable_at_filter f (𝓝 x) μ := λ x hx, ⟨s, is_open.mem_nhds hs hx, hf.ae_measurable hs.measurable_set⟩ lemma continuous_at.measurable_at_filter [topological_space α] [opens_measurable_space α] [borel_space E] {f : α → E} {s : set α} {μ : measure α} (hs : is_open s) (hf : ∀ x ∈ s, continuous_at f x) : ∀ x ∈ s, measurable_at_filter f (𝓝 x) μ := continuous_on.measurable_at_filter hs $ continuous_at.continuous_on hf lemma continuous.measurable_at_filter [topological_space α] [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] {f : α → β} (hf : continuous f) (μ : measure α) (l : filter α) : measurable_at_filter f l μ := hf.measurable.measurable_at_filter /-- If a function is continuous on a measurable set `s`, then it is measurable at the filter `𝓝[s] x` for all `x`. -/ lemma continuous_on.measurable_at_filter_nhds_within {α β : Type*} [measurable_space α] [topological_space α] [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) (x : α) : measurable_at_filter f (𝓝[s] x) μ := ⟨s, self_mem_nhds_within, hf.ae_measurable hs⟩ /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).lift' powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_on.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ha : a ∈ t) (ht : measurable_set t) {s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝[t] a).lift' powerset)) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li := (hft a ha).integral_sub_linear_is_o_ae ht ⟨t, self_mem_nhds_within, hft.ae_measurable ht⟩ hs m hsμ section /-! ### Continuous linear maps composed with integration The goal of this section is to prove that integration commutes with continuous linear maps. This holds for simple functions. The general result follows from the continuity of all involved operations on the space `L¹`. Note that composition by a continuous linear map on `L¹` is not just the composition, as we are dealing with classes of functions, but it has already been defined as `continuous_linear_map.comp_Lp`. We take advantage of this construction here. -/ open_locale complex_conjugate variables {μ : measure α} {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] {p : ennreal} local attribute [instance] fact_one_le_one_ennreal namespace continuous_linear_map variables [measurable_space F] [borel_space F] variables [second_countable_topology F] [complete_space F] [borel_space E] [second_countable_topology E] [normed_space ℝ F] lemma integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) : ∫ a, (L.comp_Lp φ) a ∂μ = ∫ a, L (φ a) ∂μ := integral_congr_ae $ coe_fn_comp_Lp _ _ lemma set_integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) {s : set α} (hs : measurable_set s) : ∫ a in s, (L.comp_Lp φ) a ∂μ = ∫ a in s, L (φ a) ∂μ := set_integral_congr_ae hs ((L.coe_fn_comp_Lp φ).mono (λ x hx hx2, hx)) lemma continuous_integral_comp_L1 [measurable_space 𝕜] [opens_measurable_space 𝕜] (L : E →L[𝕜] F) : continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) := by { rw ← funext L.integral_comp_Lp, exact continuous_integral.comp (L.comp_LpL 1 μ).continuous, } variables [complete_space E] [measurable_space 𝕜] [opens_measurable_space 𝕜] [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] [is_scalar_tower ℝ 𝕜 F] lemma integral_comp_comm (L : E →L[𝕜] F) {φ : α → E} (φ_int : integrable φ μ) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)), { intros e s s_meas s_finite, rw [integral_indicator_const e s_meas, ← @smul_one_smul E ℝ 𝕜 _ _ _ _ _ (μ s).to_real e, continuous_linear_map.map_smul, @smul_one_smul F ℝ 𝕜 _ _ _ _ _ (μ s).to_real (L e), ← integral_indicator_const (L e) s_meas], congr' 1 with a, rw set.indicator_comp_of_zero L.map_zero }, { intros f g H f_int g_int hf hg, simp [L.map_add, integral_add f_int g_int, integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] }, { exact is_closed_eq L.continuous_integral_comp_L1 (L.continuous.comp continuous_integral) }, { intros f g hfg f_int hf, convert hf using 1 ; clear hf, { exact integral_congr_ae (hfg.fun_comp L).symm }, { rw integral_congr_ae hfg.symm } }, all_goals { assumption } end lemma integral_apply {H : Type*} [normed_group H] [normed_space ℝ H] [second_countable_topology $ H →L[ℝ] E] {φ : α → H →L[ℝ] E} (φ_int : integrable φ μ) (v : H) : (∫ a, φ a ∂μ) v = ∫ a, φ a v ∂μ := ((continuous_linear_map.apply ℝ E v).integral_comp_comm φ_int).symm lemma integral_comp_comm' (L : E →L[𝕜] F) {K} (hL : antilipschitz_with K L) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin by_cases h : integrable φ μ, { exact integral_comp_comm L h }, have : ¬ (integrable (L ∘ φ) μ), by rwa lipschitz_with.integrable_comp_iff_of_antilipschitz L.lipschitz hL (L.map_zero), simp [integral_undef, h, this] end lemma integral_comp_L1_comm (L : E →L[𝕜] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.integral_comp_comm (L1.integrable_coe_fn φ) end continuous_linear_map namespace linear_isometry variables [measurable_space F] [borel_space F] [second_countable_topology F] [complete_space F] [normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F] [borel_space E] [second_countable_topology E] [complete_space E] [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma integral_comp_comm (L : E →ₗᵢ[𝕜] F) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.to_continuous_linear_map.integral_comp_comm' L.antilipschitz _ end linear_isometry variables [borel_space E] [second_countable_topology E] [complete_space E] [normed_space ℝ E] [measurable_space F] [borel_space F] [second_countable_topology F] [complete_space F] [normed_space ℝ F] [measurable_space 𝕜] [borel_space 𝕜] @[norm_cast] lemma integral_of_real {f : α → ℝ} : ∫ a, (f a : 𝕜) ∂μ = ↑∫ a, f a ∂μ := (@is_R_or_C.of_real_li 𝕜 _).integral_comp_comm f lemma integral_re {f : α → 𝕜} (hf : integrable f μ) : ∫ a, is_R_or_C.re (f a) ∂μ = is_R_or_C.re ∫ a, f a ∂μ := (@is_R_or_C.re_clm 𝕜 _).integral_comp_comm hf lemma integral_im {f : α → 𝕜} (hf : integrable f μ) : ∫ a, is_R_or_C.im (f a) ∂μ = is_R_or_C.im ∫ a, f a ∂μ := (@is_R_or_C.im_clm 𝕜 _).integral_comp_comm hf lemma integral_conj {f : α → 𝕜} : ∫ a, conj (f a) ∂μ = conj ∫ a, f a ∂μ := (@is_R_or_C.conj_lie 𝕜 _).to_linear_isometry.integral_comp_comm f lemma integral_coe_re_add_coe_im {f : α → 𝕜} (hf : integrable f μ) : ∫ x, (is_R_or_C.re (f x) : 𝕜) ∂μ + ∫ x, is_R_or_C.im (f x) ∂μ * is_R_or_C.I = ∫ x, f x ∂μ := begin rw [mul_comm, ← smul_eq_mul, ← integral_smul, ← integral_add], { congr, ext1 x, rw [smul_eq_mul, mul_comm, is_R_or_C.re_add_im] }, { exact hf.re.of_real }, { exact hf.im.of_real.smul is_R_or_C.I } end lemma integral_re_add_im {f : α → 𝕜} (hf : integrable f μ) : ((∫ x, is_R_or_C.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x, is_R_or_C.im (f x) ∂μ : ℝ) * is_R_or_C.I = ∫ x, f x ∂μ := by { rw [← integral_of_real, ← integral_of_real, integral_coe_re_add_coe_im hf] } lemma set_integral_re_add_im {f : α → 𝕜} {i : set α} (hf : integrable_on f i μ) : ((∫ x in i, is_R_or_C.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x in i, is_R_or_C.im (f x) ∂μ : ℝ) * is_R_or_C.I = ∫ x in i, f x ∂μ := integral_re_add_im hf lemma fst_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ := ((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm lemma snd_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ := ((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) : ∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) := have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this) lemma integral_smul_const (f : α → ℝ) (c : E) : ∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c := begin by_cases hf : integrable f μ, { exact ((continuous_linear_map.id ℝ ℝ).smul_right c).integral_comp_comm hf }, { by_cases hc : c = 0, { simp only [hc, integral_zero, smul_zero] }, rw [integral_undef hf, integral_undef, zero_smul], simp_rw [integrable_smul_const hc, hf, not_false_iff] } end section inner variables {E' : Type*} [inner_product_space 𝕜 E'] [measurable_space E'] [borel_space E'] [second_countable_topology E'] [complete_space E'] [normed_space ℝ E'] [is_scalar_tower ℝ 𝕜 E'] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E' _ x y lemma integral_inner {f : α → E'} (hf : integrable f μ) (c : E') : ∫ x, ⟪c, f x⟫ ∂μ = ⟪c, ∫ x, f x ∂μ⟫ := ((@inner_right 𝕜 E' _ _ c).restrict_scalars ℝ).integral_comp_comm hf lemma integral_eq_zero_of_forall_integral_inner_eq_zero (f : α → E') (hf : integrable f μ) (hf_int : ∀ (c : E'), ∫ x, ⟪c, f x⟫ ∂μ = 0) : ∫ x, f x ∂μ = 0 := by { specialize hf_int (∫ x, f x ∂μ), rwa [integral_inner hf, inner_self_eq_zero] at hf_int } end inner end
e350d72ecad9fff9f56b2bfc43f68c59b86c122d
7da5ceac20aaab989eeb795a4be9639982e7b35a
/src/tactic/depends.lean
3e0ed12e4cf3a02cfab9145b44a99d1f8a70257c
[ "MIT" ]
permissive
formalabstracts/formalabstracts
46c2f1b3a172e62ca6ffeb46fbbdf1705718af49
b0173da1af45421239d44492eeecd54bf65ee0f6
refs/heads/master
1,606,896,370,374
1,572,988,776,000
1,572,988,776,000
96,763,004
165
28
null
1,555,709,319,000
1,499,680,948,000
Lean
UTF-8
Lean
false
false
3,984
lean
/- Copyright (c) 2019 Koundinya Vajjha. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Koundinya Vajjha A meta def called `#depends` which gives the names of all the theorems (the statement of) a given definition/theorem depends on. -/ import data.pfun open tactic expr interactive nat native name list lean.parser environment /--Takes an expr and spits out a list of all the names in that expr -/ meta def list_names (e : expr): list name := e.fold [] (λ e _ es, if is_constant e then insert e.const_name es else es) /-- Takes an environment and naively lists all declarations in it.-/ meta def list_all_decls (env : environment) : list name := env.fold [] $ (λ d ns, d.to_name :: ns) /-- Takes an environment and lists all declarations in it, much faster. -/ meta def list_all_decls' (env : environment) : rb_set name := env.fold (mk_rb_set) $ (λ d ns, ns.insert d.to_name) /-- Traces all declarations with prefix `namesp` in the current environment. -/ /-TODO : optimize using rb_set filters and maps(?)-/ meta def trace_all_decls (namesp : name) : tactic unit := do e ← get_env, let l := list_all_decls' e, let k := l.to_list, let m := list.map (λ h:name, h.get_prefix) k, let f := k.filter (λ h, is_prefix_of namesp h), tactic.trace $ take 150 f, skip /- TODO : modify this to take structures into account -/ @[user_command] meta def depends_cmd (meta_info : decl_meta_info) ( _ : parse $ tk "#depends") : lean.parser unit := do given_name ← ident, resolved ← resolve_constant given_name, d ← get_decl resolved <|> fail ("declaration " ++ to_string given_name ++ " not found"), tactic.trace $ list_names d.type /-- Return the direct dependencies of the *type* of a declaration. -/ meta def name_dir_deps (n : name) : tactic(list name) := do env ← get_env, l ← get_decl n, if is_structure env n then do fields ← returnopt $ structure_fields env n, let res := map (λ h, name.append n h) fields, k ← mmap (λ h, do l ← get_decl h, pure $ list_names l.type) res, let clean := list.erase_dup (list.join k), let final := list.filter (λ h, ¬ name.is_prefix_of n h) clean, pure $ final else pure $ list_names l.type /-- Return the direct dependencies of the *value* of a declaration.-/ meta def name_dir_deps_val (n : name) : tactic(list name) := do env ← get_env, l ← get_decl n, if is_structure env n then do fields ← returnopt $ structure_fields env n, let res := map (λ h, name.append n h) fields, k ← mmap (λ h, do l ← get_decl h, pure $ list_names l.value) res, let clean := list.erase_dup (list.join k), let final := list.filter (λ h, ¬ name.is_prefix_of n h) clean, pure $ final else pure $ list_names l.value /-- Recursively return a joint list of the m-th sub-dependencies of the type of given name.-/ meta def name_dir_deps_depth (n : name) : ℕ → tactic(list name) | 0 := name_dir_deps n | (succ m) := do l ← name_dir_deps_depth m <|> name_dir_deps n, l' ← mmap (λ h, name_dir_deps h) l, let k := list.erase_dup $ list.join (l :: l'), -- tactic.trace k.length, pure $ k /-- Recursively return a joint list of the m-th sub-dependencies of the type of given name.-/ meta def name_dir_deps_depth_val (n : name) : ℕ → tactic(list name) | 0 := name_dir_deps_val n | (succ m) := do l ← name_dir_deps_depth_val m <|> name_dir_deps_val n, l' ← mmap (λ h, name_dir_deps h) l, let k := list.erase_dup $ list.join (l :: l'), -- tactic.trace k.length, pure $ k theorem foo' : 2+2 = 4 := begin simp, end /- Tests -/ -- #depends nat.has_one -- #depends group.equiv -- #depends J4 -- #depends nat.add._main -- #depends mclaughlin.McL -- #depends sends_identity_to_1 -- set_option profiler true -- run_cmd (name_dir_deps_depth_val `mathieu_group.Aut 10) >>= tactic.trace
6ca77d302289d32ff4246c8f6d97a8d8818d521d
ac2987d8c7832fb4a87edb6bee26141facbb6fa0
/Mathlib/Tactic/Spread.lean
8d07aa335169055ae5588bba40f661539552763d
[ "Apache-2.0" ]
permissive
AurelienSaue/mathlib4
52204b9bd9d207c922fe0cf3397166728bb6c2e2
84271fe0875bafdaa88ac41f1b5a7c18151bd0d5
refs/heads/master
1,689,156,096,545
1,629,378,840,000
1,629,378,840,000
389,648,603
0
0
Apache-2.0
1,627,307,284,000
1,627,307,284,000
null
UTF-8
Lean
false
false
1,119
lean
/- Copyright (c) 2021 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import Lean open Lean Parser.Term Macro /- This adds support for structure instance spread syntax. ```lean instance : Foo α where __ := instSomething -- include fields from `instSomething` example : Foo α := { __ := instSomething -- include fields from `instSomething` } ``` -/ macro_rules | `({ $[$srcs,* with]? $[$fields $[,]?]* $[: $ty?]? }) => do let mut spreads := #[] let mut newFields := #[] for field in fields do match field with | `(structInstField| $name:ident := $arg) => if name.getId.eraseMacroScopes == `__ then do spreads := spreads.push arg else newFields := newFields.push field | `(structInstFieldAbbrev| $name:ident) => newFields := newFields.push field | _ => throwUnsupported if spreads.isEmpty then throwUnsupported let srcs := (srcs.map (·.1)).getD #[] ++ spreads `({ $srcs,* with $[$newFields,]* $[: $ty?]? })
d056fc26c8c99720b132d0aefdf6d7a591d7b62c
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/examples/quotient_group.lean
cbdecf1284ddda117ec934412e2c251a26eb5416
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
2,176
lean
import group_theory.coset data.equiv data.quot import tidy.tidy open set function section quotient_group variable {α : Type*} -- Some instances allowing us to use quotient notation local attribute [instance] left_rel normal_subgroup.to_is_subgroup -- We now prove two lemmas about elements in normal subgroups. I haven't attempted any automation here. lemma quotient_group_aux [group α] (s : set α) [normal_subgroup s] (a b : α) (h : a⁻¹ * b ∈ s) : a * b⁻¹ ∈ s := begin rw [← inv_inv a, ← mul_inv_rev], exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm h), end lemma quotient_group_aux' [group α] (s : set α) [normal_subgroup s] (a b c d : α) (h₁ : a * b ∈ s) (h₂ : c * d ∈ s) : c * (a * (b * d)) ∈ s := begin apply is_subgroup.mem_norm_comm, rw [← mul_assoc, mul_assoc], apply (is_subgroup.mul_mem_cancel_right s h₁).2, exact is_subgroup.mem_norm_comm h₂ end lemma quotient_group_aux'' [group α] (s : set α) [normal_subgroup s] (a b c d : α) (h₁ : a * b ∈ s) (h₂ : c * d ∈ s) : c * a * (b * d) ∈ s := begin sorry end -- PROJECT one could write a tactic proving "all such" lemmas as above: -- Given a word in α, write it as a vector in ℤ^α, and similarly write any hypotheses. -- Now use Smith normal form (or perhaps Hermite normal form) to determine if there are solutions to the corresponding integer Diophantine equation. -- Some 'hint' attributes for obviously. local attribute [reducible] setoid_has_equiv left_rel local attribute [applicable] is_submonoid.one_mem -- `applicable` means the lemma should be applied whenever relevant local attribute [semiapplicable] quotient_group_aux quotient_group_aux' quotient_group_aux'' -- `semiapplicable` means the lemma should be applied if all its hypotheses can be satisfied from the context local attribute [simp] mul_assoc instance quotient_group' [group α] (s : set α) [normal_subgroup s] : group (left_cosets s) := by refine { one := ⟦1⟧, mul := λ a b, quotient.lift_on₂ a b (λ a b, ⟦a * b⟧) (by obviously), inv := λ a', quotient.lift_on a' (λ a, ⟦a⁻¹⟧) (by obviously), .. }; obviously end quotient_group
ad853f1718bb6dc7d638afcde0d5faa73a1f24c8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/random.lean
756e5e3c062c84871038db3398b0bf973e0f50e0
[ "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,348
lean
import control.random import data.nat.prime import data.zmod.basic /-- fermat's primality test -/ def primality_test (p : ℕ) : rand bool := if h : 2 ≤ p-1 then do n ← rand.random_r 2 (p-1) h, -- we do arithmetic with `zmod n` so that modulo and multiplication are interleaved return $ (n : zmod p)^(p-1) = 1 else return (p = 2) /-- `iterated_primality_test_aux p h n` generating `n` candidate witnesses that `p` is a composite number and concludes that `p` is prime if none of them is a valid witness -/ def iterated_primality_test_aux (p : ℕ) : ℕ → rand bool | 0 := pure tt | (n+1) := do b ← primality_test p, if b then iterated_primality_test_aux n else pure ff def iterated_primality_test (p : ℕ) : rand bool := iterated_primality_test_aux p 10 /-- `find_prime_aux p h n` generates a candidate prime number, tests it as well as the 19 odd numbers following it. If none of them is (probably) prime, try again `n-1` times. -/ def find_prime_aux (p : ℕ) (h : 1 ≤ p / 2) : ℕ → rand (option ℕ) | 0 := pure none | (n+1) := do k ← rand.random_r 1 (p / 2) h, let xs := (list.range' k 20).map (λ i, 2*i+1), some r ← option_t.run $ xs.mfirst (λ n, option_t.mk $ mcond (iterated_primality_test n) (pure (some n)) (pure none)) | find_prime_aux n, pure r def find_prime (p : ℕ) : rand (option ℕ) := if h : 1 ≤ p / 2 then find_prime_aux p h 20 else pure none open tactic /- `ps` should be `[97, 101, 103, 107, 109, 113]` but it uses a pseudo primality test and some composite numbers also sneak in -/ run_cmd do let xs := list.range' 90 30, ps ← tactic.run_rand (xs.mfilter iterated_primality_test), when (ps ≠ [97, 101, 103, 107, 109, 113]) (trace!"The random primality test also included some composite numbers: {ps}") /- `ps` should be `[97, 101, 103, 107, 109, 113]`. This test is deterministic because we pick the random seed -/ run_cmd do let xs := list.range' 90 30, let ps : list ℕ := (xs.mfilter iterated_primality_test).eval ⟨ mk_std_gen 10 ⟩, guard (ps = [97, 101, 103, 107, 109, 113]) <|> fail "wrong list of prime numbers" /- this finds a random probably-prime number -/ run_cmd do some p ← tactic.run_rand (find_prime 100000) | trace "no prime found, gave up", when (¬ nat.prime p) (trace!"The number {p} fooled Fermat's test")
b98b21c53815a6c7d8f067cc22a4a733070abdad
618003631150032a5676f229d13a079ac875ff77
/test/linarith.lean
8b5dc8a3ad9d18e20838549e9ca133dff4d6582b
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
4,553
lean
import tactic.linarith example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) : v0 + 5 + (v1 - 3) + (c - 2) = 10 := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε := by linarith example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0) (h3 : 12*y - z < 0) : false := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε := by linarith example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith {discharger := `[ring SOP]} example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false := by linarith {restrict_type := ℚ} example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0) (h5 : 0 ≤ c) (h6 : c < 1) : v ≤ V := by linarith example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z)) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) : ¬ 12*y - 4* z < 0 := by linarith example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0) (h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false := by linarith example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10) (h4 : a + b - c < 3) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false := by linarith example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 := by linarith {exfalso := ff} example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false := by linarith [rat.num_pos_iff_pos.mpr hx, h] example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false := by linarith only [rat.num_pos_iff_pos.mpr hx, h] example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (h1 : (1 : ℕ) < 1) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 := by linarith example (a b c : ℕ) : a + b ≥ a := by linarith example (a b c : ℕ) : ¬ a + b < a := by linarith example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0) (h'' : (6 + 3 * y) * y ≥ 0) : false := by linarith example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3 ∧ (x + 4) * x ≥ 0 ∧ (6 + 3 * y) * y ≥ 0) : false := by linarith example (x y : ℕ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) : false := by linarith example (a b i : ℕ) (h1 : ¬ a < i) (h2 : b < i) (h3 : a ≤ b) : false := by linarith example (n : ℕ) (h1 : n ≤ 3) (h2 : n > 2) : n = 3 := by linarith example (z : ℕ) (hz : ¬ z ≥ 2) (h2 : ¬ z + 1 ≤ 2) : false := by linarith example (z : ℕ) (hz : ¬ z ≥ 2) : z + 1 ≤ 2 := by linarith example (a b c : ℚ) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c := by linarith example (N : ℕ) (n : ℕ) (Hirrelevant : n > N) (A : ℚ) (l : ℚ) (h : A - l ≤ -(A - l)) (h_1 : ¬A ≤ -A) (h_2 : ¬l ≤ -l) (h_3 : -(A - l) < 1) : A < l + 1 := by linarith example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : d ≤ ((q : ℚ) - 1)*n := by linarith example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : ((q : ℚ) - 1)*n - d = 1/3 * (((q : ℚ) - 1)*n) := by linarith example (a : ℚ) (ha : 0 ≤ a) : 0 * 0 ≤ 2 * a := by linarith example (x : ℚ) : id x ≥ x := by success_if_fail {linarith}; linarith! example (x y z : ℚ) (hx : x < 5) (hx2 : x > 5) (hy : y < 5000000000) (hz : z > 34*y) : false := by linarith only [hx, hx2] example (x y z : ℚ) (hx : x < 5) (hy : y < 5000000000) (hz : z > 34*y) : x ≤ 5 := by linarith only [hx] example (x y : ℚ) (h : x < y) : x ≠ y := by linarith example (x y : ℚ) (h : x < y) : ¬ x = y := by linarith
5d03ddf65f3189bcbc9e25d04e2e30ef2f3b0fed
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/data/nat/bquant.lean
c8147612911a8e8d28b9d79f6e20b20fd5bc8393
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
2,375
lean
import .sub open nat def ball (n : nat) (P : nat → Prop) := ∀ k : ℕ, k < n → P k def ball' (n : nat) (P : Π (k : ℕ) (p : k < n), Prop) := Π (k : ℕ) (p : k < n), P k p theorem ball_zero (P : nat → Prop) : ball 0 P := λ x Hlt, absurd Hlt (not_lt_zero _) theorem ball_zero' (P : Π (k : ℕ) (p : k < 0), Prop) : ball' 0 P := λ k p, absurd p (not_lt_zero _) theorem ball_of_ball_succ {n : nat} {P : nat → Prop} (H : ball (succ n) P) : ball n P := λ x Hlt, H x (lt.step Hlt) def step_p {n : ℕ} (P : Π (k : ℕ) (p : k < succ n), Prop) : Π (k : ℕ) (p : k < n), Prop := λ k p, P k (lt.step p) theorem ball_of_ball_succ' {n : nat} {P : Π (k : ℕ) (p : k < succ n), Prop} (H : ball' (succ n) P) : ball' n (step_p P) := λ x Hlt, H _ _ theorem ball_succ_of_ball {n : nat} {P : nat → Prop} (H₁ : ball n P) (H₂ : P n) : ball (succ n) P := λ (x : nat) (Hlt : x < succ n), or.elim (nat.eq_or_lt_of_le (le_of_succ_le_succ Hlt)) (λ heq : x = n, (eq.symm heq) ▸ H₂) (λ hlt : x < n, H₁ x hlt) theorem not_ball_of_not {n : nat} {P : nat → Prop} (H₁ : ¬ P n) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (H n (lt.base n)) H₁ theorem not_ball_succ_of_not_ball {n : nat} {P : nat → Prop} (H₁ : ¬ ball n P) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (ball_of_ball_succ H) H₁ instance decidable_ball (n : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (ball n P) := nat.rec_on n (decidable.is_true (ball_zero P)) (λ n₁ ih, decidable.rec_on ih (λ ih_neg, decidable.is_false (not_ball_succ_of_not_ball ih_neg)) (λ ih_pos, decidable.rec_on (H n₁) (λ p_neg, decidable.is_false (not_ball_of_not p_neg)) (λ p_pos, decidable.is_true (ball_succ_of_ball ih_pos p_pos)))) instance decidable_lo_hi (lo hi : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := suffices ball (hi - lo) (λx, P (lo + x)) ↔ (∀x, lo ≤ x → x < hi → P x), from decidable_of_decidable_of_iff (by apply_instance) this, ⟨λ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 _ _) (by rw add_comm; exact nat.add_lt_of_lt_sub h)⟩
5f549359995791b41b24647f6deb4eaf0e6032eb
7282d49021d38dacd06c4ce45a48d09627687fe0
/tests/lean/using_bug1.lean
0005259190304dc9276748650d4cf72b45fd0062
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
408
lean
variables a b c d : Nat axiom H : a + (b + c) = a + (b + d) set_option pp::implicit true using Nat check add_succr a theorem mul_zerol2 (a : Nat) : 0 * a = 0 := induction_on a (have 0 * 0 = 0 : trivial) (λ (n : Nat) (iH : 0 * n = 0), calc 0 * (n + 1) = (0 * n) + 0 : mul_succr 0 n ... = 0 + 0 : { iH } ... = 0 : trivial)
f4605de39349bd069507f679f3617c5836087bc7
63abd62053d479eae5abf4951554e1064a4c45b4
/archive/imo/imo1969_q1.lean
d2298fa22500b1c4df66989cad9f992e03d1e2b1
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
2,193
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 tactic.linarith import tactic.norm_cast import tactic.ring open int open nat /-! # IMO 1969 Q1 Prove that there are infinitely many natural numbers $a$ with the following property: the number $z = n^4 + a$ is not prime for any natural number $n$. The key to the solution is that you can factor z into the product of two polynomials, if a = 4*m^4. -/ lemma factorization (m n : ℤ) : ((m - n)^2 + m^2) * ((m + n)^2 + m^2) = n^4 + 4*m^4 := by ring /-! To show that the product is not prime, we need to show each of the factors is at least 2, which nlinarith can solve since they are expressed as a sum of squares. -/ lemma left_factor_large (m n : ℤ) (h: 1 < m) : 1 < ((m - n)^2 + m^2) := by nlinarith lemma right_factor_large (m n : ℤ) (h: 1 < m) : 1 < ((m + n)^2 + m^2) := by nlinarith /-! The factorization is over the integers, but we need the nonprimality over the natural numbers. -/ lemma int_large (a : ℤ) (h : 1 < a) : 1 < a.nat_abs := by exact_mod_cast lt_of_lt_of_le h le_nat_abs lemma int_not_prime (a b : ℤ) (c : ℕ) (h1 : 1 < a) (h2 : 1 < b) (h3 : a*b = ↑c) : ¬ prime c := have h4 : (a*b).nat_abs = a.nat_abs * b.nat_abs, from nat_abs_mul a b, have h5 : a.nat_abs * b.nat_abs = c, by finish, norm_num.not_prime_helper a.nat_abs b.nat_abs c h5 (int_large a h1) (int_large b h2) lemma polynomial_not_prime (m n : ℕ) (h1 : 1 < m) : ¬ prime (n^4 + 4*m^4) := have h2 : 1 < of_nat m, from coe_nat_lt.mpr h1, begin refine int_not_prime _ _ _ (left_factor_large ↑m ↑n h2) (right_factor_large ↑m ↑n h2) _, rw factorization, norm_cast end /-! Now we just need to show this works for an arbitrarily large $a$, to prove there are infinitely many of them. $a = 4*(2+b)^4$ should do. So $m = 2+b$. -/ theorem imo1969_q1 : ∀ b : ℕ, ∃ a : ℕ, a ≥ b ∧ ∀ n : ℕ, ¬ prime (n^4 + a) := assume b, have h1 : 1 < 2+b, by linarith, have b^2 ≥ b, by nlinarith, have h2 : 4*(2+b)^4 ≥ b, by nlinarith, begin use [4*(2+b)^4, h2], assume n, exact polynomial_not_prime (2+b) n h1 end
51c4a973c3db549295810ba4903e030f55f1641e
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/erased.lean
5e83d8ec3cd9e8bbc4bcce6fcec03b614c1f295e
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
2,123
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A type for VM-erased data. -/ import data.equiv.basic /-- `erased α` is the same as `α`, except that the elements of `erased α` are erased in the VM in the same way as types and proofs. This can be used to track data without storing it literally. -/ def erased (α : Sort*) : Sort* := Σ' s : α → Prop, ∃ a, (λ b, a = b) = s namespace erased @[inline] def mk {α} (a : α) : erased α := ⟨λ b, a = b, a, rfl⟩ noncomputable def out {α} : erased α → α | ⟨s, h⟩ := classical.some h @[reducible] def out_type (a : erased Sort*) : Sort* := out a theorem out_proof {p : Prop} (a : erased p) : p := out a @[simp] theorem out_mk {α} (a : α) : (mk a).out = a := begin let h, show classical.some h = a, have := classical.some_spec h, exact cast (congr_fun this a).symm rfl end @[simp] theorem mk_out {α} : ∀ (a : erased α), mk (out a) = a | ⟨s, h⟩ := by simp [mk]; congr; exact classical.some_spec h noncomputable def equiv (α) : erased α ≃ α := ⟨out, mk, mk_out, out_mk⟩ instance (α : Type*) : has_repr (erased α) := ⟨λ _, "erased"⟩ def choice {α} (h : nonempty α) : erased α := mk (classical.choice h) theorem nonempty_iff {α} : nonempty (erased α) ↔ nonempty α := ⟨λ ⟨a⟩, ⟨a.out⟩, λ ⟨a⟩, ⟨mk a⟩⟩ instance {α} [h : nonempty α] : nonempty (erased α) := erased.nonempty_iff.2 h instance {α} [h : inhabited α] : inhabited (erased α) := ⟨mk (default _)⟩ def bind {α β} (a : erased α) (f : α → erased β) : erased β := ⟨λ b, (f a.out).1 b, (f a.out).2⟩ @[simp] theorem bind_eq_out {α β} (a f) : @bind α β a f = f a.out := by delta bind bind._proof_1; cases f a.out; refl def join {α} (a : erased (erased α)) : erased α := bind a id @[simp] theorem join_eq_out {α} (a) : @join α a = a.out := bind_eq_out _ _ instance : monad erased := { pure := @mk, bind := @bind } instance : is_lawful_monad erased := by refine {..}; intros; simp end erased
da50c42580f9f4174fd9b1cc012d7d786de591ba
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/class7.lean
ef5a4ee385457197461f8ef3c4be0f2000ff2f41
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
467
lean
import logic open tactic inductive inh [class] (A : Type) : Type := intro : A -> inh A theorem inh_bool [instance] : inh Prop := inh.intro true set_option trace.class_instances true theorem inh_fun [instance] {A B : Type} [H : inh B] : inh (A → B) := inh.rec (λ b, inh.intro (λ a : A, b)) H theorem tst {A B : Type} (H : inh B) : inh (A → B → B) theorem T1 {A : Type} (a : A) : inh A := by repeat (apply @inh.intro | eassumption) theorem T2 : inh Prop
18b170ad208123e6410c0d42a9ce14723555fa73
3268ab3a126f0fef71459fbf170dc38efe5d0506
/algebra/direct_sum.hlean
d0b56de99822a2546a6ce363aacce7bb6a4d76bd
[ "Apache-2.0" ]
permissive
soraismus/Spectral
f043fed1a4e02ddfeba531769b2980eb817471f4
32512bf47db3a1b932856e7ed7c7830b1fc07ef0
refs/heads/master
1,585,628,705,579
1,538,609,948,000
1,538,609,974,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,612
hlean
/- Copyright (c) 2015 Floris van Doorn, Egbert Rijke, Favonia. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke, Favonia Constructions with groups -/ import .quotient_group .free_abelian_group .product_group open eq is_equiv algebra is_trunc set_quotient relation sigma prod sum list trunc function equiv sigma.ops lift namespace group section parameters {I : Type} [is_set I] (Y : I → AbGroup) variables {A' : AbGroup} {Y' : I → AbGroup} definition dirsum_carrier : AbGroup := free_ab_group (Σi, Y i) local abbreviation ι [constructor] := @free_ab_group_inclusion inductive dirsum_rel : dirsum_carrier → Type := | rmk : Πi y₁ y₂, dirsum_rel (ι ⟨i, y₁⟩ * ι ⟨i, y₂⟩ * (ι ⟨i, y₁ * y₂⟩)⁻¹) definition dirsum : AbGroup := quotient_ab_group_gen dirsum_carrier (λg, ∥dirsum_rel g∥) -- definition dirsum_carrier_incl [constructor] (i : I) : Y i →g dirsum_carrier := definition dirsum_incl [constructor] (i : I) : Y i →g dirsum := homomorphism.mk (λy, class_of (ι ⟨i, y⟩)) begin intro g h, symmetry, apply gqg_eq_of_rel, apply tr, apply dirsum_rel.rmk end parameter {Y} definition dirsum.rec {P : dirsum → Type} [H : Πg, is_prop (P g)] (h₁ : Πi (y : Y i), P (dirsum_incl i y)) (h₂ : P 1) (h₃ : Πg h, P g → P h → P (g * h)) : Πg, P g := begin refine @set_quotient.rec_prop _ _ _ H _, refine @set_quotient.rec_prop _ _ _ (λx, !H) _, esimp, intro l, induction l with s l ih, exact h₂, induction s with v v, induction v with i y, exact h₃ _ _ (h₁ i y) ih, induction v with i y, refine h₃ (gqg_map _ _ (class_of [inr ⟨i, y⟩])) _ _ ih, refine transport P _ (h₁ i y⁻¹), refine _ ⬝ !one_mul, refine _ ⬝ ap (λx, mul x _) (to_respect_zero (dirsum_incl i)), apply gqg_eq_of_rel', apply tr, esimp, refine transport dirsum_rel _ (dirsum_rel.rmk i y⁻¹ y), rewrite [mul.left_inv, mul.assoc], end definition dirsum_homotopy {φ ψ : dirsum →g A'} (h : Πi (y : Y i), φ (dirsum_incl i y) = ψ (dirsum_incl i y)) : φ ~ ψ := begin refine dirsum.rec _ _ _, exact h, refine !to_respect_zero ⬝ !to_respect_zero⁻¹, intro g₁ g₂ h₁ h₂, rewrite [* to_respect_mul, h₁, h₂] end definition dirsum_elim_resp_quotient (f : Πi, Y i →g A') (g : dirsum_carrier) (r : ∥dirsum_rel g∥) : free_ab_group_elim (λv, f v.1 v.2) g = 1 := begin induction r with r, induction r, rewrite [to_respect_mul, to_respect_inv, to_respect_mul, ▸*, ↑foldl, *one_mul, to_respect_mul], apply mul.right_inv end definition dirsum_elim [constructor] (f : Πi, Y i →g A') : dirsum →g A' := gqg_elim _ (free_ab_group_elim (λv, f v.1 v.2)) (dirsum_elim_resp_quotient f) definition dirsum_elim_compute (f : Πi, Y i →g A') (i : I) (y : Y i) : dirsum_elim f (dirsum_incl i y) = f i y := begin apply one_mul end definition dirsum_elim_unique (f : Πi, Y i →g A') (k : dirsum →g A') (H : Πi, k ∘g dirsum_incl i ~ f i) : k ~ dirsum_elim f := begin apply gqg_elim_unique, apply free_ab_group_elim_unique, intro x, induction x with i y, exact H i y end end definition binary_dirsum (G H : AbGroup) : dirsum (bool.rec G H) ≃g G ×ag H := let branch := bool.rec G H in let to_hom := (dirsum_elim (bool.rec (product_inl G H) (product_inr G H)) : dirsum (bool.rec G H) →g G ×ag H) in let from_hom := (Group_sum_elim (dirsum (bool.rec G H)) (dirsum_incl branch bool.ff) (dirsum_incl branch bool.tt) : G ×g H →g dirsum branch) in begin fapply isomorphism.mk, { exact dirsum_elim (bool.rec (product_inl G H) (product_inr G H)) }, fapply adjointify, { exact from_hom }, { intro gh, induction gh with g h, exact prod_eq (mul_one (1 * g) ⬝ one_mul g) (ap (λ o, o * h) (mul_one 1) ⬝ one_mul h) }, { refine dirsum.rec _ _ _, { intro b x, refine ap from_hom (dirsum_elim_compute (bool.rec (product_inl G H) (product_inr G H)) b x) ⬝ _, induction b, { exact ap (λ y, dirsum_incl branch bool.ff x * y) (to_respect_one (dirsum_incl branch bool.tt)) ⬝ mul_one _ }, { exact ap (λ y, y * dirsum_incl branch bool.tt x) (to_respect_one (dirsum_incl branch bool.ff)) ⬝ one_mul _ } }, { refine ap from_hom (to_respect_one to_hom) ⬝ to_respect_one from_hom }, { intro g h gβ hβ, refine ap from_hom (to_respect_mul to_hom _ _) ⬝ to_respect_mul from_hom _ _ ⬝ _, exact ap011 mul gβ hβ } } end variables {I J : Type} [is_set I] [is_set J] {Y Y' Y'' : I → AbGroup} definition dirsum_functor [constructor] (f : Πi, Y i →g Y' i) : dirsum Y →g dirsum Y' := dirsum_elim (λi, dirsum_incl Y' i ∘g f i) theorem dirsum_functor_compose (f' : Πi, Y' i →g Y'' i) (f : Πi, Y i →g Y' i) : dirsum_functor f' ∘g dirsum_functor f ~ dirsum_functor (λi, f' i ∘g f i) := begin apply dirsum_homotopy, intro i y, reflexivity, end variable (Y) definition dirsum_functor_gid : dirsum_functor (λi, gid (Y i)) ~ gid (dirsum Y) := begin apply dirsum_homotopy, intro i y, reflexivity, end variable {Y} definition dirsum_functor_mul (f f' : Πi, Y i →g Y' i) : homomorphism_mul (dirsum_functor f) (dirsum_functor f') ~ dirsum_functor (λi, homomorphism_mul (f i) (f' i)) := begin apply dirsum_homotopy, intro i y, exact sorry end definition dirsum_functor_homotopy (f f' : Πi, Y i →g Y' i) (p : f ~2 f') : dirsum_functor f ~ dirsum_functor f' := begin apply dirsum_homotopy, intro i y, exact sorry end definition dirsum_functor_left [constructor] (f : J → I) : dirsum (Y ∘ f) →g dirsum Y := dirsum_elim (λj, dirsum_incl Y (f j)) definition dirsum_isomorphism [constructor] (f : Πi, Y i ≃g Y' i) : dirsum Y ≃g dirsum Y' := let to_hom := dirsum_functor (λ i, f i) in let from_hom := dirsum_functor (λ i, (f i)⁻¹ᵍ) in begin fapply isomorphism.mk, exact dirsum_functor (λ i, f i), fapply is_equiv.adjointify, exact dirsum_functor (λ i, (f i)⁻¹ᵍ), { intro ds, refine (homomorphism_compose_eq (dirsum_functor (λ i, f i)) (dirsum_functor (λ i, (f i)⁻¹ᵍ)) _)⁻¹ ⬝ _, refine dirsum_functor_compose (λ i, f i) (λ i, (f i)⁻¹ᵍ) ds ⬝ _, refine dirsum_functor_homotopy _ (λ i, !gid) (λ i, to_right_inv (equiv_of_isomorphism (f i))) ds ⬝ _, exact !dirsum_functor_gid }, { intro ds, refine (homomorphism_compose_eq (dirsum_functor (λ i, (f i)⁻¹ᵍ)) (dirsum_functor (λ i, f i)) _)⁻¹ ⬝ _, refine dirsum_functor_compose (λ i, (f i)⁻¹ᵍ) (λ i, f i) ds ⬝ _, refine dirsum_functor_homotopy _ (λ i, !gid) (λ i x, proof to_left_inv (equiv_of_isomorphism (f i)) x qed ) ds ⬝ _, exact !dirsum_functor_gid } end end group namespace group definition dirsum_down_left.{u v w} {I : Type.{u}} [is_set I] (Y : I → AbGroup.{w}) : dirsum (Y ∘ down.{u v}) ≃g dirsum Y := proof let to_hom := @dirsum_functor_left _ _ _ _ Y down.{u v} in let from_hom := dirsum_elim (λi, dirsum_incl (Y ∘ down.{u v}) (up.{u v} i)) in begin fapply isomorphism.mk, { exact to_hom }, fapply adjointify, { exact from_hom }, { intro ds, refine (homomorphism_compose_eq to_hom from_hom ds)⁻¹ ⬝ _, refine @dirsum_homotopy I _ Y (dirsum Y) (to_hom ∘g from_hom) !gid _ ds, intro i y, refine homomorphism_compose_eq to_hom from_hom _ ⬝ _, refine ap to_hom (dirsum_elim_compute (λi, dirsum_incl (Y ∘ down.{u v}) (up.{u v} i)) i y) ⬝ _, refine dirsum_elim_compute _ (up.{u v} i) y ⬝ _, reflexivity }, { intro ds, refine (homomorphism_compose_eq from_hom to_hom ds)⁻¹ ⬝ _, refine @dirsum_homotopy _ _ (Y ∘ down.{u v}) (dirsum (Y ∘ down.{u v})) (from_hom ∘g to_hom) !gid _ ds, intro i y, induction i with i, refine homomorphism_compose_eq from_hom to_hom _ ⬝ _, refine ap from_hom (dirsum_elim_compute (λi, dirsum_incl Y (down.{u v} i)) (up.{u v} i) y) ⬝ _, refine dirsum_elim_compute _ i y ⬝ _, reflexivity } end qed end group
67de9912abbfdf4c7c3696d3d73238e8d7d21c84
4fa161becb8ce7378a709f5992a594764699e268
/src/order/order_iso.lean
b3251450357693aac9aac33ab114abf249f0296b
[ "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
16,218
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.embedding import data.nat.basic import logic.function.iterate import order.rel_classes open function universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-- An increasing function is injective -/ lemma injective_of_increasing (r : α → α → Prop) (s : β → β → Prop) [is_trichotomous α r] [is_irrefl β s] (f : α → β) (hf : ∀{x y}, r x y → s (f x) (f y)) : injective f := begin intros x y hxy, rcases trichotomous_of r x y with h | h | h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this, exact h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this end /-- An order embedding with respect to a given pair of orders `r` and `s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/ structure order_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β := (ord' : ∀ {a b}, r a b ↔ s (to_embedding a) (to_embedding b)) infix ` ≼o `:25 := order_embedding /-- the induced order on a subtype is an embedding under the natural inclusion. -/ definition subtype.order_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) : ((subtype.val : subtype p → X) ⁻¹'o r) ≼o r := ⟨⟨subtype.val,subtype.val_injective⟩,by intros;refl⟩ theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop} (hs : equivalence s) : equivalence (f ⁻¹'o s) := ⟨λ a, hs.1 _, λ a b h, hs.2.1 h, λ a b c h₁ h₂, hs.2.2 h₁ h₂⟩ namespace order_embedding instance : has_coe_to_fun (r ≼o s) := ⟨λ _, α → β, λ o, o.to_embedding⟩ theorem injective (f : r ≼o s) : injective f := f.inj' theorem ord (f : r ≼o s) : ∀ {a b}, r a b ↔ s (f a) (f b) := f.ord' @[simp] theorem coe_fn_mk (f : α ↪ β) (o) : (@order_embedding.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r ≼o s) : (f.to_embedding : α → β) = f := rfl /-- The map `coe_fn : (r ≼o s) → (r → s)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_inj : ∀ ⦃e₁ e₂ : r ≼o s⦄, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨⟨f₁, h₁⟩, o₁⟩ ⟨⟨f₂, h₂⟩, o₂⟩ h := by { congr, exact h } @[refl] protected def refl (r : α → α → Prop) : r ≼o r := ⟨embedding.refl _, λ a b, iff.rfl⟩ @[trans] protected def trans (f : r ≼o s) (g : s ≼o t) : r ≼o t := ⟨f.1.trans g.1, λ a b, by rw [f.2, g.2]; simp⟩ @[simp] theorem refl_apply (x : α) : order_embedding.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼o s) (g : s ≼o t) (a : α) : (f.trans g) a = g (f a) := rfl /-- An order embedding is also an order embedding between dual orders. -/ def rsymm (f : r ≼o s) : swap r ≼o swap s := ⟨f.to_embedding, λ a b, f.ord⟩ /-- If `f` is injective, then it is an order embedding from the preimage order of `s` to `s`. -/ def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ≼o s := ⟨f, λ a b, iff.rfl⟩ theorem eq_preimage (f : r ≼o s) : r = f ⁻¹'o s := by { ext a b, exact f.ord } protected theorem is_irrefl : ∀ (f : r ≼o s) [is_irrefl β s], is_irrefl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o.1 h)⟩ protected theorem is_refl : ∀ (f : r ≼o s) [is_refl β s], is_refl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a, o.2 (H _)⟩ protected theorem is_symm : ∀ (f : r ≼o s) [is_symm β s], is_symm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h, o.2 (H _ _ (o.1 h))⟩ protected theorem is_asymm : ∀ (f : r ≼o s) [is_asymm β s], is_asymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o.1 h₁) (o.1 h₂)⟩ protected theorem is_antisymm : ∀ (f : r ≼o s) [is_antisymm β s], is_antisymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_trans : ∀ (f : r ≼o s) [is_trans β s], is_trans α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.2 (H _ _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_total : ∀ (f : r ≼o s) [is_total β s], is_total α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).2 (H _ _)⟩ protected theorem is_preorder : ∀ (f : r ≼o s) [is_preorder β s], is_preorder α r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : ∀ (f : r ≼o s) [is_partial_order β s], is_partial_order α r | f H := by exactI {..f.is_preorder, ..f.is_antisymm} protected theorem is_linear_order : ∀ (f : r ≼o s) [is_linear_order β s], is_linear_order α r | f H := by exactI {..f.is_partial_order, ..f.is_total} protected theorem is_strict_order : ∀ (f : r ≼o s) [is_strict_order β s], is_strict_order α r | f H := by exactI {..f.is_irrefl, ..f.is_trans} protected theorem is_trichotomous : ∀ (f : r ≼o s) [is_trichotomous β s], is_trichotomous α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff.symm o)).2 (H _ _)⟩ protected theorem is_strict_total_order' : ∀ (f : r ≼o s) [is_strict_total_order' β s], is_strict_total_order' α r | f H := by exactI {..f.is_trichotomous, ..f.is_strict_order} protected theorem acc (f : r ≼o s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.ord.1 h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r ≼o s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : ∀ (f : r ≼o s) [is_well_order β s], is_well_order α r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- It suffices to prove `f` is monotone between strict orders to show it is an order embedding. -/ def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ≼o s := begin haveI := @is_asymm.is_irrefl β s _, refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨H _ _, λ h, _⟩⟩, { refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _; exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) }, { refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)), { subst e, exact irrefl _ h }, { exact asymm (H _ _ h') h } } end @[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) : (@of_monotone _ _ r s _ _ f H : α → β) = f := rfl -- If le is preserved by an order embedding of preorders, then lt is too def lt_embedding_of_le_embedding [preorder α] [preorder β] (f : (has_le.le : α → α → Prop) ≼o (has_le.le : β → β → Prop)) : (has_lt.lt : α → α → Prop) ≼o (has_lt.lt : β → β → Prop) := { ord' := by intros; simp [lt_iff_le_not_le,f.ord], .. f } def nat_lt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f n) (f (n+1))) : ((<) : ℕ → ℕ → Prop) ≼o r := of_monotone f $ λ a b h, begin induction b with b IH, {exact (nat.not_lt_zero _ h).elim}, cases nat.lt_succ_iff_lt_or_eq.1 h with h e, { exact trans (IH h) (H _) }, { subst b, apply H } end def nat_gt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f (n+1)) (f n)) : ((>) : ℕ → ℕ → Prop) ≼o r := by haveI := is_strict_order.swap r; exact rsymm (nat_lt f H) theorem well_founded_iff_no_descending_seq [is_strict_order α r] : well_founded r ↔ ¬ nonempty (((>) : ℕ → ℕ → Prop) ≼o r) := ⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩, suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl, λ a ac, begin induction ac with a _ IH, intros n h, subst a, exact IH (f (n+1)) (o.1 (nat.lt_succ_self _)) _ rfl end, λ N, ⟨λ a, classical.by_contradiction $ λ na, let ⟨f, h⟩ := classical.axiom_of_choice $ show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1, from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $ ⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in N ⟨nat_gt (λ n, (f^[n] ⟨a, na⟩).1) $ λ n, by { rw [function.iterate_succ'], apply h }⟩⟩⟩ end order_embedding /-- The inclusion map `fin n → ℕ` is an order embedding. -/ def fin.val.order_embedding (n) : @order_embedding (fin n) ℕ (<) (<) := ⟨⟨fin.val, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The inclusion map `fin m → fin n` is an order embedding. -/ def fin_fin.order_embedding {m n} (h : m ≤ n) : @order_embedding (fin m) (fin n) (<) (<) := ⟨⟨λ ⟨x, h'⟩, ⟨x, lt_of_lt_of_le h' h⟩, λ ⟨a, _⟩ ⟨b, _⟩ h, by congr; injection h⟩, by intros; cases a; cases b; refl⟩ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (fin.val.order_embedding _).is_well_order /-- An order isomorphism is an equivalence that is also an order embedding. -/ structure order_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β := (ord' : ∀ {a b}, r a b ↔ s (to_equiv a) (to_equiv b)) infix ` ≃o `:25 := order_iso namespace order_iso /-- Convert an `order_iso` to an `order_embedding`. This function is also available as a coercion but often it is easier to write `f.to_order_embedding` than to write explicitly `r` and `s` in the target type. -/ def to_order_embedding (f : r ≃o s) : r ≼o s := ⟨f.to_equiv.to_embedding, f.ord'⟩ instance : has_coe (r ≃o s) (r ≼o s) := ⟨to_order_embedding⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ≃o s) := ⟨λ _, α → β, λ f, f⟩ @[simp] lemma to_order_embedding_eq_coe (f : r ≃o s) : f.to_order_embedding = f := rfl @[simp] lemma coe_coe_fn (f : r ≃o s) : ((f : r ≼o s) : α → β) = f := rfl theorem ord (f : r ≃o s) : ∀ {a b}, r a b ↔ s (f a) (f b) := f.ord' lemma ord'' {r : α → α → Prop} {s : β → β → Prop} (f : r ≃o s) {x y : α} : r x y ↔ s ((↑f : r ≼o s) x) ((↑f : r ≼o s) y) := f.ord @[simp] theorem coe_fn_mk (f : α ≃ β) (o) : (@order_iso.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃o s) : (f.to_equiv : α → β) = f := rfl theorem to_equiv_injective : injective (to_equiv : (r ≃o s) → α ≃ β) | ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by { congr, exact h } /-- The map `coe_fn : (r ≃o s) → (r → s)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_injective ⦃e₁ e₂ : r ≃o s⦄ (h : (e₁ : α → β) = e₂) : e₁ = e₂ := to_equiv_injective $ equiv.coe_fn_injective h @[ext] theorem ext {e₁ e₂ : r ≃o s} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ := coe_fn_injective $ funext h /-- Identity map is an order isomorphism. -/ @[refl] protected def refl (r : α → α → Prop) : r ≃o r := ⟨equiv.refl _, λ a b, iff.rfl⟩ /-- Inverse map of an order isomorphism is an order isomorphism. -/ @[symm] protected def symm (f : r ≃o s) : s ≃o r := ⟨f.to_equiv.symm, λ a b, by cases f with f o; rw o; simp⟩ /-- Composition of two order isomorphisms is an order isomorphism. -/ @[trans] protected def trans (f₁ : r ≃o s) (f₂ : s ≃o t) : r ≃o t := ⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, f₁.ord.trans f₂.ord⟩ /-- An order isomorphism is also an order isomorphism between dual orders. -/ def rsymm (f : r ≃o s) : (swap r) ≃o (swap s) := ⟨f.to_equiv, λ _ _, f.ord⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@order_iso.mk _ _ r s f o).symm : β → α) = f.symm := rfl @[simp] theorem refl_apply (x : α) : order_iso.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≃o s) (g : s ≃o t) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : r ≃o s) (x : β) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] theorem symm_apply_apply (e : r ≃o s) (x : α) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x theorem rel_symm_apply (e : r ≃o s) {x y} : r x (e.symm y) ↔ s (e x) y := by rw [e.ord, e.apply_symm_apply] theorem symm_apply_rel (e : r ≃o s) {x y} : r (e.symm x) y ↔ s x (e y) := by rw [e.ord, e.apply_symm_apply] protected lemma bijective (e : r ≃o s) : bijective e := e.to_equiv.bijective protected lemma injective (e : r ≃o s) : injective e := e.to_equiv.injective protected lemma surjective (e : r ≃o s) : surjective e := e.to_equiv.surjective /-- Any equivalence lifts to an order isomorphism between `s` and its preimage. -/ protected def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃o s := ⟨f, λ a b, iff.rfl⟩ /-- A surjective order embedding is an order isomorphism. -/ noncomputable def of_surjective (f : r ≼o s) (H : surjective f) : r ≃o s := ⟨equiv.of_bijective f ⟨f.injective, H⟩, by simp [f.ord']⟩ @[simp] theorem of_surjective_coe (f : r ≼o s) (H) : (of_surjective f H : α → β) = f := rfl def sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : sum.lex r₁ s₁ ≃o sum.lex r₂ s₂ := ⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b, by cases e₁ with f hf; cases e₂ with g hg; cases a; cases b; simp [hf, hg]⟩ def prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : prod.lex r₁ s₁ ≃o prod.lex r₂ s₂ := ⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, begin cases e₁ with f hf; cases e₂ with g hg, cases a with a₁ a₂; cases b with b₁ b₂, suffices : prod.lex r₁ s₁ (a₁, a₂) (b₁, b₂) ↔ prod.lex r₂ s₂ (f a₁, g a₂) (f b₁, g b₂), {simpa [hf, hg]}, split, { intro h, cases h with _ _ _ _ h _ _ _ h, { left, exact hf.1 h }, { right, exact hg.1 h } }, { generalize e : f b₁ = fb₁, intro h, cases h with _ _ _ _ h _ _ _ h, { subst e, left, exact hf.2 h }, { have := f.injective e, subst b₁, right, exact hg.2 h } } end⟩ instance : group (r ≃o r) := { one := order_iso.refl r, mul := λ f₁ f₂, f₂.trans f₁, inv := order_iso.symm, mul_assoc := λ f₁ f₂ f₃, rfl, one_mul := λ f, ext $ λ _, rfl, mul_one := λ f, ext $ λ _, rfl, mul_left_inv := λ f, ext f.symm_apply_apply } @[simp] lemma coe_one : ⇑(1 : r ≃o r) = id := rfl @[simp] lemma coe_mul (e₁ e₂ : r ≃o r) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl lemma mul_apply (e₁ e₂ : r ≃o r) (x : α) : (e₁ * e₂) x = e₁ (e₂ x) := rfl @[simp] lemma inv_apply_self (e : r ≃o r) (x) : e⁻¹ (e x) = x := e.symm_apply_apply x @[simp] lemma apply_inv_self (e : r ≃o r) (x) : e (e⁻¹ x) = x := e.apply_symm_apply x end order_iso /-- A subset `p : set α` embeds into `α` -/ def set_coe_embedding {α : Type*} (p : set α) : p ↪ α := ⟨subtype.val, @subtype.eq _ _⟩ /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : α → α → Prop) (p : set α) : p → p → Prop := @subtype.val _ p ⁻¹'o r @[simp] theorem subrel_val (r : α → α → Prop) (p : set α) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel protected def order_embedding (r : α → α → Prop) (p : set α) : subrel r p ≼o r := ⟨set_coe_embedding _, λ a b, iff.rfl⟩ @[simp] theorem order_embedding_apply (r : α → α → Prop) (p a) : subrel.order_embedding r p a = a.1 := rfl instance (r : α → α → Prop) [is_well_order α r] (p : set α) : is_well_order p (subrel r p) := order_embedding.is_well_order (subrel.order_embedding r p) end subrel /-- Restrict the codomain of an order embedding -/ def order_embedding.cod_restrict (p : set β) (f : r ≼o s) (H : ∀ a, f a ∈ p) : r ≼o subrel s p := ⟨f.to_embedding.cod_restrict p H, f.ord'⟩ @[simp] theorem order_embedding.cod_restrict_apply (p) (f : r ≼o s) (H a) : order_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl
5639834cd83c2e1f4ca9cbef757fb0377c7ecefd
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/floor.lean
932b5070b00d9907dbfd0ff936c73061f56f8fe6
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
9,808
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Kappelmann -/ import data.int.basic import tactic.linarith tactic.abel /-! # Floor and Ceil ## Summary We define `floor`, `ceil`, and `nat_ceil` functions on linear ordered rings. ## Main Definitions - `floor_ring` is a linear ordered ring with floor function. - `floor x` is the greatest integer `z` such that `z ≤ x`. - `fract x` is the fractional part of x, that is `x - floor x`. - `ceil x` is the smallest integer `z` such that `x ≤ z`. - `nat_ceil x` is the smallest nonnegative integer `n` with `x ≤ n`. ## Notations - `⌊x⌋` is `floor x`. - `⌈x⌉` is `ceil x`. ## Tags rounding -/ variables {α : Type*} /-- A `floor_ring` is a linear ordered ring over `α` with a function `floor : α → ℤ` satisfying `∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x)`. -/ class floor_ring (α) [linear_ordered_ring α] := (floor : α → ℤ) (le_floor : ∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x) instance : floor_ring ℤ := { floor := id, le_floor := λ _ _, by rw int.cast_id; refl } variables [linear_ordered_ring α] [floor_ring α] /-- `floor x` is the greatest integer `z` such that `z ≤ x` -/ def floor : α → ℤ := floor_ring.floor notation `⌊` x `⌋` := floor x theorem le_floor : ∀ {z : ℤ} {x : α}, z ≤ ⌊x⌋ ↔ (z : α) ≤ x := floor_ring.le_floor theorem floor_lt {x : α} {z : ℤ} : ⌊x⌋ < z ↔ x < z := lt_iff_lt_of_le_iff_le le_floor theorem floor_le (x : α) : (⌊x⌋ : α) ≤ x := le_floor.1 (le_refl _) theorem floor_nonneg {x : α} : 0 ≤ ⌊x⌋ ↔ 0 ≤ x := by rw [le_floor]; refl theorem lt_succ_floor (x : α) : x < ⌊x⌋.succ := floor_lt.1 $ int.lt_succ_self _ theorem lt_floor_add_one (x : α) : x < ⌊x⌋ + 1 := by simpa only [int.succ, int.cast_add, int.cast_one] using lt_succ_floor x theorem sub_one_lt_floor (x : α) : x - 1 < ⌊x⌋ := sub_lt_iff_lt_add.2 (lt_floor_add_one x) @[simp] theorem floor_coe (z : ℤ) : ⌊(z:α)⌋ = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] @[simp] theorem floor_zero : ⌊(0:α)⌋ = 0 := floor_coe 0 @[simp] theorem floor_one : ⌊(1:α)⌋ = 1 := by rw [← int.cast_one, floor_coe] theorem floor_mono {a b : α} (h : a ≤ b) : ⌊a⌋ ≤ ⌊b⌋ := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (x : α) (z : ℤ) : ⌊x + z⌋ = ⌊x⌋ + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] theorem floor_sub_int (x : α) (z : ℤ) : ⌊x - z⌋ = ⌊x⌋ - z := eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _) lemma abs_sub_lt_one_of_floor_eq_floor {α : Type*} [decidable_linear_ordered_comm_ring α] [floor_ring α] {x y : α} (h : ⌊x⌋ = ⌊y⌋) : abs (x - y) < 1 := begin have : x < ⌊x⌋ + 1 := lt_floor_add_one x, have : y < ⌊y⌋ + 1 := lt_floor_add_one y, have : (⌊x⌋ : α) = ⌊y⌋ := int.cast_inj.2 h, have : (⌊x⌋: α) ≤ x := floor_le x, have : (⌊y⌋ : α) ≤ y := floor_le y, exact abs_sub_lt_iff.2 ⟨by linarith, by linarith⟩ end lemma floor_eq_iff {r : α} {z : ℤ} : ⌊r⌋ = z ↔ ↑z ≤ r ∧ r < (z + 1) := by rw [←le_floor, ←int.cast_one, ←int.cast_add, ←floor_lt, int.lt_add_one_iff, le_antisymm_iff, and.comm] lemma floor_ring_unique {α} [linear_ordered_ring α] (inst1 inst2 : floor_ring α) : @floor _ _ inst1 = @floor _ _ inst2 := begin ext v, suffices : (⌊v⌋ : α) ≤ v ∧ v < ⌊v⌋ + 1, by rwa [floor_eq_iff], exact ⟨floor_le v, lt_floor_add_one v⟩ end /-- The fractional part fract r of r is just r - ⌊r⌋ -/ def fract (r : α) : α := r - ⌊r⌋ -- Mathematical notation is usually {r}. Let's not even go there. @[simp] lemma floor_add_fract (r : α) : (⌊r⌋ : α) + fract r = r := by unfold fract; simp @[simp] lemma fract_add_floor (r : α) : fract r + ⌊r⌋ = r := sub_add_cancel _ _ theorem fract_nonneg (r : α) : 0 ≤ fract r := sub_nonneg.2 $ floor_le _ theorem fract_lt_one (r : α) : fract r < 1 := sub_lt.1 $ sub_one_lt_floor _ @[simp] lemma fract_zero : fract (0 : α) = 0 := by unfold fract; simp @[simp] lemma fract_coe (z : ℤ) : fract (z : α) = 0 := by unfold fract; rw floor_coe; exact sub_self _ @[simp] lemma fract_floor (r : α) : fract (⌊r⌋ : α) = 0 := fract_coe _ @[simp] lemma floor_fract (r : α) : ⌊fract r⌋ = 0 := by rw floor_eq_iff; exact ⟨fract_nonneg _, by rw [int.cast_zero, zero_add]; exact fract_lt_one r⟩ theorem fract_eq_iff {r s : α} : fract r = s ↔ 0 ≤ s ∧ s < 1 ∧ ∃ z : ℤ, r - s = z := ⟨λ h, by rw ←h; exact ⟨fract_nonneg _, fract_lt_one _, ⟨⌊r⌋, sub_sub_cancel _ _⟩⟩, begin intro h, show r - ⌊r⌋ = s, apply eq.symm, rw [eq_sub_iff_add_eq, add_comm, ←eq_sub_iff_add_eq], rcases h with ⟨hge, hlt, ⟨z, hz⟩⟩, rw [hz, int.cast_inj, floor_eq_iff, ←hz], clear hz, split; linarith {discharger := `[simp]} end⟩ theorem fract_eq_fract {r s : α} : fract r = fract s ↔ ∃ z : ℤ, r - s = z := ⟨λ h, ⟨⌊r⌋ - ⌊s⌋, begin unfold fract at h, rw [int.cast_sub, sub_eq_sub_iff_sub_eq_sub.1 h], end⟩, λ h, begin rcases h with ⟨z, hz⟩, rw fract_eq_iff, split, exact fract_nonneg _, split, exact fract_lt_one _, use z + ⌊s⌋, rw [eq_add_of_sub_eq hz, int.cast_add], unfold fract, simp end⟩ @[simp] lemma fract_fract (r : α) : fract (fract r) = fract r := by rw fract_eq_fract; exact ⟨-⌊r⌋, by unfold fract;simp⟩ theorem fract_add (r s : α) : ∃ z : ℤ, fract (r + s) - fract r - fract s = z := ⟨⌊r⌋ + ⌊s⌋ - ⌊r + s⌋, by unfold fract; simp⟩ theorem fract_mul_nat (r : α) (b : ℕ) : ∃ z : ℤ, fract r * b - fract (r * b) = z := begin induction b with c hc, use 0, simp, rcases hc with ⟨z, hz⟩, rw [nat.succ_eq_add_one, nat.cast_add, mul_add, mul_add, nat.cast_one, mul_one, mul_one], rcases fract_add (r * c) r with ⟨y, hy⟩, use z - y, rw [int.cast_sub, ←hz, ←hy], abel end /-- `ceil x` is the smallest integer `z` such that `x ≤ z` -/ def ceil (x : α) : ℤ := -⌊-x⌋ notation `⌈` x `⌉` := ceil x theorem ceil_le {z : ℤ} {x : α} : ⌈x⌉ ≤ z ↔ x ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem lt_ceil {x : α} {z : ℤ} : z < ⌈x⌉ ↔ (z:α) < x := lt_iff_lt_of_le_iff_le ceil_le theorem ceil_le_floor_add_one (x : α) : ⌈x⌉ ≤ ⌊x⌋ + 1 := by rw [ceil_le, int.cast_add, int.cast_one]; exact le_of_lt (lt_floor_add_one x) theorem le_ceil (x : α) : x ≤ ⌈x⌉ := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ⌈(z:α)⌉ = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : α} (h : a ≤ b) : ⌈a⌉ ≤ ⌈b⌉ := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (x : α) (z : ℤ) : ⌈x + z⌉ = ⌈x⌉ + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (x : α) (z : ℤ) : ⌈x - z⌉ = ⌈x⌉ - z := eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _) theorem ceil_lt_add_one (x : α) : (⌈x⌉ : α) < x + 1 := by rw [← lt_ceil, ← int.cast_one, ceil_add_int]; apply lt_add_one lemma ceil_pos {a : α} : 0 < ⌈a⌉ ↔ 0 < a := ⟨ λ h, have ⌊-a⌋ < 0, from neg_of_neg_pos h, pos_of_neg_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).1 $ not_le_of_gt this, λ h, have -a < 0, from neg_neg_of_pos h, neg_pos_of_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).2 $ not_le_of_gt this ⟩ @[simp] theorem ceil_zero : ⌈(0 : α)⌉ = 0 := by simp [ceil] lemma ceil_nonneg [decidable_rel ((<) : α → α → Prop)] {q : α} (hq : 0 ≤ q) : 0 ≤ ⌈q⌉ := if h : q > 0 then le_of_lt $ ceil_pos.2 h else by rw [le_antisymm (le_of_not_lt h) hq, ceil_zero]; trivial /-- `nat_ceil x` is the smallest nonnegative integer `n` with `x ≤ n`. It is the same as `⌈q⌉` when `q ≥ 0`, otherwise it is `0`. -/ def nat_ceil (a : α) : ℕ := int.to_nat (⌈a⌉) theorem nat_ceil_le {a : α} {n : ℕ} : nat_ceil a ≤ n ↔ a ≤ n := by rw [nat_ceil, int.to_nat_le, ceil_le]; refl theorem lt_nat_ceil {a : α} {n : ℕ} [decidable ((n : α) < a)] : n < nat_ceil a ↔ (n : α) < a := not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le] theorem le_nat_ceil (a : α) : a ≤ nat_ceil a := nat_ceil_le.1 (le_refl _) theorem nat_ceil_mono {a₁ a₂ : α} (h : a₁ ≤ a₂) : nat_ceil a₁ ≤ nat_ceil a₂ := nat_ceil_le.2 (le_trans h (le_nat_ceil _)) @[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil (n : α) = n := show (⌈((n : ℤ) : α)⌉).to_nat = n, by rw [ceil_coe]; refl @[simp] theorem nat_ceil_zero : nat_ceil (0 : α) = 0 := nat_ceil_coe 0 theorem nat_ceil_add_nat {a : α} (a_nonneg : 0 ≤ a) (n : ℕ) : nat_ceil (a + n) = nat_ceil a + n := begin change int.to_nat (⌈a + (n:ℤ)⌉) = int.to_nat ⌈a⌉ + n, rw [ceil_add_int], have : 0 ≤ ⌈a⌉, by simpa using (ceil_mono a_nonneg), obtain ⟨_, ceil_a_eq⟩ : ∃ (n : ℕ), ⌈a⌉ = n, from int.eq_coe_of_zero_le this, rw ceil_a_eq, refl end theorem nat_ceil_lt_add_one {a : α} (a_nonneg : 0 ≤ a) [decidable ((nat_ceil a : α) < a + 1)] : (nat_ceil a : α) < a + 1 := lt_nat_ceil.1 $ by rw ( show nat_ceil (a + 1) = nat_ceil a + 1, by exact_mod_cast (nat_ceil_add_nat a_nonneg 1)); apply nat.lt_succ_self lemma lt_of_nat_ceil_lt {x : α} {n : ℕ} (h : nat_ceil x < n) : x < n := lt_of_le_of_lt (le_nat_ceil x) (by exact_mod_cast h) lemma le_of_nat_ceil_le {x : α} {n : ℕ} (h : nat_ceil x ≤ n) : x ≤ n := le_trans (le_nat_ceil x) (by exact_mod_cast h)
3e8dd38307d1367228eae18bb799236a4a10d936
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/parser1.lean
4e6cf5d650668cd2347a5c1622059a0913c22aca
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,046
lean
import init.lean.parser.parser open Lean open Lean.Parser namespace Foo @[builtinTestParser] def pairParser := parser! "(" >> numLit >> "," >> ident >> ")" @[builtinTestParser] def pairsParser := parser! "{" >> sepBy1 testParser "," >> "}" @[builtinTestParser] def functionParser := parser! "fun" >> ident >> "," >> testParser @[builtinTestParser] def identParser : Parser := ident @[builtinTestParser] def numParser : Parser := numLit @[builtinTestParser] def strParser : Parser := strLit end Foo def testParser (input : String) : IO Unit := do env ← mkEmptyEnvironment; testPTables ← builtinTestParsingTable.get; stx ← IO.ofExcept $ runParser env testPTables input; IO.println stx def main (xs : List String) : IO Unit := do testParser "(10, hello)"; testParser "{ hello, 400, \"hello\", (10, hello), /- comment -/ (20, world), { fun x, (10, hello) }, { (30, foo) } }"; -- Following example has syntax error testParser "{ hello, 400, \"hello\", (10, hello), /- comment -/ (20, world), { fun x, [ (10, hello) }, { (30, foo) } }"
e7a5a8aeb939679e7c62fce54f505c58ac7951e1
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/src/Lean/Elab/Match.lean
39affaa00ad4aaadb311f6d32cde6863f8730d5d
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
48,802
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.Util.CollectFVars import Lean.Meta.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Meta.SortLocalDecls import Lean.Elab.SyntheticMVars import Lean.Elab.App import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /- This modules assumes "match"-expressions use the following syntax. ```lean def matchDiscr := leading_parser optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def «match» := leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` -/ structure MatchAltView where ref : Syntax patterns : Array Syntax rhs : Syntax deriving Inhabited private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx <| elabTerm newStx expectedType? private def elabDiscrsWitMatchType (discrStxs : Array Syntax) (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr × Bool) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType let mut isDep := false for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq <| elabTermEnsuringType discrStx[1] d trace[Elab.match] "discr #{i} {discr} : {d}" if b.hasLooseBVars then isDep := true matchType ← b.instantiate1 discr discrs := discrs.push discr | _ => throwError "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected" pure (discrs, isDep) private def mkUserNameFor (e : Expr) : TermElabM Name := do match e with /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/ | Expr.fvar fvarId _ => mkFreshUserName ((← getLocalDecl fvarId).userName) | _ => mkFreshBinderName /-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/ def isAuxDiscrName (n : Name) : Bool := n.hasMacroScopes && n.eraseMacroScopes == `_discr /- We treat `@x` as atomic to avoid unnecessary extra local declarations from being inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier. Thus this is kind of discriminant is quite common. Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression. This can happen due to error recovery. Example ``` example : (p ∨ p) → p := fun h => match ``` If we don't abort, the elaborator loops because we will keep trying to expand ``` match ``` into ``` let d := <Syntax.missing>; match ``` Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/ def isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do match discr with | `($x:ident) => isLocalIdent? x | `(@$x:ident) => isLocalIdent? x | _ => if discr.isMissing then throwAbortTerm else return none -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] match (← isAtomicDiscr? term) with | some e@(Expr.fvar fvarId _) => let localDecl ← getLocalDecl fvarId if !isAuxDiscrName localDecl.userName then pure e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?` else pure localDecl.value | _ => throwErrorAt discr "unexpected discriminant" structure ElabMatchTypeAndDiscsResult where discrs : Array Expr matchType : Expr /- `true` when performing dependent elimination. We use this to decide whether we optimize the "match unit" case. See `isMatchUnit?`. -/ isDep : Bool alts : Array MatchAltView private def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM ElabMatchTypeAndDiscsResult := do let numDiscrs := discrStxs.size if matchOptType.isNone then let rec loop (i : Nat) (discrs : Array Expr) (matchType : Expr) (isDep : Bool) (matchAltViews : Array MatchAltView) := do match i with | 0 => return { discrs := discrs.reverse, matchType := matchType, isDep := isDep, alts := matchAltViews } | i+1 => let discrStx := discrStxs[i] let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let discrType ← inferType discr let discrType ← instantiateMVars discrType let matchTypeBody ← kabstract matchType discr let isDep := isDep || matchTypeBody.hasLooseBVars let userName ← mkUserNameFor discr if discrStx[0].isNone then loop i (discrs.push discr) (Lean.mkForall userName BinderInfo.default discrType matchTypeBody) isDep matchAltViews else let identStx := discrStx[0][0] withLocalDeclD userName discrType fun x => do let eqType ← mkEq discr x withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody := matchTypeBody.instantiate1 x let matchType ← mkForallFVars #[x, h] matchTypeBody let refl ← mkEqRefl discr let discrs := (discrs.push refl).push discr let matchAltViews := matchAltViews.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx } loop i discrs matchType isDep matchAltViews loop discrStxs.size (discrs := #[]) (isDep := false) expectedType matchAltViews else let matchTypeStx := matchOptType[0][1] let matchType ← elabType matchTypeStx let (discrs, isDep) ← elabDiscrsWitMatchType discrStxs matchType expectedType return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews } def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts : Syntax → Array MatchAltView | `(match $discrs,* $[: $ty?]? with $alts:matchAlt*) => alts.filterMap fun alt => match alt with | `(matchAltExpr| | $patterns,* => $rhs) => some { ref := alt, patterns := patterns, rhs := rhs } | _ => none | _ => #[] /-- Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and `_` in patterns. -/ def mkInaccessible (e : Expr) : Expr := mkAnnotation `_inaccessible e def inaccessible? (e : Expr) : Option Expr := annotation? `_inaccessible e inductive PatternVar where | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance : ToString PatternVar := ⟨fun | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩ builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do let mvarId ← mkFreshId return Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ private def getMVarSyntaxMVarId (stx : Syntax) : MVarId := stx[0].getKind /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return mkInaccessible e /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State where found : NameSet := {} vars : Array PatternVar := #[] abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do let mut result := 0 for p in ps do let localDecl ← getLocalDecl p.fvarId! if localDecl.binderInfo.isExplicit then result := result+1 pure result private def throwInvalidPattern {α} : M α := throwError "invalid pattern" /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context where funId : Syntax ctorVal? : Option ConstructorVal -- It is `some`, if constructor application explicit : Bool ellipsis : Bool paramDecls : Array (Name × BinderInfo) -- parameters names and binder information paramDeclIdx : Nat := 0 namedArgs : Array NamedArg args : List Arg newArgs : Array Syntax := #[] deriving Inhabited private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := do if ctx.namedArgs.isEmpty && ctx.args.isEmpty then let fStx ← `(@$(ctx.funId):ident) return Syntax.mkApp fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.numParams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩ d.2.isExplicit else false private def getNextParam (ctx : Context) : (Name × BinderInfo) × Context := let i := ctx.paramDeclIdx let d := ctx.paramDecls[i] (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent do throwErrorAt idStx "identifier expected" let id := idStx.getId unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic" if (← get).found.contains id then throwError "invalid pattern, variable '{id}' occurred more than once" modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id } return idStx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match stx[0].isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax private def doubleQuotedNameToPattern (stx : Syntax) : TermElabM Syntax := do match stx[1].isNameLit? with | some val => nameToPattern (← resolveGlobalConstNoOverloadWithInfo stx[1] val) | none => throwIllFormedSyntax partial def collect (stx : Syntax) : M Syntax := withRef stx <| withFreshMacroScope do let k := stx.getKind if k == identKind then processId stx else if k == ``Lean.Parser.Term.app then processCtorApp stx else if k == ``Lean.Parser.Term.anonymousCtor then let elems ← stx[1].getArgs.mapSepElemsM collect return stx.setArg 1 <| mkNullNode elems else if k == ``Lean.Parser.Term.structInst then /- ``` leading_parser "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let withMod := stx[1] unless withMod.isNone do throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns" let fields ← stx[2].getArgs.mapM fun p => do -- p is of the form (group (structInstField >> optional ", ")) let field := p[0] -- leading_parser structInstLVal >> " := " >> termParser let newVal ← collect field[2] let field := field.setArg 2 newVal pure <| field.setArg 0 field return stx.setArg 2 <| mkNullNode fields else if k == ``Lean.Parser.Term.hole then let r ← mkMVarSyntax modify fun s => { s with vars := s.vars.push <| PatternVar.anonymousVar <| getMVarSyntaxMVarId r } return r else if k == ``Lean.Parser.Term.paren then let arg := stx[1] if arg.isNone then return stx -- `()` else let t := arg[0] let s := arg[1] if s.isNone || s[0].getKind == ``Lean.Parser.Term.typeAscription then -- Ignore `s`, since it empty or it is a type ascription let t ← collect t let arg := arg.setArg 0 t return stx.setArg 1 arg else -- Tuple literal is a constructor let t ← collect t let arg := arg.setArg 0 t let tupleTail := s[0] let tupleTailElems := tupleTail[1].getArgs let tupleTailElems ← tupleTailElems.mapSepElemsM collect let tupleTail := tupleTail.setArg 1 <| mkNullNode tupleTailElems let s := s.setArg 0 tupleTail let arg := arg.setArg 1 s return stx.setArg 1 arg else if k == ``Lean.Parser.Term.explicitUniv then processCtor stx[0] else if k == ``Lean.Parser.Term.namedPattern then /- Recall that def namedPattern := check... >> trailing_parser "@" >> termParser -/ let id := stx[0] discard <| processVar id let pat := stx[2] let pat ← collect pat `(_root_.namedPattern $id $pat) else if k == ``Lean.Parser.Term.inaccessible then return stx else if k == strLitKind then return stx else if k == numLitKind then return stx else if k == scientificLitKind then return stx else if k == charLitKind then return stx else if k == ``Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum` instead of the constructors `Name.str` and `Name.num` -/ quotedNameToPattern stx else if k == ``Lean.Parser.Term.doubleQuotedName then /- Similar to previous case -/ doubleQuotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern where processCtorApp (stx : Syntax) : M Syntax := do let (f, namedArgs, args, ellipsis) ← expandApp stx true processCtorAppCore f namedArgs args ellipsis processCtor (stx : Syntax) : M Syntax := do processCtorAppCore stx #[] #[] false /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ processId (stx : Syntax) : M Syntax := do match (← resolveId? stx "pattern") with | none => processVar stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => processCtor stx | some _ => if hasMatchPatternAttribute (← getEnv) fName then processCtor stx else processVar stx | none => throwCtorExpected | _ => processVar stx pushNewArg (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := do match arg with | Arg.stx stx => let stx ← if accessible then collect stx else pure stx return { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! processExplicitArg (accessible : Bool) (ctx : Context) : M Context := do match ctx.args with | [] => if ctx.ellipsis then pushNewArg accessible ctx (Arg.stx (← `(_))) else throwError "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}" | arg::args => pushNewArg accessible { ctx with args := args } arg processImplicitArg (accessible : Bool) (ctx : Context) : M Context := do if ctx.explicit then processExplicitArg accessible ctx else pushNewArg accessible ctx (Arg.stx (← `(_))) processCtorAppContext (ctx : Context) : M Syntax := do if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx let (d, ctx) := getNextParam ctx match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.1 with | some idx => let arg := ctx.namedArgs[idx] let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx } let ctx ← pushNewArg accessible ctx arg.val processCtorAppContext ctx | none => let ctx ← match d.2 with | BinderInfo.implicit => processImplicitArg accessible ctx | BinderInfo.instImplicit => processImplicitArg accessible ctx | _ => processExplicitArg accessible ctx processCtorAppContext ctx processCtorAppCore (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList let (fId, explicit) ← match f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected" let some (Expr.const fName _ _) ← resolveId? fId "pattern" | throwCtorExpected let fInfo ← getConstInfo fName let paramDecls ← forallTelescopeReducing fInfo.type fun xs _ => xs.mapM fun x => do let d ← getFVarLocalDecl x return (d.userName, d.binderInfo) match fInfo with | ConstantInfo.ctorInfo val => processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => if hasMatchPatternAttribute (← getEnv) fName then processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected def main (alt : MatchAltView) : M MatchAltView := do let patterns ← alt.patterns.mapM fun p => do trace[Elab.match] "collecting variables at pattern: {p}" collect p return { alt with patterns := patterns } end CollectPatternVars private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do let (alt, s) ← (CollectPatternVars.main alt).run {} return (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used here, but in other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do let patternStx ← liftMacroM <| expandMacros patternStx let (_, s) ← (CollectPatternVars.collect patternStx).run {} return s.vars def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do let collect : CollectPatternVars.M Unit := do for pattern in patterns do discard <| CollectPatternVars.collect (← liftMacroM <| expandMacros pattern) let (_, s) ← collect.run {} return s.vars /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl where /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) := do if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => let type ← mkFreshTypeMVar let userName ← mkFreshBinderName withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => let type ← mkFreshTypeMVar withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do let type ← inferType (mkFVar fvarId) discard <| mkFreshExprMVarWithId mvarId type | _ => pure () k decls loop 0 #[] /- Remark: when performing dependent pattern matching, we often had to write code such as ```lean def Vec.map' (f : α → β) (xs : Vec α n) : Vec β n := match n, xs with | _, nil => nil | _, cons a as => cons (f a) (map' f as) ``` We had to include `n` and the `_`s because the type of `xs` depends on `n`. Moreover, `nil` and `cons a as` have different types. This was quite tedious. So, we have implemented an automatic "discriminant refinement procedure". The procedure is based on the observation that we get a type error whenenver we forget to include `_`s and the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant is an indexed family, and add their indices as new discriminants. The current implementation, adds indices as they are found, and does not try to "sort" the new discriminants. If the refinement process fails, we report the original error message. -/ /- Auxiliary structure for storing an type mismatch exception when processing the pattern #`idx` of some alternative. -/ structure PatternElabException where ex : Exception idx : Nat private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr × Expr) := withReader (fun ctx => { ctx with implicitLambda := false }) do let mut patterns := #[] let mut matchType := matchType for idx in [:patternStxs.size] do let patternStx := patternStxs[idx] matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← try liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d catch ex => -- Wrap the type mismatch exception for the "discriminant refinement" feature. throwThe PatternElabException { ex := ex, idx := idx } matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" return (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do let mut decls := #[] for pdecl in patternVarDecls do match pdecl with | PatternVarDecl.localVar fvarId => let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => let e ← instantiateMVars (mkMVar mvarId); trace[Elab.match] "finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}" match e with | Expr.mvar newMVarId _ => /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId) trace[Elab.match] "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}" let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | _ => pure () /- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d₁ may occur after d₂ when d₂ depends on d₁. -/ sortLocalDecls decls open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State where found : NameSet := {} localDecls : Array LocalDecl newLocals : NameSet := {} abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do let s ← get return s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError "invalid pattern {indentExpr e}" /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId! let s ← get match (← getExprMVarAssignment? mvarId) with | some val => return Pattern.inaccessible val | none => let fvarId ← mkFreshId let type ← inferType mvar /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId) let userName ← mkFreshBinderName let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default; modify fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl } return Pattern.var fvarId partial def main (e : Expr) : M Pattern := do let isLocalDecl (fvarId : FVarId) : M Bool := do return (← get).localDecls.any fun d => d.fvarId == fvarId let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do if (← alreadyVisited fvarId) then return Pattern.inaccessible e else markAsVisited fvarId return Pattern.var e.fvarId! let mkInaccessible (e : Expr) : M Pattern := do match e with | Expr.fvar fvarId _ => if (← isLocalDecl fvarId) then mkPatternVar fvarId e else return Pattern.inaccessible e | _ => return Pattern.inaccessible e match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => return Pattern.arrayLit α (← lits.mapM main) | none => if e.isAppOfArity `namedPattern 3 then let p ← main <| e.getArg! 2 match e.getArg! 1 with | Expr.fvar fvarId _ => return Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if e.isNatLit || e.isStringLit || e.isCharLit then return Pattern.val e else if e.isFVar then let fvarId := e.fvarId! unless (← isLocalDecl fvarId) do throwInvalidPattern e mkPatternVar fvarId e else if e.isMVar then mkLocalDeclFor e else let newE ← whnf e if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwInvalidPattern e let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM main return Pattern.ctor v.name us params.toList fields.toList end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls } let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ let lctx ← getLCtx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : ExceptT PatternElabException TermElabM α := do let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType id (α := TermElabM α) do let localDecls ← finalizePatternDecls patternVarDecls let patterns ← patterns.mapM (instantiateMVars ·) withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType private def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match] "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do let rhs ← elabTermEnsuringType alt.rhs matchType let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr let rhs ← if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match] "rhs: {rhs}" return (altLHS, rhs) /-- Collect indices for the "discriminant refinement feature". This method is invoked when we detect a type mismatch at a pattern #`idx` of some alternative. -/ private def getIndicesToInclude (discrs : Array Expr) (idx : Nat) : TermElabM (Array Expr) := do let discrType ← whnfD (← inferType discrs[idx]) matchConstInduct discrType.getAppFn (fun _ => return #[]) fun info _ => do let mut result := #[] let args := discrType.getAppArgs for arg in args[info.numParams : args.size] do unless (← discrs.anyM fun discr => isDefEq discr arg) do result := result.push arg return result private partial def elabMatchAltViews (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do loop discrs matchType altViews none where /- "Discriminant refinement" main loop. `first?` contains the first error message we found before updated the `discrs`. -/ loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState × Exception)) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do let s ← saveState match ← altViews.mapM (fun alt => elabMatchAltView alt matchType) |>.run with | Except.ok alts => return (discrs, matchType, alts, first?.isSome) | Except.error { idx := idx, ex := ex } => let indices ← getIndicesToInclude discrs idx if indices.isEmpty then throwEx (← updateFirst first? ex) else let first ← updateFirst first? ex s.restore let indices ← collectDeps indices discrs let matchType ← try updateMatchType indices matchType catch ex => throwEx first let altViews ← addWildcardPatterns indices.size altViews let discrs := indices ++ discrs loop discrs matchType altViews first throwEx {α} (p : SavedState × Exception) : TermElabM α := do p.1.restore; throw p.2 updateFirst (first? : Option (SavedState × Exception)) (ex : Exception) : TermElabM (SavedState × Exception) := do match first? with | none => return (← saveState, ex) | some first => return first containsFVar (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => e.isFVar && e.fvarId! == fvarId /- Update `indices` by including any free variable `x` s.t. - Type of some `discr` depends on `x`. - Type of `x` depends on some free variable in `indices`. If we don't include these extra variables in indices, then `updateMatchType` will generate a type incorrect term. For example, suppose `discr` contains `h : @HEq α a α b`, and `indices` is `#[α, b]`, and `matchType` is `@HEq α a α b → B`. `updateMatchType indices matchType` produces the type `(α' : Type) → (b : α') → @HEq α' a α' b → B` which is type incorrect because we have `a : α`. The method `collectDeps` will include `a` into `indices`. This method does not handle dependencies among non-free variables. We rely on the type checking method `check` at `updateMatchType`. -/ collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do let mut s : CollectFVars.State := {} for discr in discrs do s := collectFVars s (← instantiateMVars (← inferType discr)) let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar let indicesFVar := indicesFVar.map Expr.fvarId! let mut toAdd := #[] for fvarId in s.fvarSet.toList do unless containsFVar discrs fvarId || containsFVar indices fvarId do let localDecl ← getLocalDecl fvarId let mctx ← getMCtx for indexFVarId in indicesFVar do if mctx.localDeclDependsOn localDecl indexFVarId then toAdd := toAdd.push fvarId let lctx ← getLCtx let indicesFVar := (indicesFVar ++ toAdd).qsort fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index return indicesFVar.map mkFVar ++ indicesNonFVar updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do let matchType ← indices.foldrM (init := matchType) fun index matchType => do let indexType ← inferType index let matchTypeBody ← kabstract matchType index let userName ← mkUserNameFor index return Lean.mkForall userName BinderInfo.default indexType matchTypeBody check matchType return matchType addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do let hole := mkHole (← getRef) let wildcards := mkArray num hole return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns } def mkMatcher (elimName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : TermElabM MatcherResult := Meta.Match.mkMatcher elimName matchType numDiscrs lhss register_builtin_option match.ignoreUnusedAlts : Bool := { defValue := false descr := "if true, do not generate error if an alternative is not used" } def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do unless result.counterExamples.isEmpty do withHeadRefOnly <| throwError "missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do let mut i := 0 for alt in altLHSS do if result.unusedAltIdxs.contains i then withRef alt.ref do logError "redundant alternative" i := i + 1 /-- If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]` Otherwise, return none. -/ private def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do assert! altLHSS.length == rhss.size match altLHSS with | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] => /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/ match rhss[0] with | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b | _ => return none | _ => return none private def elabMatchAux (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do let (discrs, matchType, altLHSS, isDep, rhss) ← commitIfDidNotPostpone do let ⟨discrs, matchType, isDep, altViews⟩ ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType let matchAlts ← liftMacroM <| expandMacrosInPatterns altViews trace[Elab.match] "matchType: {matchType}" let (discrs, matchType, alts, refined) ← elabMatchAltViews discrs matchType matchAlts let isDep := isDep || refined /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available after we proces the last argument of `List.forM`. We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeSyntheticMVarsUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 /- Remark: we try to postpone before throwing an error. The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed. The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here. Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here. ``` def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) := (ps.filter fun (p : Prod _ _) => match p with | (x, y) => x == 0) ++ ps ``` When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α` However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`. -/ withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if p.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS return (discrs, matchType, altLHSS, isDep, rhss) if let some r ← if isDep then pure none else isMatchUnit? altLHSS rhss then return r else let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher matcherName matchType numDiscrs altLHSS let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType reportMatcherResultErrors altLHSS matcherResult let r := mkApp matcherResult.matcher motive let r := mkAppN r discrs let r := mkAppN r rhss trace[Elab.match] "result: {r}" return r private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[1].getSepArgs private def getMatchOptType (matchStx : Syntax) : Syntax := matchStx[2] private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptType := getMatchOptType matchStx; if matchOptType.isNone then do let discrs := getDiscrs matchStx; let allLocal ← discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1] if allLocal then return none else -- We use `foundFVars` to make sure the discriminants are distinct variables. -- See: code for computing "matchType" at `elabMatchTypeAndDiscrs` let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : NameSet) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", "); pure (matchStx.setArg 1 discrs) | discr :: discrs => -- Recall that -- matchDiscr := leading_parser optional (ident >> ":") >> termParser let term := discr[1] let addAux : TermElabM Syntax := withFreshMacroScope do let d ← `(_discr); unless isAuxDiscrName d.getId do -- Use assertion? throwError "unexpected internal auxiliary discriminant name" let discrNew := discr.setArg 1 d; let r ← loop discrs (discrsNew.push discrNew) foundFVars `(let _discr := $term; $r) match (← isAtomicDiscr? term) with | some x => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux | none => addAux return some (← loop discrs.toList #[] {}) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user return none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptType matchStx |>.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] match (← isAtomicDiscr? term) with | none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs? | some d => let dType ← inferType d trace[Elab.match] "discr {d} : {dType}" tryPostponeIfMVar dType /- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let _discr := g x match _discr with | ... => ... ``` Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`. Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`. This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => return expectedType | none => mkFreshTypeMVar /- ``` leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let altViews := getMatchAlts stx let matchOptType := getMatchOptType stx elabMatchAux discrStxs altViews matchOptType expectedType private def isPatternVar (stx : Syntax) : TermElabM Bool := do match (← resolveId? stx "pattern") with | none => isAtomicIdent stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => return false | some _ => return !hasMatchPatternAttribute (← getEnv) fName | _ => isAtomicIdent stx | _ => isAtomicIdent stx where isAtomicIdent (stx : Syntax) : Bool := stx.isIdent && stx.getId.eraseMacroScopes.isAtomic -- leading_parser "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do match stx with | `(match $discr:term with | $y:ident => $rhs:term) => if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType? | _ => elabMatchDefault stx expectedType? where elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx; let matchOptType := getMatchOptType stx; if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? builtin_initialize registerTraceClass `Elab.match -- leading_parser:leadPrec "nomatch " >> termParser @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => do match stx with | `(nomatch $discrExpr) => match ← isLocalIdent? discrExpr with | some _ => let expectedType ← waitExpectedType expectedType? let discr := Syntax.node ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux #[discr] #[] mkNullNode expectedType | _ => let stxNew ← `(let _discr := $discrExpr; nomatch _discr) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax end Lean.Elab.Term
142a9b8f079ee5a9975cf63c001e640200ae8466
626e312b5c1cb2d88fca108f5933076012633192
/src/linear_algebra/matrix/nonsingular_inverse.lean
77025e6278d1ab88c65820d2746c20457fd74189
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,267
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baanen, Lu-Ming Zhang -/ import algebra.associated import algebra.regular.smul import linear_algebra.matrix.determinant import tactic.linarith import tactic.ring_exp /-! # Nonsingular inverses In this file, we define an inverse for square matrices of invertible determinant. For matrices that are not square or not of full rank, there is a more general notion of pseudoinverses which we do not consider here. The definition of inverse used in this file is the adjugate divided by the determinant. The adjugate is calculated with Cramer's rule, which we introduce first. The vectors returned by Cramer's rule are given by the linear map `cramer`, which sends a matrix `A` and vector `b` to the vector consisting of the determinant of replacing the `i`th column of `A` with `b` at index `i` (written as `(A.update_column i b).det`). Using Cramer's rule, we can compute for each matrix `A` the matrix `adjugate A`. The entries of the adjugate are the determinants of each minor of `A`. Instead of defining a minor to be `A` with row `i` and column `j` deleted, we replace the `i`th row of `A` with the `j`th basis vector; this has the same determinant as the minor but more importantly equals Cramer's rule applied to `A` and the `j`th basis vector, simplifying the subsequent proofs. We prove the adjugate behaves like `det A • A⁻¹`. Finally, we show that dividing the adjugate by `det A` (if possible), giving a matrix `nonsing_inv A`, will result in a multiplicative inverse to `A`. ## References * https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix ## Tags matrix inverse, cramer, cramer's rule, adjugate -/ namespace matrix universes u v variables {n : Type u} [decidable_eq n] [fintype n] {α : Type v} [comm_ring α] open_locale matrix big_operators open equiv equiv.perm finset section cramer /-! ### `cramer` section Introduce the linear map `cramer` with values defined by `cramer_map`. After defining `cramer_map` and showing it is linear, we will restrict our proofs to using `cramer`. -/ variables (A : matrix n n α) (b : n → α) /-- `cramer_map A b i` is the determinant of the matrix `A` with column `i` replaced with `b`, and thus `cramer_map A b` is the vector output by Cramer's rule on `A` and `b`. If `A ⬝ x = b` has a unique solution in `x`, `cramer_map A` sends the vector `b` to `A.det • x`. Otherwise, the outcome of `cramer_map` is well-defined but not necessarily useful. -/ def cramer_map (i : n) : α := (A.update_column i b).det lemma cramer_map_is_linear (i : n) : is_linear_map α (λ b, cramer_map A b i) := { map_add := det_update_column_add _ _, map_smul := det_update_column_smul _ _ } lemma cramer_is_linear : is_linear_map α (cramer_map A) := begin split; intros; ext i, { apply (cramer_map_is_linear A i).1 }, { apply (cramer_map_is_linear A i).2 } end /-- `cramer A b i` is the determinant of the matrix `A` with column `i` replaced with `b`, and thus `cramer A b` is the vector output by Cramer's rule on `A` and `b`. If `A ⬝ x = b` has a unique solution in `x`, `cramer A` sends the vector `b` to `A.det • x`. Otherwise, the outcome of `cramer` is well-defined but not necessarily useful. -/ def cramer (A : matrix n n α) : (n → α) →ₗ[α] (n → α) := is_linear_map.mk' (cramer_map A) (cramer_is_linear A) lemma cramer_apply (i : n) : cramer A b i = (A.update_column i b).det := rfl lemma cramer_transpose_row_self (i : n) : Aᵀ.cramer (A i) = pi.single i A.det := begin ext j, rw [cramer_apply, pi.single_apply], split_ifs with h, { -- i = j: this entry should be `A.det` subst h, simp only [update_column_transpose, det_transpose, update_row, function.update_eq_self] }, { -- i ≠ j: this entry should be 0 rw [update_column_transpose, det_transpose], apply det_zero_of_row_eq h, rw [update_row_self, update_row_ne (ne.symm h)] } end lemma cramer_row_self (i : n) (h : ∀ j, b j = A j i) : A.cramer b = pi.single i A.det := begin rw [← transpose_transpose A, det_transpose], convert cramer_transpose_row_self Aᵀ i, exact funext h end @[simp] lemma cramer_one : cramer (1 : matrix n n α) = 1 := begin ext i j, convert congr_fun (cramer_row_self (1 : matrix n n α) (pi.single i 1) i _) j, { simp }, { intros j, rw [matrix.one_eq_pi_single, pi.single_comm] } end @[simp] lemma cramer_subsingleton_apply [subsingleton n] (A : matrix n n α) (b : n → α) (i : n) : cramer A b i = b i := by rw [cramer_apply, det_eq_elem_of_subsingleton _ i, update_column_self] lemma cramer_zero [nontrivial n] : cramer (0 : matrix n n α) = 0 := begin ext i j, obtain ⟨j', hj'⟩ : ∃ j', j' ≠ j := exists_ne j, apply det_eq_zero_of_column_eq_zero j', intro j'', simp [update_column_ne hj'], end /-- Use linearity of `cramer` to take it out of a summation. -/ lemma sum_cramer {β} (s : finset β) (f : β → n → α) : ∑ x in s, cramer A (f x) = cramer A (∑ x in s, f x) := (linear_map.map_sum (cramer A)).symm /-- Use linearity of `cramer` and vector evaluation to take `cramer A _ i` out of a summation. -/ lemma sum_cramer_apply {β} (s : finset β) (f : n → β → α) (i : n) : ∑ x in s, cramer A (λ j, f j x) i = cramer A (λ (j : n), ∑ x in s, f j x) i := calc ∑ x in s, cramer A (λ j, f j x) i = (∑ x in s, cramer A (λ j, f j x)) i : (finset.sum_apply i s _).symm ... = cramer A (λ (j : n), ∑ x in s, f j x) i : by { rw [sum_cramer, cramer_apply], congr' with j, apply finset.sum_apply } end cramer section adjugate /-! ### `adjugate` section Define the `adjugate` matrix and a few equations. These will hold for any matrix over a commutative ring, while the `inv` section is specifically for invertible matrices. -/ /-- The adjugate matrix is the transpose of the cofactor matrix. Typically, the cofactor matrix is defined by taking the determinant of minors, i.e. the matrix with a row and column removed. However, the proof of `mul_adjugate` becomes a lot easier if we define the minor as replacing a column with a basis vector, since it allows us to use facts about the `cramer` map. -/ def adjugate (A : matrix n n α) : matrix n n α := λ i, cramer Aᵀ (λ j, if i = j then 1 else 0) lemma adjugate_def (A : matrix n n α) : adjugate A = λ i, cramer Aᵀ (λ j, if i = j then 1 else 0) := rfl lemma adjugate_apply (A : matrix n n α) (i j : n) : adjugate A i j = (A.update_row j (λ j, if i = j then 1 else 0)).det := by { rw adjugate_def, simp only, rw [cramer_apply, update_column_transpose, det_transpose], } lemma adjugate_transpose (A : matrix n n α) : (adjugate A)ᵀ = adjugate (Aᵀ) := begin ext i j, rw [transpose_apply, adjugate_apply, adjugate_apply, update_row_transpose, det_transpose], rw [det_apply', det_apply'], apply finset.sum_congr rfl, intros σ _, congr' 1, by_cases i = σ j, { -- Everything except `(i , j)` (= `(σ j , j)`) is given by A, and the rest is a single `1`. congr; ext j', have := (@equiv.injective _ _ σ j j' : σ j = σ j' → j = j'), rw [update_row_apply, update_column_apply], finish }, { -- Otherwise, we need to show that there is a `0` somewhere in the product. have : (∏ j' : n, update_column A j (λ (i' : n), ite (i = i') 1 0) (σ j') j') = 0, { apply prod_eq_zero (mem_univ j), rw [update_column_self], exact if_neg h }, rw this, apply prod_eq_zero (mem_univ (σ⁻¹ i)), erw [apply_symm_apply σ i, update_row_self], apply if_neg, intro h', exact h ((symm_apply_eq σ).mp h'.symm) } end /-- Since the map `b ↦ cramer A b` is linear in `b`, it must be multiplication by some matrix. This matrix is `A.adjugate`. -/ lemma cramer_eq_adjugate_mul_vec (A : matrix n n α) (b : n → α) : cramer A b = A.adjugate.mul_vec b := begin nth_rewrite 1 ← A.transpose_transpose, rw [← adjugate_transpose, adjugate_def], have : b = ∑ i, (b i) • (λ j, if i = j then 1 else 0), { ext i, simp, }, rw this, ext k, simp [mul_vec, dot_product, mul_comm], end lemma mul_adjugate_apply (A : matrix n n α) (i j k) : A i k * adjugate A k j = cramer Aᵀ (λ j, if k = j then A i k else 0) j := begin erw [←smul_eq_mul, ←pi.smul_apply, ←linear_map.map_smul], congr' with l, rw [pi.smul_apply, smul_eq_mul, mul_boole], end lemma mul_adjugate (A : matrix n n α) : A ⬝ adjugate A = A.det • 1 := begin ext i j, rw [mul_apply, pi.smul_apply, pi.smul_apply, one_apply, smul_eq_mul, mul_boole], simp [mul_adjugate_apply, sum_cramer_apply, cramer_transpose_row_self, pi.single_apply, eq_comm] end lemma adjugate_mul (A : matrix n n α) : adjugate A ⬝ A = A.det • 1 := calc adjugate A ⬝ A = (Aᵀ ⬝ (adjugate Aᵀ))ᵀ : by rw [←adjugate_transpose, ←transpose_mul, transpose_transpose] ... = A.det • 1 : by rw [mul_adjugate (Aᵀ), det_transpose, transpose_smul, transpose_one] /-- `det_adjugate_of_cancel` is an auxiliary lemma for computing `(adjugate A).det`, used in `det_adjugate_eq_one` and `det_adjugate_of_is_unit`. The formula for the determinant of the adjugate of an `n` by `n` matrix `A` is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases. This lemma `det_adjugate_of_cancel` covers the case that `det A` cancels on the left of the equation `A.det * b = A.det ^ n`. -/ lemma det_adjugate_of_cancel {A : matrix n n α} (h : ∀ b, A.det * b = A.det ^ fintype.card n → b = A.det ^ (fintype.card n - 1)) : (adjugate A).det = A.det ^ (fintype.card n - 1) := h (adjugate A).det (calc A.det * (adjugate A).det = (A ⬝ adjugate A).det : (det_mul _ _).symm ... = A.det ^ fintype.card n : by simp [mul_adjugate]) lemma adjugate_subsingleton [subsingleton n] (A : matrix n n α) : adjugate A = 1 := begin ext i j, simp [subsingleton.elim i j, adjugate_apply, det_eq_elem_of_subsingleton _ i] end lemma adjugate_eq_one_of_card_eq_one {A : matrix n n α} (h : fintype.card n = 1) : adjugate A = 1 := begin haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le, exact adjugate_subsingleton _ end @[simp] lemma adjugate_zero (h : 1 < fintype.card n) : adjugate (0 : matrix n n α) = 0 := begin ext i j, obtain ⟨j', hj'⟩ : ∃ j', j' ≠ j := fintype.exists_ne_of_one_lt_card h j, apply det_eq_zero_of_column_eq_zero j', intro j'', simp [update_column_ne hj'], end @[simp] lemma adjugate_one : adjugate (1 : matrix n n α) = 1 := by { ext, simp [adjugate_def, matrix.one_apply] } lemma det_adjugate_eq_one {A : matrix n n α} (h : A.det = 1) : (adjugate A).det = 1 := calc (adjugate A).det = A.det ^ (fintype.card n - 1) : det_adjugate_of_cancel (λ b hb, by simpa [h] using hb) ... = 1 : by rw [h, one_pow] /-- `det_adjugate_of_is_unit` gives the formula for `(adjugate A).det` if `A.det` has an inverse. The formula for the determinant of the adjugate of an `n` by `n` matrix `A` is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases. This lemma `det_adjugate_of_is_unit` covers the case that `det A` has an inverse. -/ lemma det_adjugate_of_is_unit {A : matrix n n α} (h : is_unit A.det) : (adjugate A).det = A.det ^ (fintype.card n - 1) := begin rcases is_unit_iff_exists_inv'.mp h with ⟨a, ha⟩, by_cases card_lt_zero : fintype.card n ≤ 0, { have h : fintype.card n = 0 := by linarith, simp [det_eq_one_of_card_eq_zero h] }, have zero_lt_card : 0 < fintype.card n := by linarith, have n_nonempty : nonempty n := fintype.card_pos_iff.mp zero_lt_card, by_cases card_lt_one : fintype.card n ≤ 1, { have h : fintype.card n = 1 := by linarith, simp [h, adjugate_eq_one_of_card_eq_one h] }, have one_lt_card : 1 < fintype.card n := by linarith, have zero_lt_card_sub_one : 0 < fintype.card n - 1 := (nat.sub_lt_sub_right_iff (refl 1)).mpr one_lt_card, apply det_adjugate_of_cancel, intros b hb, calc b = a * (det A ^ (fintype.card n - 1 + 1)) : by rw [←one_mul b, ←ha, mul_assoc, hb, nat.sub_add_cancel zero_lt_card] ... = a * det A * det A ^ (fintype.card n - 1) : by ring_exp ... = det A ^ (fintype.card n - 1) : by rw [ha, one_mul] end end adjugate section inv /-! ### `inv` section Defines the matrix `nonsing_inv A` and proves it is the inverse matrix of a square matrix `A` as long as `det A` has a multiplicative inverse. -/ variables (A : matrix n n α) (B : matrix n n α) open_locale classical lemma is_unit_det_transpose (h : is_unit A.det) : is_unit Aᵀ.det := by { rw det_transpose, exact h, } /-- The inverse of a square matrix, when it is invertible (and zero otherwise).-/ noncomputable def nonsing_inv : matrix n n α := if h : is_unit A.det then h.unit⁻¹ • A.adjugate else 0 noncomputable instance : has_inv (matrix n n α) := ⟨matrix.nonsing_inv⟩ lemma inv_def (A : matrix n n α) : A⁻¹ = A.nonsing_inv := rfl lemma nonsing_inv_apply_not_is_unit (h : ¬ is_unit A.det) : A⁻¹ = 0 := by rw [inv_def, nonsing_inv, dif_neg h] lemma nonsing_inv_apply (h : is_unit A.det) : A⁻¹ = h.unit⁻¹ • A.adjugate := by rw [inv_def, nonsing_inv, dif_pos h] lemma transpose_nonsing_inv (h : is_unit A.det) : (A⁻¹)ᵀ = (Aᵀ)⁻¹ := begin have h' := A.is_unit_det_transpose h, have dets_eq : h.unit = h'.unit := units.ext (by rw [h.unit_spec, h'.unit_spec, det_transpose]), rw [A.nonsing_inv_apply h, Aᵀ.nonsing_inv_apply h', dets_eq, A.adjugate_transpose.symm], refl, end /-- The `nonsing_inv` of `A` is a right inverse. -/ @[simp] lemma mul_nonsing_inv (h : is_unit A.det) : A ⬝ A⁻¹ = 1 := by rw [A.nonsing_inv_apply h, units.smul_def, mul_smul, mul_adjugate, smul_smul, units.inv_mul_of_eq h.unit_spec, one_smul] /-- The `nonsing_inv` of `A` is a left inverse. -/ @[simp] lemma nonsing_inv_mul (h : is_unit A.det) : A⁻¹ ⬝ A = 1 := calc A⁻¹ ⬝ A = (Aᵀ ⬝ (Aᵀ)⁻¹)ᵀ : by { rw [transpose_mul, Aᵀ.transpose_nonsing_inv (A.is_unit_det_transpose h), transpose_transpose], } ... = 1ᵀ : by { rw Aᵀ.mul_nonsing_inv, exact A.is_unit_det_transpose h, } ... = 1 : transpose_one @[simp] lemma nonsing_inv_det (h : is_unit A.det) : A⁻¹.det * A.det = 1 := by rw [←det_mul, A.nonsing_inv_mul h, det_one] lemma is_unit_nonsing_inv_det (h : is_unit A.det) : is_unit A⁻¹.det := is_unit_of_mul_eq_one _ _ (A.nonsing_inv_det h) @[simp] lemma nonsing_inv_nonsing_inv (h : is_unit A.det) : (A⁻¹)⁻¹ = A := calc (A⁻¹)⁻¹ = 1 ⬝ (A⁻¹)⁻¹ : by rw matrix.one_mul ... = A ⬝ A⁻¹ ⬝ (A⁻¹)⁻¹ : by rw A.mul_nonsing_inv h ... = A : by { rw [matrix.mul_assoc, (A⁻¹).mul_nonsing_inv (A.is_unit_nonsing_inv_det h), matrix.mul_one], } @[simp] lemma is_unit_nonsing_inv_det_iff {A : matrix n n α} : is_unit A⁻¹.det ↔ is_unit A.det := begin refine ⟨λ h, _, is_unit_nonsing_inv_det _⟩, nontriviality α, casesI is_empty_or_nonempty n, { simp }, contrapose! h, rw [nonsing_inv_apply_not_is_unit _ h, det_zero], { simp }, { apply_instance } end /-- If `A.det` has a constructive inverse, produce one for `A`. -/ def invertible_of_det_invertible [invertible A.det] : invertible A := { inv_of := ⅟A.det • A.adjugate, mul_inv_of_self := by rw [mul_smul_comm, matrix.mul_eq_mul, mul_adjugate, smul_smul, inv_of_mul_self, one_smul], inv_of_mul_self := by rw [smul_mul_assoc, matrix.mul_eq_mul, adjugate_mul, smul_smul, inv_of_mul_self, one_smul] } /-- `A.det` is invertible if `A` has a left inverse. -/ def det_invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A.det := { inv_of := B.det, mul_inv_of_self := by rw [mul_comm, ← det_mul, h, det_one], inv_of_mul_self := by rw [← det_mul, h, det_one] } /-- `A.det` is invertible if `A` has a right inverse. -/ def det_invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A.det := { inv_of := B.det, mul_inv_of_self := by rw [← det_mul, h, det_one], inv_of_mul_self := by rw [mul_comm, ← det_mul, h, det_one] } /-- If `A` has a constructive inverse, produce one for `A.det`. -/ def det_invertible_of_invertible [invertible A] : invertible A.det := det_invertible_of_left_inverse A (⅟A) (inv_of_mul_self _) /-- Given a proof that `A.det` has a constructive inverse, lift `A` to `units (matrix n n α)`-/ def unit_of_det_invertible [invertible A.det] : units (matrix n n α) := @unit_of_invertible _ _ A (invertible_of_det_invertible A) /-- A matrix whose determinant is a unit is itself a unit. This is a noncomputable version of `matrix.units_of_det_invertible`, with the inverse defeq to `matrix.nonsing_inv`. -/ noncomputable def nonsing_inv_unit (h : is_unit A.det) : units (matrix n n α) := { val := A, inv := A⁻¹, val_inv := by { rw matrix.mul_eq_mul, apply A.mul_nonsing_inv h, }, inv_val := by { rw matrix.mul_eq_mul, apply A.nonsing_inv_mul h, } } lemma unit_of_det_invertible_eq_nonsing_inv_unit [invertible A.det] : unit_of_det_invertible A = nonsing_inv_unit A (is_unit_of_invertible _) := by { ext, refl } /-- When lowered to a prop, `matrix.det_invertible_of_invertible` and `matrix.invertible_of_det_invertible` form an `iff`. -/ lemma is_unit_iff_is_unit_det : is_unit A ↔ is_unit A.det := begin split; rintros ⟨x, hx⟩; refine @is_unit_of_invertible _ _ _ (id _), { haveI : invertible A := hx.rec x.invertible, apply det_invertible_of_invertible, }, { haveI : invertible A.det := hx.rec x.invertible, apply invertible_of_det_invertible, }, end /- `is_unit_of_invertible A` converts the "stronger" condition `invertible A` to proposition `is_unit A`. -/ /-- `matrix.is_unit_det_of_invertible` converts `invertible A` to `is_unit A.det`. -/ lemma is_unit_det_of_invertible [invertible A] : is_unit A.det := @is_unit_of_invertible _ _ _(det_invertible_of_invertible A) @[simp] lemma inv_eq_nonsing_inv_of_invertible [invertible A] : ⅟ A = A⁻¹ := begin suffices : is_unit A, { rw [←this.mul_left_inj, inv_of_mul_self, matrix.mul_eq_mul, nonsing_inv_mul], rwa ←is_unit_iff_is_unit_det }, exact is_unit_of_invertible _ end variables {A} {B} /- `is_unit.invertible` lifts the proposition `is_unit A` to a constructive inverse of `A`. -/ /-- "Lift" the proposition `is_unit A.det` to a constructive inverse of `A`. -/ noncomputable def invertible_of_is_unit_det (h : is_unit A.det) : invertible A := ⟨A⁻¹, nonsing_inv_mul A h, mul_nonsing_inv A h⟩ lemma is_unit_det_of_left_inverse (h : B ⬝ A = 1) : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_left_inverse _ _ h) lemma is_unit_det_of_right_inverse (h : A ⬝ B = 1) : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_right_inverse _ _ h) lemma nonsing_inv_left_right (h : A ⬝ B = 1) : B ⬝ A = 1 := begin have h' : is_unit B.det := is_unit_det_of_left_inverse h, calc B ⬝ A = (B ⬝ A) ⬝ (B ⬝ B⁻¹) : by simp only [h', matrix.mul_one, mul_nonsing_inv] ... = B ⬝ ((A ⬝ B) ⬝ B⁻¹) : by simp only [matrix.mul_assoc] ... = B ⬝ B⁻¹ : by simp only [h, matrix.one_mul] ... = 1 : mul_nonsing_inv B h', end lemma nonsing_inv_right_left (h : B ⬝ A = 1) : A ⬝ B = 1 := nonsing_inv_left_right h /-- If matrix A is left invertible, then its inverse equals its left inverse. -/ lemma inv_eq_left_inv (h : B ⬝ A = 1) : A⁻¹ = B := begin have h1 := (is_unit_det_of_left_inverse h), have h2 := matrix.invertible_of_is_unit_det h1, have := @inv_of_eq_left_inv (matrix n n α) (infer_instance) A B h2 h, simp* at *, end /-- If matrix A is right invertible, then its inverse equals its right inverse. -/ lemma inv_eq_right_inv (h : A ⬝ B = 1) : A⁻¹ = B := begin have h1 := (is_unit_det_of_right_inverse h), have h2 := matrix.invertible_of_is_unit_det h1, have := @inv_of_eq_right_inv (matrix n n α) (infer_instance) A B h2 h, simp* at *, end /-- We can construct an instance of invertible A if A has a left inverse. -/ def invertible_of_left_inverse (h: B ⬝ A = 1) : invertible A := ⟨B, h, nonsing_inv_right_left h⟩ /-- We can construct an instance of invertible A if A has a right inverse. -/ def invertible_of_right_inverse (h: A ⬝ B = 1) : invertible A := ⟨B, nonsing_inv_left_right h, h⟩ section inv_eq_inv variables {C : matrix n n α} /-- The left inverse of matrix A is unique when existing. -/ lemma left_inv_eq_left_inv (h: B ⬝ A = 1) (g: C ⬝ A = 1) : B = C := by rw [←(inv_eq_left_inv h), ←(inv_eq_left_inv g)] /-- The right inverse of matrix A is unique when existing. -/ lemma right_inv_eq_right_inv (h: A ⬝ B = 1) (g: A ⬝ C = 1) : B = C := by rw [←(inv_eq_right_inv h), ←(inv_eq_right_inv g)] /-- The right inverse of matrix A equals the left inverse of A when they exist. -/ lemma right_inv_eq_left_inv (h: A ⬝ B = 1) (g: C ⬝ A = 1) : B = C := by rw [←(inv_eq_right_inv h), ←(inv_eq_left_inv g)] lemma inv_inj (h : A⁻¹ = B⁻¹) (h' : is_unit A.det) : A = B := begin refine left_inv_eq_left_inv (mul_nonsing_inv _ h') _, rw h, refine mul_nonsing_inv _ _, rwa [←is_unit_nonsing_inv_det_iff, ←h, is_unit_nonsing_inv_det_iff] end end inv_eq_inv variable (A) @[simp] lemma mul_inv_of_invertible [invertible A] : A ⬝ A⁻¹ = 1 := mul_nonsing_inv A (is_unit_det_of_invertible A) @[simp] lemma inv_mul_of_invertible [invertible A] : A⁻¹ ⬝ A = 1 := nonsing_inv_mul A (is_unit_det_of_invertible A) @[simp] lemma inv_zero : (0 : matrix n n α)⁻¹ = 0 := begin casesI (subsingleton_or_nontrivial α) with ht ht, { simp }, cases (fintype.card n).zero_le.eq_or_lt with hc hc, { rw [eq_comm, fintype.card_eq_zero_iff] at hc, haveI := hc, ext i, exact (is_empty.false i).elim }, { have hn : nonempty n := fintype.card_pos_iff.mp hc, refine nonsing_inv_apply_not_is_unit _ _, simp [hn] }, end @[simp] lemma inv_one : (1 : matrix n n α)⁻¹ = 1 := inv_eq_left_inv (by simp) lemma inv_smul (k : α) [invertible k] (h : is_unit A.det) : (k • A)⁻¹ = ⅟k • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) lemma inv_smul' (k : units α) (h : is_unit A.det) : (k • A)⁻¹ = k⁻¹ • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) lemma _root_.is_unit.coe_inv_mul {α : Type*} [monoid α] {a : α} (h : is_unit a) : ↑(h.unit)⁻¹ * a = 1 := begin convert units.mul_inv _, simp [h.unit_spec] end lemma _root_.is_unit.mul_coe_inv {α : Type*} [monoid α] {a : α} (h : is_unit a) : a * ↑(h.unit)⁻¹ = 1 := begin convert units.mul_inv _, simp [h.unit_spec] end lemma _root_.is_unit.inv_smul {α : Type*} [monoid α] {a : α} (h : is_unit a) : (h.unit)⁻¹ • a = 1 := h.coe_inv_mul lemma inv_adjugate (A : matrix n n α) (h : is_unit A.det) : (adjugate A)⁻¹ = h.unit⁻¹ • A := begin refine inv_eq_left_inv _, rw [smul_mul, mul_adjugate, units.smul_def, smul_smul, h.coe_inv_mul, one_smul] end @[simp] lemma inv_inv_inv (A : matrix n n α) : A⁻¹⁻¹⁻¹ = A⁻¹ := begin by_cases h : is_unit A.det, { rw [nonsing_inv_nonsing_inv _ h] }, { simp [nonsing_inv_apply_not_is_unit _ h] } end lemma mul_inv_rev (A B : matrix n n α) : (A ⬝ B)⁻¹ = B⁻¹ ⬝ A⁻¹ := begin by_cases h : is_unit (A ⬝ B).det, { refine inv_eq_left_inv _, rw det_mul at h, rw [←matrix.mul_assoc, matrix.mul_assoc _ _ A, nonsing_inv_mul _ (is_unit_of_mul_is_unit_left h), matrix.mul_one, nonsing_inv_mul _ (is_unit_of_mul_is_unit_right h)] }, { rw nonsing_inv_apply_not_is_unit _ h, rw det_mul at h, have : ¬ is_unit A.det ∨ ¬ is_unit B.det, { contrapose! h, exact h.left.mul h.right }, cases this with h' h'; simp [nonsing_inv_apply_not_is_unit _ h'] } end lemma ring_hom.map_adjugate {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (M : matrix n n R) : f.map_matrix M.adjugate = matrix.adjugate (f.map_matrix M) := begin ext i k, have : (λ (j : n), ite (i = j) (1 : S) 0) = f ∘ (λ (j : n), ite (i = j) 1 0), { ext, simp [apply_ite f] }, rw [adjugate_apply, ring_hom.map_matrix_apply, map_apply, ring_hom.map_matrix_apply, this, ←map_update_row, ←ring_hom.map_matrix_apply, ←ring_hom.map_det, ←adjugate_apply] end lemma is_regular_of_is_left_regular_det {A : matrix n n α} (hA : is_left_regular A.det) : is_regular A := begin split, { intros B C h, refine hA.matrix _, rw [←matrix.one_mul B, ←matrix.one_mul C, ←matrix.smul_mul, ←matrix.smul_mul, ←adjugate_mul, matrix.mul_assoc, matrix.mul_assoc, ←mul_eq_mul A, h, mul_eq_mul] }, { intros B C h, simp only [mul_eq_mul] at h, refine hA.matrix _, rw [←matrix.mul_one B, ←matrix.mul_one C, ←matrix.mul_smul, ←matrix.mul_smul, ←mul_adjugate, ←matrix.mul_assoc, ←matrix.mul_assoc, h] } end lemma adjugate_mul_distrib_aux (A B : matrix n n α) (hA : is_left_regular A.det) (hB : is_left_regular B.det) : adjugate (A ⬝ B) = adjugate B ⬝ adjugate A := begin have hAB : is_left_regular (A ⬝ B).det, { rw [det_mul], exact hA.mul hB }, refine (is_regular_of_is_left_regular_det hAB).left _, rw [mul_eq_mul, mul_adjugate, mul_eq_mul, matrix.mul_assoc, ←matrix.mul_assoc B, mul_adjugate, smul_mul, matrix.one_mul, mul_smul, mul_adjugate, smul_smul, mul_comm, ←det_mul] end end inv /-- One form of Cramer's rule -/ @[simp] lemma det_smul_inv_mul_vec_eq_cramer (A : matrix n n α) (b : n → α) (h : is_unit A.det) : A.det • A⁻¹.mul_vec b = cramer A b := begin rw [cramer_eq_adjugate_mul_vec, A.nonsing_inv_apply h, ← smul_mul_vec_assoc, units.smul_def, smul_smul, h.mul_coe_inv, one_smul] end /-- A stronger form of **Cramer's rule** that allows us to solve some instances of `A ⬝ x = b` even if the determinant is not a unit. A sufficient (but still not necessary) condition is that `A.det` divides `b`. -/ @[simp] lemma mul_vec_cramer (A : matrix n n α) (b : n → α) : A.mul_vec (cramer A b) = A.det • b := by rw [cramer_eq_adjugate_mul_vec, mul_vec_mul_vec, mul_adjugate, smul_mul_vec_assoc, one_mul_vec] /-- If `M` has a nonzero determinant, then `M` as a bilinear form on `n → A` is nondegenerate. See also `bilin_form.nondegenerate_of_det_ne_zero'` and `bilin_form.nondegenerate_of_det_ne_zero`. -/ theorem nondegenerate_of_det_ne_zero {A : Type*} [integral_domain A] {M : matrix n n A} (hM : M.det ≠ 0) (v : n → A) (hv : ∀ w, matrix.dot_product v (mul_vec M w) = 0) : v = 0 := begin ext i, specialize hv (M.cramer (pi.single i 1)), refine (mul_eq_zero.mp _).resolve_right hM, convert hv, simp only [mul_vec_cramer M (pi.single i 1), dot_product, pi.smul_apply, smul_eq_mul], rw [finset.sum_eq_single i, pi.single_eq_same, mul_one], { intros j _ hj, simp [hj] }, { intros, have := finset.mem_univ i, contradiction } end end matrix
55ac8cf3ddb88e02d28696e1d8c74f079db23ad3
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/algebra/module/basic.lean
3b45ac125715f81954ee7c3356f55b68a4205828
[ "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
19,820
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.big_operators.basic import algebra.group.hom import algebra.ring.basic import data.rat.cast import group_theory.group_action.group import tactic.nth_rewrite /-! # Modules over a ring In this file we define * `semimodule R M` : an additive commutative monoid `M` is a `semimodule` over a `semiring` `R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. * `module R M` : same as `semimodule R M` but assumes that `R` is a `ring` and `M` is an additive commutative group. * `vector_space k M` : same as `semimodule k M` and `module k M` but assumes that `k` is a `field` and `M` is an additive commutative group. * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. ## Implementation notes * `vector_space` and `module` are abbreviations for `semimodule R M`. ## Tags semimodule, module, vector space -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ @[protect_proj] class semimodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) section add_comm_monoid variables [semiring R] [add_comm_monoid M] [semimodule R M] (r s : R) (x y : M) theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (R) @[simp] theorem zero_smul : (0 : R) • x = 0 := semimodule.zero_smul x theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] theorem two_smul' : (2 : R) • x = bit0 x := two_smul R x /-- Pullback a `semimodule` structure along an injective additive monoid homomorphism. -/ protected def function.injective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul], zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero], .. hf.distrib_mul_action f smul } /-- Pushforward a `semimodule` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩, simp only [add_smul, ← smul, ← f.map_add] }, zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] }, .. hf.distrib_mul_action f smul } variable (M) /-- `(•)` as an `add_monoid_hom`. -/ def smul_add_hom : R →+ M →+ M := { to_fun := const_smul_hom M, map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul] } variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_list_sum l lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_multiset_sum l lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : (∑ i in s, f i) • x = (∑ i in s, (f i) • x) := ((smul_add_hom R M).flip x).map_sum f s end add_comm_monoid variables (R) /-- An `add_comm_monoid` that is a `semimodule` over a `ring` carries a natural `add_comm_group` structure. -/ def semimodule.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [semimodule R M] : add_comm_group M := { neg := λ a, (-1 : R) • a, add_left_neg := λ a, show (-1 : R) • a + a = 0, by { nth_rewrite 1 ← one_smul _ a, rw [← add_smul, add_left_neg, zero_smul] }, ..(infer_instance : add_comm_monoid M), } variables {R} section add_comm_group variables (R M) [semiring R] [add_comm_group M] /-- A structure containing most informations as in a semimodule, except the fields `zero_smul` and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`, this provides a way to construct a semimodule structure by checking less properties, in `semimodule.of_core`. -/ @[nolint has_inhabited_instance] structure semimodule.core extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) variables {R M} /-- Define `semimodule` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `semimodule.core`, when the underlying space is an `add_comm_group`. -/ def semimodule.of_core (H : semimodule.core R M) : semimodule R M := by letI := H.to_has_scalar; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero, ..H } end add_comm_group /-- Modules are defined as an `abbreviation` for semimodules, if the base semiring is a ring. (A previous definition made `module` a structure defined to be `semimodule`.) This has as advantage that modules are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for modules as well. A cosmetic disadvantage is that one can not extend modules as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "module definition" /-- A module is the same as a semimodule, except the scalar semiring is actually a ring. This is the traditional generalization of spaces like `ℤ^n`, which have a natural addition operation and a way to multiply them by elements of a ring, but no multiplication operation between vectors. -/ abbreviation module (R : Type u) (M : Type v) [ring R] [add_comm_group M] := semimodule R M /-- To prove two semimodule structures on a fixed `add_comm_monoid` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `semimodule ℕ M` and `module ℤ M` are subsingletons. @[ext] lemma semimodule_ext {R : Type*} [semiring R] {M : Type*} [add_comm_monoid M] (P Q : semimodule R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ }, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E] {c : R} {x : E} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨λ h, or_iff_not_imp_left.2 $ λ hc, (units.mk0 c hc).smul_eq_zero.1 h, λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩ end module /-- A semimodule over a `subsingleton` semiring is a `subsingleton`. We cannot register this as an instance because Lean has no way to guess `R`. -/ theorem semimodule.subsingleton (R M : Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [semimodule R M] : subsingleton M := ⟨λ x y, by rw [← one_smul R x, ← one_smul R y, subsingleton.elim (1:R) 0, zero_smul, zero_smul]⟩ @[priority 910] -- see Note [lower instance priority] instance semiring.to_semimodule [semiring R] : semimodule R R := { 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 } @[simp] lemma smul_eq_mul [semiring R] {a a' : R} : a • a' = a * a' := rfl /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_semimodule [semiring R] [semiring S] (f : R →+* S) : semimodule R S := { 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 [f.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul], zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul], smul_zero := λ r, mul_zero (f r) } /-- Vector spaces are defined as an `abbreviation` for semimodules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "vector space definition" /-- 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. -/ abbreviation vector_space (R : Type u) (M : Type v) [field R] [add_comm_group M] := semimodule R M section add_comm_monoid variables [semiring R] [add_comm_monoid M] [semimodule R M] /-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/ -- We don't make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℕ`. def add_comm_monoid.nat_semimodule : semimodule ℕ M := { smul := nsmul, smul_add := λ _ _ _, nsmul_add _ _ _, add_smul := λ _ _ _, add_nsmul _ _ _, mul_smul := λ _ _ _, mul_nsmul _ _ _, one_smul := one_nsmul, zero_smul := zero_nsmul, smul_zero := nsmul_zero } section local attribute [instance] add_comm_monoid.nat_semimodule /-- `nsmul` is defined as the `smul` action of `add_comm_monoid.nat_semimodule`. -/ lemma nsmul_def (n : ℕ) (x : M) : n •ℕ x = n • x := rfl end section variables (R) /-- `nsmul` is equal to any other semimodule structure via a cast. -/ lemma nsmul_eq_smul_cast (n : ℕ) (b : M) : n •ℕ b = (n : R) • b := begin rw nsmul_def, induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { rw [nat.succ_eq_add_one, nat.cast_succ, add_smul, add_smul, one_smul, ih, one_smul] } end end /-- `nsmul` is equal to any `ℕ`-semimodule structure. -/ lemma nsmul_eq_smul [semimodule ℕ M] (n : ℕ) (b : M) : n •ℕ b = n • b := by rw [nsmul_eq_smul_cast ℕ, n.cast_id] /-- All `ℕ`-semimodule structures are equal. -/ instance add_comm_monoid.nat_semimodule.subsingleton : subsingleton (semimodule ℕ M) := ⟨λ P Q, by { ext n, rw [←nsmul_eq_smul, ←nsmul_eq_smul], }⟩ /-- Note this does not depend on the `nat_semimodule` definition above, to avoid issues when diamonds occur in finding `semimodule ℕ M` instances. -/ instance add_comm_monoid.nat_is_scalar_tower [semimodule ℕ R] [semimodule ℕ M] : is_scalar_tower ℕ R M := { smul_assoc := λ n x y, nat.rec_on n (by simp only [zero_smul]) (λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ih]) } instance add_comm_monoid.nat_smul_comm_class [semimodule ℕ M] : smul_comm_class ℕ R M := { smul_comm := λ n r m, nat.rec_on n (by simp only [zero_smul, smul_zero]) (λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ←ih, smul_add]) } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_comm_monoid.nat_smul_comm_class' [semimodule ℕ M] : smul_comm_class R ℕ M := smul_comm_class.symm _ _ _ end add_comm_monoid section add_comm_group variables [semiring S] [ring R] [add_comm_group M] [semimodule S M] [semimodule R M] /-- The natural ℤ-module structure on any `add_comm_group`. -/ -- We don't immediately make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℤ`. -- We do turn it into a global instance, but only at the end of this file, -- and I remain dubious whether this is a good idea. def add_comm_group.int_module : 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 } section local attribute [instance] add_comm_group.int_module /-- `gsmul` is defined as the `smul` action of `add_comm_group.int_module`. -/ lemma gsmul_def (n : ℤ) (x : M) : gsmul n x = n • x := rfl end section variables (R) /-- `gsmul` is equal to any other module structure via a cast. -/ lemma gsmul_eq_smul_cast (n : ℤ) (b : M) : gsmul n b = (n : R) • b := begin rw gsmul_def, induction n using int.induction_on with p hp n hn, { rw [int.cast_zero, zero_smul, zero_smul] }, { rw [int.cast_add, int.cast_one, add_smul, add_smul, one_smul, one_smul, hp] }, { rw [int.cast_sub, int.cast_one, sub_smul, sub_smul, one_smul, one_smul, hn] }, end end /-- `gsmul` is equal to any `ℤ`-module structure. -/ lemma gsmul_eq_smul [semimodule ℤ M] (n : ℤ) (b : M) : n •ℤ b = n • b := by rw [gsmul_eq_smul_cast ℤ, n.cast_id] /-- All `ℤ`-module structures are equal. -/ instance add_comm_group.int_module.subsingleton : subsingleton (semimodule ℤ M) := ⟨λ P Q, by { ext n, rw [←gsmul_eq_smul, ←gsmul_eq_smul], }⟩ instance add_comm_group.int_is_scalar_tower [semimodule ℤ R] [semimodule ℤ M] : is_scalar_tower ℤ R M := { smul_assoc := λ n x y, int.induction_on n (by simp only [zero_smul]) (λ n ih, by simp only [one_smul, add_smul, ih]) (λ n ih, by simp only [one_smul, sub_smul, ih]) } instance add_comm_group.int_smul_comm_class [semimodule ℤ M] : smul_comm_class ℤ S M := { smul_comm := λ n x y, int.induction_on n (by simp only [zero_smul, smul_zero]) (λ n ih, by simp only [one_smul, add_smul, smul_add, ih]) (λ n ih, by simp only [one_smul, sub_smul, smul_sub, ih]) } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_comm_group.int_smul_comm_class' [semimodule ℤ M] : smul_comm_class S ℤ M := smul_comm_class.symm _ _ _ end add_comm_group namespace add_monoid_hom -- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here -- come from whatever the local `module ℤ` structure actually is. lemma map_int_module_smul [add_comm_group M] [add_comm_group M₂] [module ℤ M] [module ℤ M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a := by simp only [←gsmul_eq_smul, f.map_gsmul] lemma map_int_cast_smul [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [←gsmul_eq_smul_cast, f.map_gsmul] lemma map_nat_cast_smul [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [←nsmul_eq_smul_cast, f.map_nsmul] lemma map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x @[simp] lemma nat_smul_apply [add_monoid M] [add_comm_monoid M₂] [semimodule ℕ (M →+ M₂)] [semimodule ℕ M₂] (n : ℕ) (f : M →+ M₂) (a : M) : (n • f) a = n • (f a) := begin induction n with n IH, { simp only [zero_smul, zero_apply] }, { simp only [nat.succ_eq_add_one, add_smul, IH, one_smul, add_apply] } end @[simp] lemma int_smul_apply [add_monoid M] [add_comm_group M₂] [module ℤ (M →+ M₂)] [module ℤ M₂] (n : ℤ) (f : M →+ M₂) (a : M) : (n • f) a = n • (f a) := begin apply int.induction_on' n 0, { simp only [zero_smul, zero_apply] }, all_goals { intros k hk IH, simp only [add_smul, sub_smul, IH, one_smul, add_apply, sub_apply] } end end add_monoid_hom section module_division_ring /-! Some tests for the vanishing of elements in modules over division rings. -/ variables (R) [division_ring R] [add_comm_group M] [module R M] lemma smul_nat_eq_zero [semimodule ℕ M] [char_zero R] {v : M} {n : ℕ} : n • v = 0 ↔ n = 0 ∨ v = 0 := by { rw [←nsmul_eq_smul, nsmul_eq_smul_cast R, smul_eq_zero], simp } lemma eq_zero_of_smul_two_eq_zero [semimodule ℕ M] [char_zero R] {v : M} (hv : 2 • v = 0) : v = 0 := ((smul_nat_eq_zero R).mp hv).resolve_left (by norm_num) lemma eq_zero_of_eq_neg [char_zero R] {v : M} (hv : v = - v) : v = 0 := begin -- any semimodule will do haveI : semimodule ℕ M := add_comm_monoid.nat_semimodule, refine eq_zero_of_smul_two_eq_zero R _, rw ←nsmul_eq_smul, convert add_eq_zero_iff_eq_neg.mpr hv, abel end lemma ne_neg_of_ne_zero [char_zero R] {v : R} (hv : v ≠ 0) : v ≠ -v := λ h, have semimodule ℕ R := add_comm_monoid.nat_semimodule, by exactI hv (eq_zero_of_eq_neg R h) end module_division_ring -- We finally turn on these instances globally. By doing this here, we ensure that none of the -- lemmas about nat semimodules above are specific to these instances. attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module
6b32b10f3a64e101b72d0fb3b97c5c320359d29d
46125763b4dbf50619e8846a1371029346f4c3db
/src/tactic/linarith.lean
2595e49ad106841d9250bdc70e94e7dc4e6de343
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
33,083
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.ring data.nat.gcd data.list.defs meta.rb_map data.tree /-! A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination. `linarith` is (in principle) complete for ℚ and ℝ. It is not complete for non-dense orders, i.e. ℤ. @TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains @TODO: delay proofs of denominator normalization and nat casting until after contradiction is found -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) open native namespace linarith section lemmas lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0] lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0] lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff] lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le] lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt] lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 := by simp * lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 := by simp * lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 := by simp * lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 := by simp * lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 := by simp * lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : b > 0) : b * a < 0 := have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha, neg_of_neg_pos (by simpa) lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : b > 0) : b * a ≤ 0 := have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha, (by simpa) lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b > 0) : b * a = 0 := by simp * lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b := le_antisymm (le_of_not_gt h2) (le_of_not_gt h1) lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *] lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *, sub_eq_add_neg] lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp * private meta def apnn : tactic unit := `[norm_num] lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 := have h3 : n1 * n2 = k, from h3, by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) : k * (e1 / e2) = t1 := by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul] end lemmas section datatypes @[derive decidable_eq, derive inhabited] inductive ineq | eq | le | lt open ineq def ineq.max : ineq → ineq → ineq | eq a := a | le a := a | lt a := lt def ineq.is_lt : ineq → ineq → bool | eq le := tt | eq lt := tt | le lt := tt | _ _ := ff def ineq.to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" instance : has_to_string ineq := ⟨ineq.to_string⟩ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is coeffs.keys.sum (λ i, coeffs.find i * Var[i]). str determines the direction of the comparison -- is it < 0, ≤ 0, or = 0? -/ @[derive _root_.inhabited] meta structure comp := (str : ineq) (coeffs : rb_map ℕ int) meta inductive comp_source | assump : ℕ → comp_source | add : comp_source → comp_source → comp_source | scale : ℕ → comp_source → comp_source meta def comp_source.flatten : comp_source → rb_map ℕ ℕ | (comp_source.assump n) := mk_rb_map.insert n 1 | (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2) | (comp_source.scale n c) := (comp_source.flatten c).map (λ v, v * n) meta def comp_source.to_string : comp_source → string | (comp_source.assump e) := to_string e | (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2 | (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c meta instance comp_source.has_to_format : has_to_format comp_source := ⟨λ a, comp_source.to_string a⟩ meta structure pcomp := (c : comp) (src : comp_source) meta def map_lt (m1 m2 : rb_map ℕ int) : bool := list.lex (prod.lex (<) (<)) m1.to_list m2.to_list -- make more efficient meta def comp.lt (c1 c2 : comp) : bool := (c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩ meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩ -- short-circuit type class inference meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp → pcomp → Prop) := by apply_instance meta def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a meta def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.map ((*) (n : ℤ)) } meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp := ⟨c.c.scale n, comp_source.scale n c.src⟩ meta def pcomp.add (c1 c2 : pcomp) : pcomp := ⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩ meta instance pcomp.to_format : has_to_format pcomp := ⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩ meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs⟩ end datatypes section fm_elim /-- If c1 and c2 both contain variable a with opposite coefficients, produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/ meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ × comp) := let v1 := c1.coeff_of a, v2 := c2.coeff_of a in if v1 * v2 < 0 then let vlcm := nat.lcm v1.nat_abs v2.nat_abs, v1' := vlcm / v1.nat_abs, v2' := vlcm / v2.nat_abs in some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩ else none meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp := do (n1, n2, c) ← elim_var p1.c p2.c a, return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp := if ¬ p.c.coeffs.contains a then mk_rb_set.insert p else comps.fold mk_rb_set $ λ pc s, match pelim_var p pc a with | some pc := s.insert pc | none := s end /-- The state for the elimination monad. vars: the set of variables present in comps comps: a set of comparisons inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, ≤, =} 0, indexed by ℕ. has_false: stores a pcomp of 0 < 0 if one has been found TODO: is it more efficient to store comps as a list, to avoid comparisons? -/ meta structure linarith_structure := (vars : rb_set ℕ) (comps : rb_set pcomp) @[reducible] meta def linarith_monad := state_t linarith_structure (except_t pcomp id) meta instance : monad linarith_monad := state_t.monad meta instance : monad_except pcomp linarith_monad := state_t.monad_except pcomp meta def get_vars : linarith_monad (rb_set ℕ) := linarith_structure.vars <$> get meta def get_var_list : linarith_monad (list ℕ) := rb_set.to_list <$> get_vars meta def get_comps : linarith_monad (rb_set pcomp) := linarith_structure.comps <$> get meta def validate : linarith_monad unit := do ⟨_, comps⟩ ← get, match comps.to_list.find (λ p : pcomp, p.is_contr) with | none := return () | some c := throw c end meta def update (vars : rb_set ℕ) (comps : rb_set pcomp) : linarith_monad unit := state_t.put ⟨vars, comps⟩ >> validate meta def monad.elim_var (a : ℕ) : linarith_monad unit := do vs ← get_vars, when (vs.contains a) $ do comps ← get_comps, let cs' := comps.fold mk_rb_set (λ p s, s.union (elim_with_set a p comps)), update (vs.erase a) cs' meta def elim_all_vars : linarith_monad unit := get_var_list >>= list.mmap' monad.elim_var end fm_elim section parse open ineq tactic meta def map_of_expr_mul_aux (c1 c2 : rb_map ℕ ℤ) : option (rb_map ℕ ℤ) := match c1.keys, c2.keys with | [0], _ := some $ c2.scale (c1.zfind 0) | _, [0] := some $ c1.scale (c2.zfind 0) | [], _ := some mk_rb_map | _, [] := some mk_rb_map | _, _ := none end meta def list.mfind {α} (tac : α → tactic unit) : list α → tactic α | [] := failed | (h::t) := tac h >> return h <|> list.mfind t meta def rb_map.find_defeq (red : transparency) {v} (m : expr_map v) (e : expr) : tactic v := prod.snd <$> list.mfind (λ p, is_def_eq e p.1 red) m.to_list /-- Turns an expression into a map from ℕ to ℤ, for use in a comp object. The expr_map ℕ argument identifies which expressions have already been assigned numbers. Returns a new map. -/ meta def map_of_expr (red : transparency) : expr_map ℕ → expr → tactic (expr_map ℕ × rb_map ℕ ℤ) | m e@`(%%e1 * %%e2) := (do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, mp ← map_of_expr_mul_aux comp1 comp2, return (m', mp)) <|> (do k ← rb_map.find_defeq red m e, return (m, mk_rb_map.insert k 1)) <|> (let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1)) | m `(%%e1 + %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add comp2) | m `(%%e1 - %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add (comp2.scale (-1))) | m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1)) | m e := match e.to_int with | some 0 := return ⟨m, mk_rb_map⟩ | some z := return ⟨m, mk_rb_map.insert 0 z⟩ | none := (do k ← rb_map.find_defeq red m e, return (m, mk_rb_map.insert k 1)) <|> (let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1)) end meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none meta def to_comp (red : transparency) (e : expr) (m : expr_map ℕ) : tactic (comp × expr_map ℕ) := do (iq, e) ← parse_into_comp_and_expr e, (m', comp') ← map_of_expr red m e, return ⟨⟨iq, comp'⟩, m'⟩ meta def to_comp_fold (red : transparency) : expr_map ℕ → list expr → tactic (list (option comp) × expr_map ℕ) | m [] := return ([], m) | m (h::t) := (do (c, m') ← to_comp red h m, (l, mp) ← to_comp_fold m' t, return (c::l, mp)) <|> (do (l, mp) ← to_comp_fold m t, return (none::l, mp)) /-- Takes a list of proofs of props of the form t {<, ≤, =} 0, and creates a linarith_structure. -/ meta def mk_linarith_structure (red : transparency) (l : list expr) : tactic (linarith_structure × rb_map ℕ (expr × expr)) := do pftps ← l.mmap infer_type, (l', map) ← to_comp_fold red mk_rb_map pftps, let lz := list.enum $ ((l.zip pftps).zip l').filter_map (λ ⟨a, b⟩, prod.mk a <$> b), let prmap := rb_map.of_list $ lz.map (λ ⟨n, x⟩, (n, x.1)), let vars : rb_set ℕ := rb_map.set_of_list $ list.range map.size.succ, let pc : rb_set pcomp := rb_map.set_of_list $ lz.map (λ ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩), return (⟨vars, pc⟩, prmap) meta def linarith_monad.run (red : transparency) {α} (tac : linarith_monad α) (l : list expr) : tactic ((pcomp ⊕ α) × rb_map ℕ (expr × expr)) := do (struct, inputs) ← mk_linarith_structure red l, match (state_t.run (validate >> tac) struct).run with | (except.ok (a, _)) := return (sum.inr a, inputs) | (except.error contr) := return (sum.inl contr, inputs) end end parse section prove open ineq tactic meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := failed meta def mul_expr (n : ℕ) (e : expr) : pexpr := if n = 1 then ``(%%e) else ``(%%(nat.to_pexpr n) * %%e) meta def add_exprs_aux : pexpr → list pexpr → pexpr | p [] := p | p [a] := ``(%%p + %%a) | p (h::t) := add_exprs_aux ``(%%p + %%h) t meta def add_exprs : list pexpr → pexpr | [] := ``(0) | (h::t) := add_exprs_aux h t meta def find_contr (m : rb_set pcomp) : option pcomp := m.keys.find (λ p, p.c.is_contr) meta def ineq_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq meta def ineq_const_nm : ineq → ineq → (name × ineq) | eq eq := (``eq_of_eq_of_eq, eq) | eq le := (``le_of_eq_of_le, le) | eq lt := (``lt_of_eq_of_lt, lt) | le eq := (``le_of_le_of_eq, le) | le le := (`add_nonpos, le) | le lt := (`add_neg_of_nonpos_of_neg, lt) | lt eq := (``lt_of_lt_of_eq, lt) | lt le := (`add_neg_of_neg_of_nonpos, lt) | lt lt := (`add_neg, lt) meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (eq, e') else if c = 1 then return (iq, h) else do nm ← resolve_name (ineq_const_mul_nm iq), tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0), (_, ex) ← solve_aux cpos `[norm_num, done], -- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why? e' ← to_expr ``(%%nm %%h %%ex) ff, return (iq, e') meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : ℕ) : tactic (ineq × expr) := do (iq, h') ← mk_single_comp_zero_pf coeff npf, let (nm, niq) := ineq_const_nm c iq, n ← resolve_name nm, e' ← to_expr ``(%%n %%pf %%h'), return (niq, e') /-- Takes a list of coefficients [c] and list of expressions, of equal length. Each expression is a proof of a prop of the form t {<, ≤, =} 0. Produces a proof that the sum of (c*t) {<, ≤, =} 0, where the comp is as strong as possible. -/ meta def mk_lt_zero_pf : list ℕ → list expr → tactic expr | _ [] := fail "no linear hypotheses found" | [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h | (c::ct) (h::t) := do (iq, h') ← mk_single_comp_zero_pf c h, prod.snd <$> (ct.zip t).mfoldl (λ pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h') | _ _ := fail "not enough args to mk_lt_zero_pf" meta def term_of_ineq_prf (prf : expr) : tactic expr := do (lhs, _) ← infer_type prf >>= get_rel_sides, return lhs meta structure linarith_config := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . apply_instance) (exfalso : bool := tt) (transparency : transparency := reducible) meta def ineq_pf_tp (pf : expr) : tactic expr := do (_, z) ← infer_type pf >>= get_rel_sides, infer_type z meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr := to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp))) /-- Assumes e is a proof that t = 0. Creates a proof that -t = 0. -/ meta def mk_neg_eq_zero_pf (e : expr) : tactic expr := to_expr ``(neg_eq_zero.mpr %%e) meta def add_neg_eq_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h, match iq with | ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl | _ := list.cons h <$> add_neg_eq_pfs t end /-- Takes a list of proofs of propositions of the form t {<, ≤, =} 0, and tries to prove the goal `false`. -/ meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr → tactic unit | [] := fail "no args to linarith" | l@(h::t) := do l' ← add_neg_eq_pfs l, hz ← ineq_pf_tp h >>= mk_neg_one_lt_zero_pf, (sum.inl contr, inputs) ← elim_all_vars.run cfg.transparency (hz::l') | fail "linarith failed to find a contradiction", let coeffs := inputs.keys.map (λ k, (contr.src.flatten.ifind k)), let pfs : list expr := inputs.keys.map (λ k, (inputs.ifind k).1), let zip := (coeffs.zip pfs).filter (λ pr, pr.1 ≠ 0), let (coeffs, pfs) := zip.unzip, mls ← zip.mmap (λ pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)), sm ← to_expr $ add_exprs mls, tgt ← to_expr ``(%%sm = 0), (a, b) ← solve_aux tgt (cfg.discharger >> done), pf ← mk_lt_zero_pf coeffs pfs, pftp ← infer_type pf, (_, nep, _) ← rewrite_core b pftp, pf' ← mk_eq_mp nep pf, mk_app `lt_irrefl [pf'] >>= exact end prove section normalize open tactic set_option eqn_compiler.max_steps 50000 meta def rem_neg (prf : expr) : expr → tactic expr | `(_ ≤ _) := to_expr ``(lt_of_not_ge %%prf) | `(_ < _) := to_expr ``(le_of_not_gt %%prf) | `(_ > _) := to_expr ``(le_of_not_gt %%prf) | `(_ ≥ _) := to_expr ``(lt_of_not_ge %%prf) | e := failed meta def rearr_comp : expr → expr → tactic expr | prf `(%%a ≤ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a ≥ 0) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf) | prf `(0 ≥ %%a) := to_expr ``(show %%a ≤ 0, from %%prf) | prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf) | prf `(0 = %%a) := to_expr ``(eq.symm %%prf) | prf `(0 ≤ %%a) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf) | prf `(%%a ≤ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf) | prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a ≥ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp | prf _ := fail "couldn't rearrange comp" meta def is_numeric : expr → option ℚ | `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2 | `(-%%e) := rat.neg <$> is_numeric e | e := e.to_rat meta def find_cancel_factor : expr → ℕ × tree ℕ | `(%%e1 + %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 - %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 * %%e2) := match is_numeric e1, is_numeric e2 with | none, none := (1, tree.node 1 tree.nil tree.nil) | _, _ := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in (pd, tree.node pd t1 t2) end | `(%%e1 / %%e2) := match is_numeric e2 with | some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in (n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil)) | none := (1, tree.node 1 tree.nil tree.nil) end | `(-%%e) := find_cancel_factor e | _ := (1, tree.node 1 tree.nil tree.nil) open tree meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr | v (node _ lhs rhs) `(%%e1 + %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2] | v (node _ lhs rhs) `(%%e1 - %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2] | v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2, ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v, ntp ← to_expr ``(%%ln' * %%vln' = %%v'), (_, npf) ← solve_aux ntp `[norm_num, done], mk_app ``mul_subst [v1, v2, npf] | v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1, rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v, ntp ← to_expr ``(%%rn' / %%e2 = 1), (_, npf) ← solve_aux ntp `[norm_num, done], ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'), (_, npf2) ← solve_aux ntp2 `[norm_num, done], mk_app ``div_subst [v1, npf, npf2] | v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v'] | v _ e := do tp ← infer_type e, v' ← tp.of_nat v, e' ← to_expr ``(%%v' * %%e), mk_app `eq.refl [e'] /-- e is a term with rational division. produces a natural number n and a proof that n*e = e', where e' has no division. -/ meta def kill_factors (e : expr) : tactic (ℕ × expr) := let (n, t) := find_cancel_factor e in do e' ← mk_prod_prf n t e, return (n, e') open expr meta def expr_contains (n : name) : expr → bool | (const nm _) := nm = n | (lam _ _ _ bd) := expr_contains bd | (pi _ _ _ bd) := expr_contains bd | (app e1 e2) := expr_contains e1 || expr_contains e2 | _ := ff lemma sub_into_lt {α} [ordered_semiring α] {a b : α} (he : a = b) (hl : a ≤ 0) : b ≤ 0 := by rwa he at hl meta def norm_hyp_aux (h' lhs : expr) : tactic expr := do (v, lhs') ← kill_factors lhs, if v = 1 then return h' else do (ih, h'') ← mk_single_comp_zero_pf v h', (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' meta def norm_hyp (h : expr) : tactic expr := do htp ← infer_type h, h' ← rearr_comp h htp, some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h', if expr_contains `has_div.div lhs then norm_hyp_aux h' lhs else return h' meta def get_contr_lemma_name : expr → option name | `(%%a < %%b) := return `lt_of_not_ge | `(%%a ≤ %%b) := return `le_of_not_gt | `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt | `(%%a ≠ %%b) := return `not.intro | `(%%a ≥ %%b) := return `le_of_not_gt | `(%%a > %%b) := return `lt_of_not_ge | `(¬ %%a < %%b) := return `not.intro | `(¬ %%a ≤ %%b) := return `not.intro | `(¬ %%a = %%b) := return `not.intro | `(¬ %%a ≥ %%b) := return `not.intro | `(¬ %%a > %%b) := return `not.intro | _ := none -- assumes the input t is of type ℕ. Produces t' of type ℤ such that ↑t = t' and a proof of equality meta def cast_expr (e : expr) : tactic (expr × expr) := do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one, ``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul, ``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one, ``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk, ce ← to_expr ``(↑%%e : ℤ), simplify s [] ce {fail_if_unchanged := ff} meta def is_nat_int_coe : expr → option expr | `((↑(%%n : ℕ) : ℤ)) := some n | _ := none meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] meta def get_nat_comps : expr → list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) := (get_nat_comps e).mmap mk_coe_nat_nonneg_prf meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) := do (a', prfa) ← cast_expr a, (b', prfb) ← cast_expr b, la ← mk_coe_nat_nonneg_prfs a', lb ← mk_coe_nat_nonneg_prfs b', pf' ← mk_app ln [pf, prfa, prfb], return $ pf'::(la.append lb) meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) := do tp ← infer_type pf, match tp with | `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst | `(%%a ≤ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst | `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst | `(%%a ≥ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst | `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst | `(¬ %%a ≤ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst | `(¬ %%a < %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst | `(¬ %%a ≥ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst | `(¬ %%a > %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst | _ := fail "mk_int_pfs_of_nat_pf failed: proof is not an inequality" end meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr := do tp ← infer_type pf, match tp with | `(%%a < %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) %%pf) | `(%%a > %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) %%pf) | `(¬ %%a ≤ %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) (lt_of_not_ge %%pf)) | `(¬ %%a ≥ %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) (lt_of_not_ge %%pf)) | _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality" end meta def guard_is_nat_prop : expr → tactic unit | `(%%a = _) := infer_type a >>= unify `(ℕ) | `(%%a ≤ _) := infer_type a >>= unify `(ℕ) | `(%%a < _) := infer_type a >>= unify `(ℕ) | `(%%a ≥ _) := infer_type a >>= unify `(ℕ) | `(%%a > _) := infer_type a >>= unify `(ℕ) | `(¬ %%p) := guard_is_nat_prop p | _ := failed meta def guard_is_strict_int_prop : expr → tactic unit | `(%%a < _) := infer_type a >>= unify `(ℤ) | `(%%a > _) := infer_type a >>= unify `(ℤ) | `(¬ %%a ≤ _) := infer_type a >>= unify `(ℤ) | `(¬ %%a ≥ _) := infer_type a >>= unify `(ℤ) | _ := failed meta def replace_nat_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_nat_prop, ls ← mk_int_pfs_of_nat_pf h, list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t meta def replace_strict_int_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_strict_int_prop, l ← mk_non_strict_int_pf_of_strict_int_pf h, list.cons l <$> replace_strict_int_pfs t) <|> list.cons h <$> replace_strict_int_pfs t meta def partition_by_type_aux : rb_lmap expr expr → list expr → tactic (rb_lmap expr expr) | m [] := return m | m (h::t) := do tp ← ineq_pf_tp h, partition_by_type_aux (m.insert tp h) t meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) := partition_by_type_aux mk_rb_map l private meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic unit := (first $ ls.map $ prove_false_by_linarith1 cfg) <|> fail "linarith failed" /-- Takes a list of proofs of propositions. Filters out the proofs of linear (in)equalities, and tries to use them to prove `false`. If pref_type is given, starts by working over this type -/ meta def prove_false_by_linarith (cfg : linarith_config) (pref_type : option expr) (l : list expr) : tactic unit := do l' ← replace_nat_pfs l, l'' ← replace_strict_int_pfs l', ls ← list.reduce_option <$> l''.mmap (λ h, (do s ← norm_hyp h, return (some s)) <|> return none) >>= partition_by_type, pref_type ← (unify pref_type.iget `(ℕ) >> return (some `(ℤ) : option expr)) <|> return pref_type, match cfg.restrict_type, rb_map.values ls, pref_type with | some rtp, _, _ := do m ← mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, m ← instantiate_mvars m, prove_false_by_linarith1 cfg (ls.ifind m) | none, [ls'], _ := prove_false_by_linarith1 cfg ls' | none, ls', none := try_linarith_on_lists cfg ls' | none, _, (some t) := prove_false_by_linarith1 cfg (ls.ifind t) <|> try_linarith_on_lists cfg (rb_map.values (ls.erase t)) end end normalize end linarith section open tactic linarith open lean lean.parser interactive tactic interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def linarith.elab_arg_list : option (list pexpr) → tactic (list expr) | none := return [] | (some l) := l.mmap i_to_expr meta def linarith.preferred_type_of_goal : option expr → tactic (option expr) | none := return none | (some e) := some <$> ineq_pf_tp e /-- linarith.interactive_aux cfg o_goal restrict_hyps args: * cfg is a linarith_config object * o_goal : option expr is the local constant corresponding to the former goal, if there was one * restrict_hyps : bool is tt if `linarith only [...]` was used * args : option (list pexpr) is the optional list of arguments in `linarith [...]` -/ meta def linarith.interactive_aux (cfg : linarith_config) : option expr → bool → option (list pexpr) → tactic unit | none tt none := fail "linarith only called with no arguments" | none tt (some l) := l.mmap i_to_expr >>= prove_false_by_linarith cfg none | (some e) tt l := do tp ← ineq_pf_tp e, list.cons e <$> linarith.elab_arg_list l >>= prove_false_by_linarith cfg (some tp) | oe ff l := do otp ← linarith.preferred_type_of_goal oe, list.append <$> local_context <*> (list.filter (λ a, bnot $ expr.is_local_constant a) <$> linarith.elab_arg_list l) >>= prove_false_by_linarith cfg otp /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. `linarith` will use all relevant hypotheses in the local context. `linarith [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses h1, h2, h3, and proofs t1, t2, t3. It will ignore the rest of the local context. `linarith!` will use a stronger reducibility setting to identify atoms. Config options: `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` -/ meta def tactic.interactive.linarith (red : parse ((tk "!")?)) (restr : parse ((tk "only")?)) (hyps : parse pexpr_list?) (cfg : linarith_config := {}) : tactic unit := let cfg := if red.is_some then {cfg with transparency := semireducible, discharger := `[ring!]} else cfg in do t ← target, match get_contr_lemma_name t with | some nm := seq (applyc nm) $ do t ← intro1, linarith.interactive_aux cfg (some t) restr.is_some hyps | none := if cfg.exfalso then exfalso >> linarith.interactive_aux cfg none restr.is_some hyps else fail "linarith failed: target type is not an inequality." end add_hint_tactic "linarith" end
41296e06bcd604561945380c3533219e764d08b1
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Init/Util.lean
7b0e3ce3fdcceda2e2424effd69c55dcae46bc61
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
2,666
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.Data.String.Basic import Init.Data.ToString.Basic universe u v /- debugging helper functions -/ @[neverExtract, extern "lean_dbg_trace"] def dbgTrace {α : Type u} (s : String) (f : Unit → α) : α := f () def dbgTraceVal {α : Type u} [ToString α] (a : α) : α := dbgTrace (toString a) (fun _ => a) /- Display the given message if `a` is shared, that is, RC(a) > 1 -/ @[neverExtract, extern "lean_dbg_trace_if_shared"] def dbgTraceIfShared {α : Type u} (s : String) (a : α) : α := a @[extern "lean_dbg_sleep"] def dbgSleep {α : Type u} (ms : UInt32) (f : Unit → α) : α := f () @[noinline] private def mkPanicMessage (modName : String) (line col : Nat) (msg : String) : String := "PANIC at " ++ modName ++ ":" ++ toString line ++ ":" ++ toString col ++ ": " ++ msg @[neverExtract, inline] def panicWithPos {α : Type u} [Inhabited α] (modName : String) (line col : Nat) (msg : String) : α := panic (mkPanicMessage modName line col msg) @[noinline] private def mkPanicMessageWithDecl (modName : String) (declName : String) (line col : Nat) (msg : String) : String := "PANIC at " ++ declName ++ " " ++ modName ++ ":" ++ toString line ++ ":" ++ toString col ++ ": " ++ msg @[neverExtract, inline] def panicWithPosWithDecl {α : Type u} [Inhabited α] (modName : String) (declName : String) (line col : Nat) (msg : String) : α := panic (mkPanicMessageWithDecl modName declName line col msg) @[extern "lean_ptr_addr"] unsafe def ptrAddrUnsafe {α : Type u} (a : @& α) : USize := 0 @[inline] unsafe def withPtrAddrUnsafe {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k (ptrAddrUnsafe a) @[inline] unsafe def withPtrEqUnsafe {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := if ptrAddrUnsafe a == ptrAddrUnsafe b then true else k () @[implementedBy withPtrEqUnsafe] def withPtrEq {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := k () /-- `withPtrEq` for `DecidableEq` -/ @[inline] def withPtrEqDecEq {α : Type u} (a b : α) (k : Unit → Decidable (a = b)) : Decidable (a = b) := let b := withPtrEq a b (fun _ => toBoolUsing (k ())) (toBoolUsingEqTrue (k ())); match h:b with | true => isTrue (ofBoolUsingEqTrue h) | false => isFalse (ofBoolUsingEqFalse h) @[implementedBy withPtrAddrUnsafe] def withPtrAddr {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k 0
aa47a50f13c0867ef790b564da9d03ece8e6dacc
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Init/Data/String/Basic.lean
ab7f3d2ff740eb6ff272b914eaf4f5e8b0e43f65
[ "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
15,873
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.List.Basic import Init.Data.Char.Basic import Init.Data.Option.Basic universes u /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ def List.asString (s : List Char) : String := ⟨s⟩ namespace String instance : HasLess String := ⟨fun s₁ s₂ => s₁.data < s₂.data⟩ @[extern "lean_string_dec_lt"] instance decLt (s₁ s₂ : @& String) : Decidable (s₁ < s₂) := List.hasDecidableLt s₁.data s₂.data @[extern "lean_string_length"] def length : (@& String) → Nat | ⟨s⟩ => s.length /- The internal implementation uses dynamic arrays and will perform destructive updates if the String is not shared. -/ @[extern "lean_string_push"] def push : String → Char → String | ⟨s⟩, c => ⟨s ++ [c]⟩ /- The internal implementation uses dynamic arrays and will perform destructive updates if the String is not shared. -/ @[extern "lean_string_append"] def append : String → (@& String) → String | ⟨a⟩, ⟨b⟩ => ⟨a ++ b⟩ /- O(n) in the runtime, where n is the length of the String -/ def toList (s : String) : List Char := s.data private def utf8GetAux : List Char → Pos → Pos → Char | [], i, p => arbitrary | c::cs, i, p => if i = p then c else utf8GetAux cs (i + csize c) p @[extern "lean_string_utf8_get"] def get : (@& String) → (@& Pos) → Char | ⟨s⟩, p => utf8GetAux s 0 p def getOp (self : String) (idx : Pos) : Char := self.get idx private def utf8SetAux (c' : Char) : List Char → Pos → Pos → List Char | [], i, p => [] | c::cs, i, p => if i = p then (c'::cs) else c::(utf8SetAux c' cs (i + csize c) p) @[extern "lean_string_utf8_set"] def set : String → (@& Pos) → Char → String | ⟨s⟩, i, c => ⟨utf8SetAux c s 0 i⟩ def modify (s : String) (i : Pos) (f : Char → Char) : String := s.set i <| f <| s.get i @[extern "lean_string_utf8_next"] def next (s : @& String) (p : @& Pos) : Pos := let c := get s p p + csize c private def utf8PrevAux : List Char → Pos → Pos → Pos | [], i, p => 0 | c::cs, i, p => let cz := csize c let i' := i + cz if i' = p then i else utf8PrevAux cs i' p @[extern "lean_string_utf8_prev"] def prev : (@& String) → (@& Pos) → Pos | ⟨s⟩, p => if p = 0 then 0 else utf8PrevAux s 0 p def front (s : String) : Char := get s 0 def back (s : String) : Char := get s (prev s (bsize s)) @[extern "lean_string_utf8_at_end"] def atEnd : (@& String) → (@& Pos) → Bool | s, p => p ≥ utf8ByteSize s /- TODO: remove `partial` keywords after we restore the tactic framework and wellfounded recursion support -/ partial def posOfAux (s : String) (c : Char) (stopPos : Pos) (pos : Pos) : Pos := if pos == stopPos then pos else if s.get pos == c then pos else posOfAux s c stopPos (s.next pos) @[inline] def posOf (s : String) (c : Char) : Pos := posOfAux s c s.bsize 0 partial def revPosOfAux (s : String) (c : Char) (pos : Pos) : Option Pos := if s.get pos == c then some pos else if pos == 0 then none else revPosOfAux s c (s.prev pos) def revPosOf (s : String) (c : Char) : Option Pos := if s.bsize == 0 then none else revPosOfAux s c (s.prev s.bsize) private def utf8ExtractAux₂ : List Char → Pos → Pos → List Char | [], _, _ => [] | c::cs, i, e => if i = e then [] else c :: utf8ExtractAux₂ cs (i + csize c) e private def utf8ExtractAux₁ : List Char → Pos → Pos → Pos → List Char | [], _, _, _ => [] | s@(c::cs), i, b, e => if i = b then utf8ExtractAux₂ s i e else utf8ExtractAux₁ cs (i + csize c) b e @[extern "lean_string_utf8_extract"] def extract : (@& String) → (@& Pos) → (@& Pos) → String | ⟨s⟩, b, e => if b ≥ e then ⟨[]⟩ else ⟨utf8ExtractAux₁ s 0 b e⟩ @[specialize] partial def splitAux (s : String) (p : Char → Bool) (b : Pos) (i : Pos) (r : List String) : List String := if s.atEnd i then let r := if p (s.get i) then ""::(s.extract b (i-1))::r else (s.extract b i)::r r.reverse else if p (s.get i) then let i := s.next i splitAux s p i i (s.extract b (i-1)::r) else splitAux s p b (s.next i) r @[specialize] def split (s : String) (p : Char → Bool) : List String := splitAux s p 0 0 [] partial def splitOnAux (s sep : String) (b : Pos) (i : Pos) (j : Pos) (r : List String) : List String := if s.atEnd i then let r := if sep.atEnd j then ""::(s.extract b (i-j))::r else (s.extract b i)::r r.reverse else if s.get i == sep.get j then let i := s.next i let j := sep.next j if sep.atEnd j then splitOnAux s sep i i 0 (s.extract b (i-j)::r) else splitOnAux s sep b i j r else splitOnAux s sep b (s.next i) 0 r def splitOn (s : String) (sep : String := " ") : List String := if sep == "" then [s] else splitOnAux s sep 0 0 0 [] instance : Inhabited String := ⟨""⟩ instance : SizeOf String := ⟨String.length⟩ instance : Append String := ⟨String.append⟩ def str : String → Char → String := push def pushn (s : String) (c : Char) (n : Nat) : String := n.repeat (fun s => s.push c) s def isEmpty (s : String) : Bool := s.bsize == 0 def join (l : List String) : String := l.foldl (fun r s => r ++ s) "" def singleton (c : Char) : String := "".push c def intercalate (s : String) (ss : List String) : String := (List.intercalate s.toList (ss.map toList)).asString structure Iterator := (s : String) (i : Pos) def mkIterator (s : String) : Iterator := ⟨s, 0⟩ namespace Iterator def toString : Iterator → String | ⟨s, _⟩ => s def remainingBytes : Iterator → Nat | ⟨s, i⟩ => s.bsize - i def pos : Iterator → Pos | ⟨s, i⟩ => i def curr : Iterator → Char | ⟨s, i⟩ => get s i def next : Iterator → Iterator | ⟨s, i⟩ => ⟨s, s.next i⟩ def prev : Iterator → Iterator | ⟨s, i⟩ => ⟨s, s.prev i⟩ def hasNext : Iterator → Bool | ⟨s, i⟩ => i < utf8ByteSize s def hasPrev : Iterator → Bool | ⟨s, i⟩ => i > 0 def setCurr : Iterator → Char → Iterator | ⟨s, i⟩, c => ⟨s.set i c, i⟩ def toEnd : Iterator → Iterator | ⟨s, _⟩ => ⟨s, s.bsize⟩ def extract : Iterator → Iterator → String | ⟨s₁, b⟩, ⟨s₂, e⟩ => if s₁ ≠ s₂ || b > e then "" else s₁.extract b e def forward : Iterator → Nat → Iterator | it, 0 => it | it, n+1 => forward it.next n def remainingToString : Iterator → String | ⟨s, i⟩ => s.extract i s.bsize /- (isPrefixOfRemaining it₁ it₂) is `true` Iff `it₁.remainingToString` is a prefix of `it₂.remainingToString`. -/ def isPrefixOfRemaining : Iterator → Iterator → Bool | ⟨s₁, i₁⟩, ⟨s₂, i₂⟩ => s₁.extract i₁ s₁.bsize = s₂.extract i₂ (i₂ + (s₁.bsize - i₁)) def nextn : Iterator → Nat → Iterator | it, 0 => it | it, i+1 => nextn it.next i def prevn : Iterator → Nat → Iterator | it, 0 => it | it, i+1 => prevn it.prev i end Iterator partial def offsetOfPosAux (s : String) (pos : Pos) (i : Pos) (offset : Nat) : Nat := if i == pos || s.atEnd i then offset else offsetOfPosAux s pos (s.next i) (offset+1) def offsetOfPos (s : String) (pos : Pos) : Nat := offsetOfPosAux s pos 0 0 @[specialize] partial def foldlAux {α : Type u} (f : α → Char → α) (s : String) (stopPos : Pos) (i : Pos) (a : α) : α := let rec loop (i : Pos) (a : α) := if i == stopPos then a else loop (s.next i) (f a (s.get i)) loop i a @[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : String) : α := foldlAux f s s.bsize 0 a @[specialize] partial def foldrAux {α : Type u} (f : Char → α → α) (a : α) (s : String) (stopPos : Pos) (i : Pos) : α := let rec loop (i : Pos) := if i == stopPos then a else f (s.get i) (loop (s.next i)) loop i @[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : String) : α := foldrAux f a s s.bsize 0 @[specialize] partial def anyAux (s : String) (stopPos : Pos) (p : Char → Bool) (i : Pos) : Bool := let rec loop (i : Pos) := if i == stopPos then false else if p (s.get i) then true else loop (s.next i) loop i @[inline] def any (s : String) (p : Char → Bool) : Bool := anyAux s s.bsize p 0 @[inline] def all (s : String) (p : Char → Bool) : Bool := !s.any (fun c => !p c) def contains (s : String) (c : Char) : Bool := s.any (fun a => a == c) @[specialize] partial def mapAux (f : Char → Char) (i : Pos) (s : String) : String := if s.atEnd i then s else let c := f (s.get i) let s := s.set i c mapAux f (s.next i) s @[inline] def map (f : Char → Char) (s : String) : String := mapAux f 0 s def isNat (s : String) : Bool := s.all fun c => c.isDigit def toNat? (s : String) : Option Nat := if s.isNat then some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0 else none /- Return true iff `p` is a prefix of `s` -/ partial def isPrefixOf (p : String) (s : String) : Bool := let rec loop (i : Pos) := if p.atEnd i then true else let c₁ := p.get i let c₂ := s.get i c₁ == c₂ && loop (s.next i) p.length ≤ s.length && loop 0 end String namespace Substring @[inline] def bsize : Substring → Nat | ⟨_, b, e⟩ => e - b @[inline] def isEmpty (ss : Substring) : Bool := ss.bsize == 0 @[inline] def toString : Substring → String | ⟨s, b, e⟩ => s.extract b e @[inline] def toIterator : Substring → String.Iterator | ⟨s, b, _⟩ => ⟨s, b⟩ @[inline] def get : Substring → String.Pos → Char | ⟨s, b, _⟩, p => s.get (b+p) @[inline] def next : Substring → String.Pos → String.Pos | ⟨s, b, e⟩, p => let p := s.next (b+p) if p > e then e - b else p - b @[inline] def prev : Substring → String.Pos → String.Pos | ⟨s, b, _⟩, p => if p = b then p else s.prev (b+p) - b def nextn : Substring → Nat → String.Pos → String.Pos | ss, 0, p => p | ss, i+1, p => ss.nextn i (ss.next p) def prevn : Substring → String.Pos → Nat → String.Pos | ss, 0, p => p | ss, i+1, p => ss.prevn i (ss.prev p) @[inline] def front (s : Substring) : Char := s.get 0 @[inline] def posOf (s : Substring) (c : Char) : String.Pos := match s with | ⟨s, b, e⟩ => (String.posOfAux s c e b) - b @[inline] def drop : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, ss.nextn n b, e⟩ @[inline] def dropRight : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b, ss.prevn n e⟩ @[inline] def take : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b, ss.nextn n b⟩ @[inline] def takeRight : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, ss.prevn n e, e⟩ @[inline] def atEnd : Substring → String.Pos → Bool | ⟨s, b, e⟩, p => b + p == e @[inline] def extract : Substring → String.Pos → String.Pos → Substring | ⟨s, b, _⟩, b', e' => if b' ≥ e' then ⟨"", 0, 1⟩ else ⟨s, b+b', b+e'⟩ partial def splitOn (s : Substring) (sep : String := " ") : List Substring := if sep == "" then [s] else let stopPos := s.stopPos let str := s.str let rec loop (b i j : String.Pos) (r : List Substring) : List Substring := if i == stopPos then let r := if sep.atEnd j then "".toSubstring::{ str := str, startPos := b, stopPos := i-j } :: r else { str := str, startPos := b, stopPos := i } :: r r.reverse else if s.get i == sep.get j then let i := s.next i let j := sep.next j if sep.atEnd j then loop i i 0 ({ str := str, startPos := b, stopPos := i-j } :: r) else loop b i j r else loop b (s.next i) 0 r loop s.startPos s.startPos 0 [] @[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : Substring) : α := match s with | ⟨s, b, e⟩ => String.foldlAux f s e b a @[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : Substring) : α := match s with | ⟨s, b, e⟩ => String.foldrAux f a s e b @[inline] def any (s : Substring) (p : Char → Bool) : Bool := match s with | ⟨s, b, e⟩ => String.anyAux s e p b @[inline] def all (s : Substring) (p : Char → Bool) : Bool := !s.any (fun c => !p c) def contains (s : Substring) (c : Char) : Bool := s.any (fun a => a == c) @[specialize] partial def takeWhileAux (s : String) (stopPos : String.Pos) (p : Char → Bool) (i : String.Pos) : String.Pos := if i == stopPos then i else if p (s.get i) then takeWhileAux s stopPos p (s.next i) else i @[inline] def takeWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let e := takeWhileAux s e p b; ⟨s, b, e⟩ @[inline] def dropWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let b := takeWhileAux s e p b; ⟨s, b, e⟩ @[specialize] partial def takeRightWhileAux (s : String) (begPos : String.Pos) (p : Char → Bool) (i : String.Pos) : String.Pos := if i == begPos then i else let i' := s.prev i let c := s.get i' if !p c then i else takeRightWhileAux s begPos p i' @[inline] def takeRightWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let b := takeRightWhileAux s b p e ⟨s, b, e⟩ @[inline] def dropRightWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let e := takeRightWhileAux s b p e ⟨s, b, e⟩ @[inline] def trimLeft (s : Substring) : Substring := s.dropWhile Char.isWhitespace @[inline] def trimRight (s : Substring) : Substring := s.dropRightWhile Char.isWhitespace @[inline] def trim : Substring → Substring | ⟨s, b, e⟩ => let b := takeWhileAux s e Char.isWhitespace b let e := takeRightWhileAux s b Char.isWhitespace e ⟨s, b, e⟩ def isNat (s : Substring) : Bool := s.all fun c => c.isDigit def toNat? (s : Substring) : Option Nat := if s.isNat then some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0 else none def beq (ss1 ss2 : Substring) : Bool := ss1.toString == ss2.toString instance hasBeq : BEq Substring := ⟨beq⟩ end Substring namespace String def drop (s : String) (n : Nat) : String := (s.toSubstring.drop n).toString def dropRight (s : String) (n : Nat) : String := (s.toSubstring.dropRight n).toString def take (s : String) (n : Nat) : String := (s.toSubstring.take n).toString def takeRight (s : String) (n : Nat) : String := (s.toSubstring.takeRight n).toString def takeWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.takeWhile p).toString def dropWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.dropWhile p).toString def trimRight (s : String) : String := s.toSubstring.trimRight.toString def trimLeft (s : String) : String := s.toSubstring.trimLeft.toString def trim (s : String) : String := s.toSubstring.trim.toString @[inline] def nextWhile (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos := Substring.takeWhileAux s s.bsize p i @[inline] def nextUntil (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos := nextWhile s (fun c => !p c) i def capitalize (s : String) := s.set 0 <| s.get 0 |>.toUpper end String protected def Char.toString (c : Char) : String := String.singleton c
52a160c7da7c2ed086664b9f9dafe99d7e0e49b0
eb9357a70318e50e095b58730bebfe0cffee457f
/lean/love04_functional_programming_demo.lean
ae84a5b50eb046a44c78d2e144a9f9176127f6a0
[]
no_license
Vierkantor/logical_verification_2021
7485dd916953131d501760f023d5b30fbb74d36a
9500b9c194e22a9ab4067321cfed7a1f445afcfc
refs/heads/main
1,692,560,845,086
1,624,721,275,000
1,624,721,275,000
416,354,079
0
0
null
null
null
null
UTF-8
Lean
false
false
12,660
lean
import .lovelib /-! # LoVe Demo 4: Functional Programming We take a closer look at the basics of typed functional programming: inductive types, proofs by induction, recursive functions, pattern matching, structures (records), and type classes. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /-! ## Inductive Types Recall the definition of type `nat` (= `ℕ`): -/ #print nat /-! Mottos: * **No junk**: The type contains no values beyond those expressible using the constructors. * **No confusion**: Values built in a different ways are different. For `nat` (= `ℕ`): * "No junk" means that there are no special values, say, `–1` or `ε`, that cannot be expressed using a finite combination of `zero` and `succ`. * "No confusion" is what ensures that `zero` ≠ `succ x`. In addition, inductive types are always finite. `succ (succ (succ …))` is not a value. ## Structural Induction __Structural induction__ is a generalization of mathematical induction to inductive types. To prove a property `P[n]` for all natural numbers `n`, it suffices to prove the base case `P[0]` and the induction step `∀k, P[k] → P[k + 1]` For lists, the base case is `P[[]]` and the induction step is `∀y ys, P[ys] → P[y :: ys]` In general, there is one subgoal per constructor, and induction hypotheses are available for all constructor arguments of the type we are doing the induction on. -/ lemma nat.succ_neq_self (n : ℕ) : nat.succ n ≠ n := begin induction' n, { simp }, { simp [ih] } end /-! The `case` tactic can be used to supply custom names, and potentially reorder the cases. -/ lemma nat.succ_neq_self₂ (n : ℕ) : nat.succ n ≠ n := begin induction' n, case succ : m IH { simp [IH] }, case zero { simp } end /-! ## Structural Recursion __Structural recursion__ is a form of recursion that allows us to peel off one or more constructors from the value on which we recurse. Such functions are guaranteed to call themselves only finitely many times before the recursion stops. This is a prerequisite for establishing that the function terminates. -/ def fact : ℕ → ℕ | 0 := 1 | (n + 1) := (n + 1) * fact n def fact₂ : ℕ → ℕ | 0 := 1 | 1 := 1 | (n + 1) := (n + 1) * fact₂ n /-! For structurally recursive functions, Lean can automatically prove termination. For more general recursive schemes, the termination check may fail. Sometimes it does so for a good reason, as in the following example: -/ -- fails def illegal : ℕ → ℕ | n := illegal n + 1 constant immoral : ℕ → ℕ axiom immoral_eq (n : ℕ) : immoral n = immoral n + 1 lemma proof_of_false : false := have immoral 0 = immoral 0 + 1 := immoral_eq 0, have immoral 0 - immoral 0 = immoral 0 + 1 - immoral 0 := by cc, have 0 = 1 := by simp [*] at *, show false, from by cc /-! ## Pattern Matching Expressions `match` _term₁_, …, _termM_ `with` | _pattern₁₁_, …, _pattern₁M_ := _result₁_ ⋮ | _patternN₁_, …, _patternNM_ := _resultN_ `end` `match` allows nonrecursive pattern matching within terms. In contrast to pattern matching after `lemma` or `def`, the patterns are separated by commas, so parentheses are optional. -/ def bcount {α : Type} (p : α → bool) : list α → ℕ | [] := 0 | (x :: xs) := match p x with | tt := bcount xs + 1 | ff := bcount xs end def min (a b : ℕ) : ℕ := if a ≤ b then a else b /-! ## Structures Lean provides a convenient syntax for defining records, or structures. These are essentially nonrecursive, single-constructor inductive types. -/ structure rgb := (red green blue : ℕ) #check rgb.mk #check rgb.red #check rgb.green #check rgb.blue namespace rgb_as_inductive inductive rgb : Type | mk : ℕ → ℕ → ℕ → rgb def rgb.red : rgb → ℕ | (rgb.mk r _ _) := r def rgb.green : rgb → ℕ | (rgb.mk _ g _) := g def rgb.blue : rgb → ℕ | (rgb.mk _ _ b) := b end rgb_as_inductive structure rgba extends rgb := (alpha : ℕ) #print rgba def pure_red : rgb := { red := 0xff, green := 0x00, blue := 0x00 } def semitransparent_red : rgba := { alpha := 0x7f, ..pure_red } #print pure_red #print semitransparent_red def shuffle (c : rgb) : rgb := { red := rgb.green c, green := rgb.blue c, blue := rgb.red c } /-! `cases'` performs a case distinction on the specified term. This gives rise to as many subgoals as there are constructors in the definition of the term's type. The tactic behaves the same as `induction'` except that it does not produce induction hypotheses. -/ lemma shuffle_shuffle_shuffle (c : rgb) : shuffle (shuffle (shuffle c)) = c := begin cases' c, refl end lemma shuffle_shuffle_shuffle₂ (c : rgb) : shuffle (shuffle (shuffle c)) = c := match c with | rgb.mk _ _ _ := eq.refl _ end /-! ## Type Classes A __type class__ is a structure type combining abstract constants and their properties. A type can be declared an instance of a type class by providing concrete definitions for the constants and proving that the properties hold. Based on the type, Lean retrieves the relevant instance. -/ #print inhabited @[instance] def nat.inhabited : inhabited ℕ := { default := 0 } @[instance] def list.inhabited {α : Type} : inhabited (list α) := { default := [] } #eval inhabited.default ℕ -- result: 0 #eval inhabited.default (list ℤ) -- result: [] def head {α : Type} [inhabited α] : list α → α | [] := inhabited.default α | (x :: _) := x lemma head_head {α : Type} [inhabited α] (xs : list α) : head [head xs] = head xs := begin cases' xs, { refl }, { refl } end #eval head ([] : list ℕ) -- result: 0 #check list.head @[instance] def fun.inhabited {α β : Type} [inhabited β] : inhabited (α → β) := { default := λa : α, inhabited.default β } inductive empty : Type @[instance] def fun_empty.inhabited {β : Type} : inhabited (empty → β) := { default := λa : empty, match a with end } @[instance] def prod.inhabited {α β : Type} [inhabited α] [inhabited β] : inhabited (α × β) := { default := (inhabited.default α, inhabited.default β) } /-! Here are other type classes without properties: -/ #check has_zero #check has_neg #check has_add #check has_one #check has_inv #check has_mul #check (1 : ℕ) #check (1 : ℤ) #check (1 : ℝ) /-! We encountered these type classes in lecture 2: -/ #print is_commutative #print is_associative /-! ## Lists `list` is an inductive polymorphic type constructed from `nil` and `cons`: -/ #print list /-! `cases'` can also be used on a hypothesis of the form `l = r`. It matches `r` against `l` and replaces all occurrences of the variables occurring in `r` with the corresponding terms in `l` everywhere in the goal. -/ lemma injection_example {α : Type} (x y : α) (xs ys : list α) (h : list.cons x xs = list.cons y ys) : x = y ∧ xs = ys := begin cases' h, cc end /-! If `r` fails to match `l`, no subgoals emerge; the proof is complete. -/ lemma distinctness_example {α : Type} (y : α) (ys : list α) (h : [] = y :: ys) : false := by cases' h def map {α β : Type} (f : α → β) : list α → list β | [] := [] | (x :: xs) := f x :: map xs def map₂ {α β : Type} : (α → β) → list α → list β | _ [] := [] | f (x :: xs) := f x :: map₂ f xs #check list.map lemma map_ident {α : Type} (xs : list α) : map (λx, x) xs = xs := begin induction' xs, case nil { refl }, case cons : y ys { simp [map, ih] } end lemma map_comp {α β γ : Type} (f : α → β) (g : β → γ) (xs : list α) : map g (map f xs) = map (λx, g (f x)) xs := begin induction' xs, case nil { refl }, case cons : y ys { simp [map, ih] } end lemma map_append {α β : Type} (f : α → β) (xs ys : list α) : map f (xs ++ ys) = map f xs ++ map f ys := begin induction' xs, case nil { refl }, case cons : y ys { simp [map, ih] } end def tail {α : Type} : list α → list α | [] := [] | (_ :: xs) := xs #check list.tail def head_opt {α : Type} : list α → option α | [] := option.none | (x :: _) := option.some x def head_pre {α : Type} : ∀xs : list α, xs ≠ [] → α | [] hxs := by cc | (x :: _) _ := x #eval head_opt [3, 1, 4] #eval head_pre [3, 1, 4] (by simp) -- fails #eval head_pre ([] : list ℕ) sorry def zip {α β : Type} : list α → list β → list (α × β) | (x :: xs) (y :: ys) := (x, y) :: zip xs ys | [] _ := [] | (_ :: _) [] := [] #check list.zip def length {α : Type} : list α → ℕ | [] := 0 | (x :: xs) := length xs + 1 #check list.length /-! `cases'` can also be used to perform a case distinction on a proposition, in conjunction with `classical.em`. Two cases emerge: one in which the proposition is true and one in which it is false. -/ #check classical.em lemma min_add_add (l m n : ℕ) : min (m + l) (n + l) = min m n + l := begin cases' classical.em (m ≤ n), case inl { simp [min, h] }, case inr { simp [min, h] } end lemma min_add_add₂ (l m n : ℕ) : min (m + l) (n + l) = min m n + l := match classical.em (m ≤ n) with | or.inl h := by simp [min, h] | or.inr h := by simp [min, h] end lemma min_add_add₃ (l m n : ℕ) : min (m + l) (n + l) = min m n + l := if h : m ≤ n then by simp [min, h] else by simp [min, h] lemma length_zip {α β : Type} (xs : list α) (ys : list β) : length (zip xs ys) = min (length xs) (length ys) := begin induction' xs, case nil { refl }, case cons : x xs' { cases' ys, case nil { refl }, case cons : y ys' { simp [zip, length, ih ys', min_add_add] } } end lemma map_zip {α α' β β' : Type} (f : α → α') (g : β → β') : ∀xs ys, map (λab : α × β, (f (prod.fst ab), g (prod.snd ab))) (zip xs ys) = zip (map f xs) (map g ys) | (x :: xs) (y :: ys) := by simp [zip, map, map_zip xs ys] | [] _ := by refl | (_ :: _) [] := by refl /-! ## Binary Trees Inductive types with constructors taking several recursive arguments define tree-like objects. __Binary trees__ have nodes with at most two children. -/ inductive btree (α : Type) : Type | empty {} : btree | node : α → btree → btree → btree /-! The type `aexp` of arithmetic expressions was also an example of a tree data structure. The nodes of a tree, whether inner nodes or leaf nodes, often carry labels or other annotations. Inductive trees contain no infinite branches, not even cycles. This is less expressive than pointer- or reference-based data structures (in imperative languages) but easier to reason about. Recursive definitions (and proofs by induction) work roughly as for lists, but we may need to recurse (or invoke the induction hypothesis) on several child nodes. -/ def mirror {α : Type} : btree α → btree α | btree.empty := btree.empty | (btree.node a l r) := btree.node a (mirror r) (mirror l) lemma mirror_mirror {α : Type} (t : btree α) : mirror (mirror t) = t := begin induction' t, case empty { refl }, case node : a l r ih_l ih_r { simp [mirror, ih_l, ih_r] } end lemma mirror_mirror₂ {α : Type} : ∀t : btree α, mirror (mirror t) = t | btree.empty := by refl | (btree.node a l r) := calc mirror (mirror (btree.node a l r)) = mirror (btree.node a (mirror r) (mirror l)) : by refl ... = btree.node a (mirror (mirror l)) (mirror (mirror r)) : by refl ... = btree.node a l (mirror (mirror r)) : by rw mirror_mirror₂ l ... = btree.node a l r : by rw mirror_mirror₂ r lemma mirror_eq_empty_iff {α : Type} : ∀t : btree α, mirror t = btree.empty ↔ t = btree.empty | btree.empty := by refl | (btree.node _ _ _) := by simp [mirror] /-! ## Dependent Inductive Types (**optional**) -/ #check vector inductive vec (α : Type) : ℕ → Type | nil {} : vec 0 | cons (a : α) {n : ℕ} (v : vec n) : vec (n + 1) #check vec.nil #check vec.cons def list_of_vec {α : Type} : ∀{n : ℕ}, vec α n → list α | _ vec.nil := [] | _ (vec.cons a v) := a :: list_of_vec v def vec_of_list {α : Type} : ∀xs : list α, vec α (list.length xs) | [] := vec.nil | (x :: xs) := vec.cons x (vec_of_list xs) lemma length_list_of_vec {α : Type} : ∀{n : ℕ} (v : vec α n), list.length (list_of_vec v) = n | _ vec.nil := by refl | _ (vec.cons a v) := by simp [list_of_vec, length_list_of_vec v] end LoVe
3af71fa752bd70c66965d34bbd7d9c83cfa484b1
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_1891.lean
5526596290ba0eeab74f41c02c7ee875c3b85a93
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
163
lean
import data.real.basic variable {y : ℝ} -- BEGIN example (h : y > 0) : y > 0 ∨ y < -1 := or.inl h example (h : y < -1) : y > 0 ∨ y < -1 := or.inr h -- END
ff9156e46738da4b37cfbcae87c2e6e1e96e0718
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/group_theory/congruence.lean
0ab9d20514fa25f8cece613db1ad2a868a771940
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
42,284
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import group_theory.submonoid import data.setoid import algebra.pi_instances /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with a addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_beta {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, c.to_setoid ≤ d.to_setoid⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations S equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw Sup_eq_con_gen, congr, ext x y, erw [Sup_image, supr_apply, supr_apply, supr_Prop_eq], simp only [Sup_image, supr_Prop_eq, supr_apply, supr_Prop_eq, exists_prop], refl, end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : ((≤) : {d // c ≤ d} → {d // c ≤ d} → Prop) ≃o ((≤) : con c.quotient → con c.quotient → Prop) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy⟩ } end end -- Monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive add_monoid "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive add_comm_monoid "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive add_submonoid "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive of_add_submonoid "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive to_add_submonoid "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive to_add_submonoid_inj] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma injective_ker_lift (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).range_restrict) $ bijective_comp (equiv.bijective _) ⟨λ x y h, injective_ker_lift f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..@equiv.of_bijective _ _ (ker_lift f) ⟨injective_ker_lift f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient _ _ h } end con
456c608310dc34fd3b5f0bc628096d3da1bbbe59
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.39.lean
068d8b8c6e1febe7e49ee035a04e77085f6d0b67
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
103
lean
import standard import data.list open list (renaming induction_on → induction_on) check induction_on
d23658e049fb15104c545cf867038d440139d87c
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/polynomial/ring_division.lean
03a2bee16f93216651554828302116a6d99f4c47
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,703
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker, Johan Commelin -/ import data.polynomial.algebra_map import data.polynomial.degree.lemmas import data.polynomial.div /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : polynomial R} variables [comm_ring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : polynomial R} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := eval₂_mod_by_monic_eq_self_of_root hq hx lemma mod_by_monic_eq_of_dvd_sub [nontrivial R] (hq : q.monic) {p₁ p₂ : polynomial R} (h : q ∣ (p₁ - p₂)) : p₁ %ₘ q = p₂ %ₘ q := begin obtain ⟨f, sub_eq⟩ := h, refine (div_mod_by_monic_unique (p₂ /ₘ q + f) _ hq ⟨_, degree_mod_by_monic_lt _ hq⟩).2, rw [sub_eq_iff_eq_add.mp sub_eq, mul_add, ← add_assoc, mod_by_monic_add_div _ hq, add_comm] end lemma add_mod_by_monic [nontrivial R] (hq : q.monic) (p₁ p₂ : polynomial R) : (p₁ + p₂) %ₘ q = p₁ %ₘ q + p₂ %ₘ q := (div_mod_by_monic_unique (p₁ /ₘ q + p₂ /ₘ q) _ hq ⟨by rw [mul_add, add_left_comm, add_assoc, mod_by_monic_add_div _ hq, ← add_assoc, add_comm (q * _), mod_by_monic_add_div _ hq], (degree_add_le _ _).trans_lt (max_lt (degree_mod_by_monic_lt _ hq) (degree_mod_by_monic_lt _ hq))⟩).2 lemma smul_mod_by_monic [nontrivial R] (hq : q.monic) (c : R) (p : polynomial R) : (c • p) %ₘ q = c • (p %ₘ q) := (div_mod_by_monic_unique (c • (p /ₘ q)) (c • (p %ₘ q)) hq ⟨by rw [mul_smul_comm, ← smul_add, mod_by_monic_add_div p hq], (degree_smul_le _ _).trans_lt (degree_mod_by_monic_lt _ hq)⟩).2 /-- `polynomial.mod_by_monic_hom (hq : monic (q : polynomial R))` is `_ %ₘ q` as a `R`-linear map. -/ @[simps] def mod_by_monic_hom [nontrivial R] (hq : q.monic) : polynomial R →ₗ[R] polynomial R := { to_fun := λ p, p %ₘ q, map_add' := add_mod_by_monic hq, map_smul' := smul_mod_by_monic hq } end comm_ring section no_zero_divisors variables [comm_ring R] [no_zero_divisors R] {p q : polynomial R} instance : no_zero_divisors (polynomial R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], refine eq_zero_or_eq_zero_of_mul_eq_zero _, rw [← leading_coeff_zero, ← leading_coeff_mul, h], end } lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] @[simp] lemma nat_degree_pow (p : polynomial R) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end end no_zero_divisors section integral_domain variables [comm_ring R] [integral_domain R] {p q : polynomial R} instance : integral_domain (polynomial R) := { ..polynomial.no_zero_divisors, ..polynomial.nontrivial, ..polynomial.comm_ring } lemma nat_trailing_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : (p * q).nat_trailing_degree = p.nat_trailing_degree + q.nat_trailing_degree := begin simp only [←sub_eq_of_eq_add_rev (nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree _)], rw [reverse_mul_of_domain, nat_degree_mul hp hq, nat_degree_mul (mt reverse_eq_zero.mp hp) (mt reverse_eq_zero.mp hq), reverse_nat_degree, reverse_nat_degree, ←nat.sub_sub, nat.add_comm, nat.add_sub_assoc (nat.sub_le _ _), add_comm, nat.add_sub_assoc (nat.sub_le _ _)], end section roots open multiset lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial R) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial R)) : degree (u : polynomial R) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem prime_X_sub_C (r : R) : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : polynomial R) := by { convert (prime_X_sub_C (0 : R)), simp } lemma monic.prime_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm ▸ prime_X_sub_C _ theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := (prime_X_sub_C r).irreducible theorem irreducible_X : irreducible (X : polynomial R) := prime.irreducible prime_X lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu, apply_instance, end lemma root_multiplicity_mul {p q : polynomial R} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin have hp : p ≠ 0 := left_ne_zero_of_mul hpq, have hq : q ≠ 0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, multiplicity.mul' (prime_X_sub_C x)], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := (ne_zero_of_monic (monic_pow (monic_X_sub_C a) n.succ)), rw pow_succ (X - C a) n at hzero ⊢, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end /-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at least `n`. -/ lemma root_multiplicity_of_dvd {p : polynomial R} {a : R} {n : ℕ} (hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p := begin obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h, rw hq at hzero, simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow, ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right], end /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : polynomial R} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := begin refine root_multiplicity_of_dvd hzero _, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end lemma exists_multiset_roots : ∀ {p : polynomial R} (hp : p ≠ 0), ∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p | 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 rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, 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_multiset_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)).1 $ not_lt.2 hdeg, ⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≤ 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 a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : polynomial R) : multiset R := if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) @[simp] lemma roots_zero : (0 : polynomial R).roots = 0 := dif_pos rfl 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_multiset_roots hp0)).1 end lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma count_roots (hp : p ≠ 0) : p.roots.count a = root_multiplicity a p := by { rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a } @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by rw [← count_pos, count_roots hp, root_multiplicity_pos hp] lemma eq_zero_of_infinite_is_root (p : polynomial R) (h : set.infinite {x | is_root p x}) : p = 0 := begin by_contradiction hp, apply h, convert p.roots.to_finset.finite_to_set using 1, ext1 r, simp only [mem_roots hp, multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe] end lemma exists_max_root [linear_order R] (p : polynomial R) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x ≤ x₀ := set.exists_upper_bound_image _ _ $ not_not.mp (mt (eq_zero_of_infinite_is_root p) hp) lemma exists_min_root [linear_order R] (p : polynomial R) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x₀ ≤ x := set.exists_lower_bound_image _ _ $ not_not.mp (mt (eq_zero_of_infinite_is_root p) hp) lemma eq_of_infinite_eval_eq {R : Type*} [comm_ring R] [integral_domain R] (p q : polynomial R) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : polynomial R} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots := multiset.ext.mpr $ λ r, by rw [count_add, count_roots hpq, count_roots (left_ne_zero_of_mul hpq), count_roots (right_ne_zero_of_mul hpq), root_multiplicity_mul hpq] @[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := begin ext s, rw [count_roots (X_sub_C_ne_zero r), root_multiplicity_X_sub_C], split_ifs with h, { rw [h, count_singleton_self] }, { rw [singleton_eq_cons, count_cons_of_ne h, count_zero] } end @[simp] lemma roots_C (x : R) : (C x).roots = 0 := if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r, have h : C x ≠ 0, from λ h, H $ C_inj.1 $ h.symm ▸ C_0.symm, have not_root : ¬ is_root (C x) r := mt (λ (h : eval r (C x) = 0), trans eval_C.symm h) H, by rw [count_roots h, count_zero, root_multiplicity_eq_zero not_root] @[simp] lemma roots_one : (1 : polynomial R).roots = ∅ := roots_C 1 lemma roots_list_prod (L : list (polynomial R)) : ((0 : polynomial R) ∉ L) → L.prod.roots = (L : multiset (polynomial R)).bind roots := list.rec_on L (λ _, roots_one) $ λ hd tl ih H, begin rw [list.mem_cons_iff, not_or_distrib] at H, rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset (polynomial R)) : (0 : polynomial R) ∉ m → m.prod.roots = m.bind roots := by { rcases m with ⟨L⟩, simpa only [coe_prod, quot_mk_to_coe''] using roots_list_prod L } lemma roots_prod {ι : Type*} (f : ι → polynomial R) (s : finset ι) : s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) := begin rcases s with ⟨m, hm⟩, simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f) end lemma roots_prod_X_sub_C (s : finset R) : (s.prod (λ a, X - C a)).roots = s.val := (roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id']) lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : polynomial R) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : ℕ) (a : R) : multiset R := roots ((X : polynomial R) ^ n - C a) @[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by 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] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : polynomial R) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ], 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) /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type*) [comm_ring R] [integral_domain R] : finset R := multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] end nth_roots lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, by rwa mem_support_iff at hbs, refine coeff_eq_zero_of_degree_lt _, erw [degree_mul, degree_C this, degree_pow, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id, mul_lt_mul_right (pos_iff_ne_zero.mpr hqd0)], exact lt_of_le_of_ne (le_nat_degree_of_ne_zero this) hbp, end begin intro h, contrapose! hp0, rw mem_support_iff at h, push_neg at h, rwa ← leading_coeff_eq_zero, end ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma units_coeff_zero_smul (c : units (polynomial R)) (p : polynomial R) : (c : polynomial R).coeff 0 • p = c * p := by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)] @[simp] lemma nat_degree_coe_units (u : units (polynomial R)) : nat_degree (u : polynomial R) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma comp_eq_zero_iff : p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) := begin split, { intro h, have key : p.nat_degree = 0 ∨ q.nat_degree = 0, { rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] }, replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key, cases key, { rw [key, C_comp] at h, exact or.inl (key.trans h) }, { rw [key, comp_C, C_eq_zero] at h, exact or.inr ⟨h, key⟩ }, }, { exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h }, end lemma zero_of_eval_zero [infinite R] (p : polynomial R) (h : ∀ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact fintype.false ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : polynomial R} (ext : ∀ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end variables [comm_ring T] /-- The set of distinct roots of `p` in `E`. If you have a non-separable polynomial, use `polynomial.roots` for the multiset where multiple roots have the appropriate multiplicity. -/ def root_set (p : polynomial T) (S) [comm_ring S] [integral_domain S] [algebra T S] : set S := (p.map (algebra_map T S)).roots.to_finset lemma root_set_def (p : polynomial T) (S) [comm_ring S] [integral_domain S] [algebra T S] : p.root_set S = (p.map (algebra_map T S)).roots.to_finset := rfl @[simp] lemma root_set_zero (S) [comm_ring S] [integral_domain S] [algebra T S] : (0 : polynomial T).root_set S = ∅ := by rw [root_set_def, polynomial.map_zero, roots_zero, to_finset_zero, finset.coe_empty] @[simp] lemma root_set_C [comm_ring S] [integral_domain S] [algebra T S] (a : T) : (C a).root_set S = ∅ := by rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty] instance root_set_fintype (p : polynomial T) (S : Type*) [comm_ring S] [integral_domain S] [algebra T S] : fintype (p.root_set S) := finset_coe.fintype _ lemma root_set_finite (p : polynomial T) (S : Type*) [comm_ring S] [integral_domain S] [algebra T S] : (p.root_set S).finite := ⟨polynomial.root_set_fintype p S⟩ end roots theorem is_unit_iff {f : polynomial R} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) : coeff (u : polynomial R) 0 ≠ 0 := begin conv in (0) { rw [← nat_degree_coe_units u] }, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.is_unit_or_is_unit hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [comm_ring R] [integral_domain R] {p q : polynomial R} (hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff := begin have hp := mod_by_monic_add_div p hmonic, have hzero : (p /ₘ q) ≠ 0, { intro h, exact not_lt_of_le hdegree ((div_by_monic_eq_zero_iff hmonic).1 h) }, have deglt : (p %ₘ q).degree < (q * (p /ₘ q)).degree, { rw degree_mul, refine lt_of_lt_of_le (degree_mod_by_monic_lt p hmonic) _, rw [degree_eq_nat_degree (monic.ne_zero hmonic), degree_eq_nat_degree hzero], norm_cast, simp only [zero_le, le_add_iff_nonneg_right] }, have hrew := (leading_coeff_add_of_degree_lt deglt), rw leading_coeff_mul q (p /ₘ q) at hrew, simp only [hmonic, one_mul, monic.leading_coeff] at hrew, nth_rewrite 1 ← hp, exact hrew.symm end lemma eq_of_monic_of_dvd_of_nat_degree_le (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = p := begin obtain ⟨r, hr⟩ := hdiv, have rzero : r ≠ 0, { intro h, simpa [h, monic.ne_zero hq] using hr }, rw [hr, nat_degree_mul (monic.ne_zero hp) rzero] at hdeg, have hdegeq : p.nat_degree + r.nat_degree = p.nat_degree, { suffices hdegle : p.nat_degree ≤ p.nat_degree + r.nat_degree, { exact le_antisymm hdeg hdegle }, exact nat.le.intro rfl }, replace hdegeq := eq_C_of_nat_degree_eq_zero (((@add_right_inj _ _ p.nat_degree) _ 0).1 hdegeq), suffices hlead : 1 = r.leading_coeff, { have hcoeff := leading_coeff_C (r.coeff 0), rw [← hdegeq, ← hlead] at hcoeff, rw [← hcoeff, C_1] at hdegeq, rwa [hdegeq, mul_one] at hr }, have hprod : q.leading_coeff = p.leading_coeff * r.leading_coeff, { simp only [hr, leading_coeff_mul] }, rwa [monic.leading_coeff hp, monic.leading_coeff hq, one_mul] at hprod end end integral_domain section variables [semiring R] [comm_ring S] [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 have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, refine is_unit.map (C.to_monoid_hom : R →* polynomial R) _, convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (φ f.leading_coeff) := is_unit.map φ.to_monoid_hom hf, rw h at u, simpa using u, } end end section variables [comm_ring R] [integral_domain R] [comm_ring S] [integral_domain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : polynomial R) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := begin fsplit, { intro h, exact h_irr.not_unit (is_unit.map (map_ring_hom φ).to_monoid_hom h), }, { intros a b h, have q := (leading_coeff_mul a b).symm, rw ←h at q, dsimp [monic] at h_mon, rw h_mon at q, have au : is_unit a.leading_coeff := is_unit_of_mul_eq_one _ _ q, rw mul_comm at q, have bu : is_unit b.leading_coeff := is_unit_of_mul_eq_one _ _ q, clear q h_mon, have h' := congr_arg (map φ) h, simp only [map_mul] at h', cases h_irr.is_unit_or_is_unit h' with w w, { left, exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ au w, }, { right, exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ bu w, }, } end end end polynomial namespace is_integral_domain variables {R : Type*} [comm_ring R] /-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/ lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) := @integral_domain.to_is_integral_domain _ _ (@polynomial.integral_domain _ _ (h.to_integral_domain _)) end is_integral_domain
37b4953a7d1efebe20305af07dd1ecf29b7f4191
367134ba5a65885e863bdc4507601606690974c1
/docs/tutorial/category_theory/intro.lean
458709a47fe84617c52d50fd1b4f3cbf9f706f9f
[ "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
9,298
lean
import category_theory.functor_category -- this transitively imports -- category_theory.category -- category_theory.functor -- category_theory.natural_transformation /-! # An introduction to category theory in Lean This is an introduction to the basic usage of category theory (in the mathematical sense) in Lean. We cover how the basic theory of categories, functors and natural transformations is set up in Lean. Most of the below is not hard to read off from the files `category_theory/category.lean`, `category_theory/functor.lean` and `category_theory/natural_transformation.lean`. ## Overview A category is a collection of objects, and a collection of morphisms (also known as arrows) between the objects. The objects and morphisms have some extra structure and satisfy some axioms -- see the [definition on Wikipedia](https://en.wikipedia.org/wiki/Category_%28mathematics%29#Definition) for details. One important thing to note is that a morphism in an abstract category may not be an actual function between two types. In particular, there is new notation `⟶` , typed as `\h` or `\hom` in VS Code, for a morphism. Nevertheless, in most of the "concrete" categories like `Top` and `Ab`, it is still possible to write `f x` when `x : X` and `f : X ⟶ Y` is a morphism, as there is an automatic coercion from morphisms to functions. (If the coercion doesn't fire automatically, sometimes it is necessary to write `(f : X → Y) x`.) In some fonts the `⟶` morphism arrow can be virtually indistinguishable from the standard function arrow `→` . You may want to install the [Deja Vu Sans Mono](https://dejavu-fonts.github.io/) and put that at the beginning of the `Font Family` setting in VSCode, to get a nice readable font with excellent unicode coverage. Another point of confusion can be universe issues. Following Lean's conventions for universe polymorphism, the objects of a category might live in one universe `u` and the morphisms in another universe `v`. Note that in many categories showing up in "set-theoretic mathematics", the morphisms between two objects often form a set, but the objects themselves may or may not form a set. In Lean this corresponds to the two possibilities `u=v` and `u=v+1`, known as `small_category` and `large_category` respectively. In order to avoid proving the same statements for both small and large categories, we usually stick to the general polymorphic situation with `u` and `v` independent universes, and we do this below. ## Getting started with categories The structure of a category on a type `C` in Lean is done using typeclasses; terms of `C` then correspond to objects in the category. The convention in the category theory library is to use universes prefixed with `u` (e.g. `u`, `u₁`, `u₂`) for the objects, and universes prefixed with `v` for morphisms. Thus we have `C : Type u`, and if `X : C` and `Y : C` then morphisms `X ⟶ Y : Type v` (note the non-standard arrow). We set this up as follows: -/ open category_theory section category universes v u -- the order matters (see below) variables (C : Type u) [category.{v} C] variables {W X Y Z : C} variables (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) /-! This says "let `C` be a category, let `W`, `X`, `Y`, `Z` be objects of `C`, and let `f : W ⟶ X`, `g : X ⟶ Y` and `h : Y ⟶ Z` be morphisms in `C` (with the specified source and targets)". Note that we need to explicitly tell Lean the universe that the morphisms live in, by writing `category.{v} C`, because Lean cannot guess this from `C` alone. The order in which universes are introduced at the top of the file matters: we put the universes for morphisms first (typically `v`, `v₁` and so on), and then universes for objects (typically `u`, `u₁` and so on). This ensures that in any new definition we make the universe variables for morphisms come first, so that they can be explicitly specified while still allowing the universe levels of the objects to be inferred automatically. ## Basic notation In categories one has morphisms between objects, such as the identity morphism from an object to itself. One can compose morphisms, and there are standard facts about the composition of a morphism with the identity morphism, and the fact that morphism composition is associative. In Lean all of this looks like the following: -/ -- The identity morphism from `X` to `X` (remember that this is the `\h` arrow): example : X ⟶ X := 𝟙 X -- type `𝟙` as `\bb1` -- Function composition `h ∘ g`, a morphism from `X` to `Z`: example : X ⟶ Z := g ≫ h /- Note in particular the order! The "maps on the right" convention was chosen; `g ≫ h` means "`g` then `h`". Type `≫` with `\gg` in VS Code. Here are the theorems which ensure that we have a category. -/ open category_theory.category example : 𝟙 X ≫ g = g := id_comp g example : g ≫ 𝟙 Y = g := comp_id g example : (f ≫ g) ≫ h = f ≫ (g ≫ h) := assoc f g h example : (f ≫ g) ≫ h = f ≫ g ≫ h := assoc f g h -- note \gg is right associative -- All four examples above can also be proved with `simp`. -- Monomorphisms and epimorphisms are predicates on morphisms and are implemented as typeclasses. variables (f' : W ⟶ X) (h' : Y ⟶ Z) example [mono g] : f ≫ g = f' ≫ g → f = f' := mono.right_cancellation f f' example [epi g] : g ≫ h = g ≫ h' → h = h' := epi.left_cancellation h h' end category -- end of section /-! ## Getting started with functors A functor is a map between categories. It is implemented as a structure. The notation for a functor from `C` to `D` is `C ⥤ D`. Type `\func` in VS Code for the symbol. Here we demonstrate how to evaluate functors on objects and on morphisms, how to show functors preserve the identity morphism and composition of morphisms, how to compose functors, and show the notation `𝟭` for the identity functor. -/ section functor -- recall we put morphism universes (`vᵢ`) before object universes (`uᵢ`) universes v₁ v₂ v₃ u₁ u₂ u₃ variables (C : Type u₁) [category.{v₁} C] variables (D : Type u₂) [category.{v₂} D] variables (E : Type u₃) [category.{v₃} E] variables {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) -- functors variables (F : C ⥤ D) (G : D ⥤ E) example : D := F.obj X -- functor F on objects example : F.obj Y ⟶ F.obj Z := F.map g -- functor F on morphisms -- A functor sends identity objects to identity objects example : F.map (𝟙 X) = 𝟙 (F.obj X) := F.map_id X -- and preserves compositions example : F.map (f ≫ g) = (F.map f) ≫ (F.map g) := F.map_comp f g -- The identity functor is `𝟭`, which you can write as `\sb1`. example : C ⥤ C := 𝟭 C -- The identity functor is (definitionally) the identity on objects and morphisms: example : (𝟭 C).obj X = X := category_theory.functor.id_obj X example : (𝟭 C).map f = f := category_theory.functor.id_map f -- Composition of functors; note order: example : C ⥤ E := F ⋙ G -- typeset with `\ggg` -- Composition of the identity either way does nothing: example : F ⋙ 𝟭 D = F := F.comp_id example : 𝟭 C ⋙ F = F := F.id_comp -- Composition of functors definitionally does the right thing on objects and morphisms: example : (F ⋙ G).obj X = G.obj (F.obj X) := F.comp_obj G X -- or rfl example : (F ⋙ G).map f = G.map (F.map f) := rfl -- or F.comp_map G X Y f end functor -- end of section /-! One can also check that associativity of composition of functors is definitionally true, although we've observed that relying on this can result in slow proofs. (One should rather use the natural isomorphisms provided in `src/category_theory/whiskering.lean`.) ## Getting started with natural transformations A natural transformation is a morphism between functors. If `F` and `G` are functors from `C` to `D` then a natural transformation is a map `F X ⟶ G X` for each object `X : C` plus the theorem that if `f : X ⟶ Y` is a morphism then the two routes from `F X` to `G Y` are the same. One might imagine that this is now another layer of notation, but fortunately the `category_theory.functor_category` import gives the type of functors from `C` to `D` a category structure, which means that we can just use morphism notation for natural transformations. -/ section nat_trans universes v₁ v₂ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] variables (X Y : C) variable (f : X ⟶ Y) variables (F G H : C ⥤ D) variables (α : F ⟶ G) (β : G ⟶ H) -- natural transformations (note it's the usual `\hom` arrow here) -- Composition of natural transformations is just composition of morphisms: example : F ⟶ H := α ≫ β -- Applying natural transformation to an object: example (X : C) : F.obj X ⟶ G.obj X := α.app X /- The diagram coming from g and α F(f) F X ---> F Y | | |α(X) |α(Y) v v G X ---> G Y G(f) commutes. -/ example : F.map f ≫ α.app Y = (α.app X) ≫ G.map f := α.naturality f end nat_trans -- section /-! ## What next? There are several lean files in the [category theory docs directory of mathlib](https://github.com/leanprover-community/mathlib/tree/master/docs/tutorial/category_theory) which give further examples of using the category theory library in Lean. -/
7e397816eba485384ed50297aa7d965198e15ba3
e8159fb1a58abf09f7d75106ba3aa6c1c504c038
/theorem-proving-in-lean/3.7.2.lean
07d35c48f452744dc40e869a152d5687a8ea2311
[]
no_license
ndcroos/lean-snippets
cbf53e777a72964b6875a8c98bdd7eb02e74e246
b66736347cd80a4143e43397f359dbdf9cbcd491
refs/heads/master
1,584,160,922,314
1,525,542,053,000
1,525,542,053,000
131,447,243
0
0
null
null
null
null
UTF-8
Lean
false
false
58
lean
/- Prove ¬(p ↔ ¬p) without using classical logic. -/
f706081afe587c884d96718c63b05c42b0e97ced
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/Format.lean
399f45c63baeb18ea11d75ab5140b7eee8449a67
[ "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
584
lean
open Lean open Std open Std.Format def eval (w : Nat) (f : Format) : IO Unit := do IO.println $ f.pretty w -- hard line breaks should re-evaluate flattening behavior within group #eval eval 5 $ fill (text "a" ++ line ++ text "b\nlooooooooong" ++ line ++ text "c") ++ line ++ text "d" -- basic `fill` test #eval eval 20 $ fill (Format.joinSep ((List.range 13).map fun i => i.repeat (fun s => s ++ "a") "a") line) -- `fill` items that are too big should get dedicated #eval eval 8 $ fill (Format.joinSep [text "a", text "b", paren (text "ccccc" ++ line ++ text "d"), text "e"] line)
525feb392ad967204fdac97a912714f82813a320
4fa161becb8ce7378a709f5992a594764699e268
/src/algebra/direct_limit.lean
1cff3faa6059cf5501fa7635efbda82ae146703b
[ "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
25,240
lean
/- Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes Direct limit of modules, abelian groups, rings, and fields. See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270 Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring, or incomparable abelian groups, or rings, or fields. It is constructed as a quotient of the free module (for the module case) or quotient of the free commutative ring (for the ring case) instead of a quotient of the disjoint union so as to make the operations (addition etc.) "computable". -/ import ring_theory.free_comm_ring universes u v w u₁ open submodule variables {R : Type u} [ring R] variables {ι : Type v} [nonempty ι] variables [decidable_eq ι] [directed_order ι] variables (G : ι → Type w) [Π i, decidable_eq (G i)] /-- A directed system is a functor from the category (directed poset) to another category. This is used for abelian groups and rings and fields because their maps are not bundled. See module.directed_system -/ class directed_system (f : Π i j, i ≤ j → G i → G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) namespace module variables [Π i, add_comm_group (G i)] [Π i, module R (G i)] /-- A directed system is a functor from the category (directed poset) to the category of R-modules. -/ class directed_system (f : Π i j, i ≤ j → G i →ₗ[R] G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) variables (f : Π i j, i ≤ j → G i →ₗ[R] G j) [directed_system G f] /-- The direct limit of a directed system is the modules glued together along the maps. -/ def direct_limit : Type (max v w) := (span R $ { a | ∃ (i j) (H : i ≤ j) x, direct_sum.lof R ι G i x - direct_sum.lof R ι G j (f i j H x) = a }).quotient namespace direct_limit instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _ instance : semimodule R (direct_limit G f) := quotient.semimodule _ variables (R ι) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[R] direct_limit G f := (mkq _).comp $ direct_sum.lof R ι G i variables {R ι G f} @[simp] lemma of_f {i j hij x} : (of R ι G f j (f i j hij x)) = of R ι G f i x := eq.symm $ (submodule.quotient.eq _).2 $ subset_span ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of (z : direct_limit G f) : ∃ i x, of R ι G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ z, direct_sum.induction_on z ⟨ind, 0, linear_map.map_zero _⟩ (λ i x, ⟨i, x, rfl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] protected theorem induction_on {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of R ι G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x variables {P : Type u₁} [add_comm_group P] [module R P] (g : Π i, G i →ₗ[R] P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg variables (R ι G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[R] P := liftq _ (direct_sum.to_module R ι P g) (span_le.2 $ λ a ⟨i, j, hij, x, hx⟩, by rw [← hx, mem_coe, linear_map.sub_mem_ker_iff, direct_sum.to_module_lof, direct_sum.to_module_lof, Hg]) variables {R ι G f} omit Hg lemma lift_of {i} (x) : lift R ι G f g Hg (of R ι G f i x) = g i x := direct_sum.to_module_lof R _ _ theorem lift_unique (F : direct_limit G f →ₗ[R] P) (x) : F x = lift R ι G f (λ i, F.comp $ of R ι G f i) (λ i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x := direct_limit.induction_on x $ λ i x, by rw lift_of; refl section totalize open_locale classical variables (G f) noncomputable def totalize : Π i j, G i →ₗ[R] G j := λ i j, if h : i ≤ j then f i j h else 0 variables {G f} lemma totalize_apply (i j x) : totalize G f i j x = if h : i ≤ j then f i j h x else 0 := if h : i ≤ j then by dsimp only [totalize]; rw [dif_pos h, dif_pos h] else by dsimp only [totalize]; rw [dif_neg h, dif_neg h, linear_map.zero_apply] end totalize lemma to_module_totalize_of_le {x : direct_sum ι G} {i j : ι} (hij : i ≤ j) (hx : ∀ k ∈ x.support, k ≤ i) : direct_sum.to_module R ι (G j) (λ k, totalize G f k j) x = f i j hij (direct_sum.to_module R ι (G i) (λ k, totalize G f k i) x) := begin rw [← @dfinsupp.sum_single ι G _ _ _ x], unfold dfinsupp.sum, simp only [linear_map.map_sum], refine finset.sum_congr rfl (λ k hk, _), rw direct_sum.single_eq_lof R k (x k), simp [totalize_apply, hx k hk, le_trans (hx k hk) hij, directed_system.map_map f] end lemma of.zero_exact_aux {x : direct_sum ι G} (H : submodule.quotient.mk x = (0 : direct_limit G f)) : ∃ j, (∀ k ∈ x.support, k ≤ j) ∧ direct_sum.to_module R ι (G j) (λ i, totalize G f i j) x = (0 : G j) := nonempty.elim (by apply_instance) $ assume ind : ι, span_induction ((quotient.mk_eq_zero _).1 H) (λ x ⟨i, j, hij, y, hxy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, begin clear_, subst hxy, split, { intros i0 hi0, rw [dfinsupp.mem_support_iff, dfinsupp.sub_apply, ← direct_sum.single_eq_lof, ← direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0, split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk }, exfalso, apply hi0, rw sub_zero }, simp [linear_map.map_sub, totalize_apply, hik, hjk, directed_system.map_map f, direct_sum.apply_eq_component, direct_sum.component.of], end⟩) ⟨ind, λ _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _⟩ (λ x y ⟨i, hi, hxi⟩ ⟨j, hj, hyj⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, λ l hl, (finset.mem_union.1 (dfinsupp.support_add hl)).elim (λ hl, le_trans (hi _ hl) hik) (λ hl, le_trans (hj _ hl) hjk), by simp [linear_map.map_add, hxi, hyj, to_module_totalize_of_le hik hi, to_module_totalize_of_le hjk hj]⟩) (λ a x ⟨i, hi, hxi⟩, ⟨i, λ k hk, hi k (dfinsupp.support_smul hk), by simp [linear_map.map_smul, hxi]⟩) /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact {i x} (H : of R ι G f i x = 0) : ∃ j hij, f i j hij x = (0 : G j) := let ⟨j, hj, hxj⟩ := of.zero_exact_aux H in if hx0 : x = 0 then ⟨i, le_refl _, by simp [hx0]⟩ else have hij : i ≤ j, from hj _ $ by simp [direct_sum.apply_eq_component, hx0], ⟨j, hij, by simpa [totalize_apply, hij] using hxj⟩ end direct_limit end module namespace add_comm_group variables [Π i, add_comm_group (G i)] /-- The direct limit of a directed system is the abelian groups glued together along the maps. -/ def direct_limit (f : Π i j, i ≤ j → G i → G j) [Π i j hij, is_add_group_hom (f i j hij)] [directed_system G f] : Type* := @module.direct_limit ℤ _ ι _ _ _ G _ _ _ (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) ⟨directed_system.map_self f, directed_system.map_map f⟩ namespace direct_limit variables (f : Π i j, i ≤ j → G i → G j) variables [Π i j hij, is_add_group_hom (f i j hij)] [directed_system G f] lemma directed_system : module.directed_system G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) := ⟨directed_system.map_self f, directed_system.map_map f⟩ local attribute [instance] directed_system instance : add_comm_group (direct_limit G f) := module.direct_limit.add_comm_group G (λ i j hij, (add_monoid_hom.of $f i j hij).to_int_linear_map) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i → direct_limit G f := module.direct_limit.of ℤ ι G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) i variables {G f} instance of.is_add_group_hom (i) : is_add_group_hom (of G f i) := linear_map.is_add_group_hom _ @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := module.direct_limit.of_f @[simp] lemma of_zero (i) : of G f i 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_add_hom.map_add _ _ _ @[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_add_group_hom.map_neg _ _ @[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_add_group_hom.map_sub _ _ _ @[elab_as_eliminator] protected theorem induction_on {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := module.direct_limit.induction_on z ih /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact (i x) (h : of G f i x = 0) : ∃ j hij, f i j hij x = 0 := module.direct_limit.of.zero_exact h variables (P : Type u₁) [add_comm_group P] variables (g : Π i, G i → P) [Π i, is_add_group_hom (g i)] variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) variables (G f) /-- The universal property of the direct limit: maps from the components to another abelian group that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f → P := module.direct_limit.lift ℤ ι G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) (λ i, (add_monoid_hom.of $ g i).to_int_linear_map) Hg variables {G f} instance lift.is_add_group_hom : is_add_group_hom (lift G f P g Hg) := linear_map.is_add_group_hom _ @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := module.direct_limit.lift_of _ _ _ @[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := is_add_hom.map_add _ _ _ @[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := is_add_group_hom.map_neg _ _ @[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := is_add_group_hom.map_sub _ _ _ lemma lift_unique (F : direct_limit G f → P) [is_add_group_hom F] (x) : F x = @lift _ _ _ _ G _ _ f _ _ P _ (λ i x, F $ of G f i x) (λ i, is_add_group_hom.comp _ _) (λ i j hij x, by dsimp; rw of_f) x := direct_limit.induction_on x $ λ i x, by rw lift_of end direct_limit end add_comm_group namespace ring variables [Π i, comm_ring (G i)] variables (f : Π i j, i ≤ j → G i → G j) variables [Π i j hij, is_ring_hom (f i j hij)] variables [directed_system G f] open free_comm_ring /-- The direct limit of a directed system is the rings glued together along the maps. -/ def direct_limit : Type (max v w) := (ideal.span { a | (∃ i j H x, of (⟨j, f i j H x⟩ : Σ i, G i) - of ⟨i, x⟩ = a) ∨ (∃ i, of (⟨i, 1⟩ : Σ i, G i) - 1 = a) ∨ (∃ i x y, of (⟨i, x + y⟩ : Σ i, G i) - (of ⟨i, x⟩ + of ⟨i, y⟩) = a) ∨ (∃ i x y, of (⟨i, x * y⟩ : Σ i, G i) - (of ⟨i, x⟩ * of ⟨i, y⟩) = a) }).quotient namespace direct_limit instance : comm_ring (direct_limit G f) := ideal.quotient.comm_ring _ instance : ring (direct_limit G f) := comm_ring.to_ring _ /-- The canonical map from a component to the direct limit. -/ def of (i) (x : G i) : direct_limit G f := ideal.quotient.mk _ $ of ⟨i, x⟩ variables {G f} instance of.is_ring_hom (i) : is_ring_hom (of G f i) := { map_one := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl ⟨i, rfl⟩, map_mul := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr ⟨i, x, y, rfl⟩, map_add := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl ⟨i, x, y, rfl⟩ } @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := ideal.quotient.eq.2 $ subset_span $ or.inl ⟨i, j, hij, x, rfl⟩ @[simp] lemma of_zero (i) : of G f i 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma of_one (i) : of G f i 1 = 1 := is_ring_hom.map_one _ @[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_ring_hom.map_add _ @[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_ring_hom.map_neg _ @[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_ring_hom.map_sub _ @[simp] lemma of_mul (i x y) : of G f i (x * y) = of G f i x * of G f i y := is_ring_hom.map_mul _ @[simp] lemma of_pow (i x) (n : ℕ) : of G f i (x ^ n) = of G f i x ^ n := is_semiring_hom.map_pow _ _ _ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of (z : direct_limit G f) : ∃ i x, of G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ x, free_abelian_group.induction_on x ⟨ind, 0, of_zero ind⟩ (λ s, multiset.induction_on s ⟨ind, 1, of_one ind⟩ (λ a s ih, let ⟨i, x⟩ := a, ⟨j, y, hs⟩ := ih, ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x * f j k hjk y, by rw [of_mul, of_f, of_f, hs]; refl⟩)) (λ s ⟨i, x, ih⟩, ⟨i, -x, by rw [of_neg, ih]; refl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [of_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] theorem induction_on {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := let ⟨i, x, hx⟩ := exists_of z in hx ▸ ih i x section of_zero_exact open_locale classical variables (G f) lemma of.zero_exact_aux2 {x : free_comm_ring Σ i, G i} {s t} (hxs : is_supported x s) {j k} (hj : ∀ z : Σ i, G i, z ∈ s → z.1 ≤ j) (hk : ∀ z : Σ i, G i, z ∈ t → z.1 ≤ k) (hjk : j ≤ k) (hst : s ⊆ t) : f j k hjk (lift (λ ix : s, f ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) = lift (λ ix : t, f ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw [restriction_one, lift_one, is_ring_hom.map_one (f j k hjk), restriction_one, lift_one] }, { rw [restriction_neg, restriction_one, lift_neg, lift_one, is_ring_hom.map_neg (f j k hjk), is_ring_hom.map_one (f j k hjk), restriction_neg, restriction_one, lift_neg, lift_one] }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, lift_mul, is_ring_hom.map_mul (f j k hjk), ih, restriction_mul, lift_mul, restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of], dsimp only, rw directed_system.map_map f, refl }, { rintros x y ihx ihy, rw [restriction_add, lift_add, is_ring_hom.map_add (f j k hjk), ihx, ihy, restriction_add, lift_add] } end variables {G f} lemma of.zero_exact_aux {x : free_comm_ring Σ i, G i} (H : ideal.quotient.mk _ x = (0 : direct_limit G f)) : ∃ j s, ∃ H : (∀ k : Σ i, G i, k ∈ s → k.1 ≤ j), is_supported x s ∧ lift (λ ix : s, f ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) := begin refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _, { rintros x (⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩), { refine ⟨j, {⟨i, x⟩, ⟨j, f i j hij x⟩}, _, is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _⟩, { rintros k (rfl | ⟨rfl | _⟩), exact hij, refl }, { rw [restriction_sub, lift_sub, restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of], dsimp only, rw directed_system.map_map f, exact sub_self _, exacts [or.inr rfl, or.inl rfl] } }, { refine ⟨i, {⟨i, 1⟩}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _⟩, { rintros k (rfl|h), refl }, { rw [restriction_sub, lift_sub, restriction_of, dif_pos, restriction_one, lift_of, lift_one], dsimp only, rw [is_ring_hom.map_one (f i i _), sub_self], exacts [_inst_7 i i _, rfl] } }, { refine ⟨i, {⟨i, x+y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [restriction_sub, restriction_add, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, lift_sub, lift_add, lift_of, lift_of, lift_of], dsimp only, rw is_ring_hom.map_add (f i i _), exact sub_self _, exacts [or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } }, { refine ⟨i, {⟨i, x*y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [restriction_sub, restriction_mul, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, lift_sub, lift_mul, lift_of, lift_of, lift_of], dsimp only, rw is_ring_hom.map_mul (f i i _), exacts [sub_self _, or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } } }, { refine nonempty.elim (by apply_instance) (assume ind : ι, _), refine ⟨ind, ∅, λ _, false.elim, is_supported_zero, _⟩, rw [restriction_zero, lift_zero] }, { rintros x y ⟨i, s, hi, hxs, ihs⟩ ⟨j, t, hj, hyt, iht⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, s ∪ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hyt $ set.subset_union_right s t), _⟩, { rw [restriction_add, lift_add, ← of.zero_exact_aux2 G f hxs hi this hik (set.subset_union_left s t), ← of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right s t), ihs, is_ring_hom.map_zero (f i k hik), iht, is_ring_hom.map_zero (f j k hjk), zero_add] } }, { rintros x y ⟨j, t, hj, hyt, iht⟩, rw smul_eq_mul, rcases exists_finset_support x with ⟨s, hxs⟩, rcases (s.image sigma.fst).exists_le with ⟨i, hi⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ ↑s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exact le_trans (hi z.1 $ finset.mem_image.2 ⟨z, hz, rfl⟩) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, ↑s ∪ t, this, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left ↑s t) (is_supported_upwards hyt $ set.subset_union_right ↑s t), _⟩, rw [restriction_mul, lift_mul, ← of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right ↑s t), iht, is_ring_hom.map_zero (f j k hjk), mul_zero] } end /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ lemma of.zero_exact {i x} (hix : of G f i x = 0) : ∃ j, ∃ hij : i ≤ j, f i j hij x = 0 := let ⟨j, s, H, hxs, hx⟩ := of.zero_exact_aux hix in have hixs : (⟨i, x⟩ : Σ i, G i) ∈ s, from is_supported_of.1 hxs, ⟨j, H ⟨i, x⟩ hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hx⟩ end of_zero_exact /-- If the maps in the directed system are injective, then the canonical maps from the components to the direct limits are injective. -/ theorem of_injective (hf : ∀ i j hij, function.injective (f i j hij)) (i) : function.injective (of G f i) := begin suffices : ∀ x, of G f i x = 0 → x = 0, { intros x y hxy, rw ← sub_eq_zero_iff_eq, apply this, rw [is_ring_hom.map_sub (of G f i), hxy, sub_self] }, intros x hx, rcases of.zero_exact hx with ⟨j, hij, hfx⟩, apply hf i j hij, rw [hfx, is_ring_hom.map_zero (f i j hij)] end variables (P : Type u₁) [comm_ring P] variables (g : Π i, G i → P) [Π i, is_ring_hom (g i)] variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg open free_comm_ring variables (G f) /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. We don't use this function as the canonical form because Lean 3 fails to automatically coerce it to a function; use `lift` instead. -/ def lift_hom : direct_limit G f →+* P := ideal.quotient.lift _ (free_comm_ring.lift_hom $ λ x, g x.1 x.2) begin suffices : ideal.span _ ≤ ideal.comap (free_comm_ring.lift_hom (λ (x : Σ (i : ι), G i), g (x.fst) (x.snd))) ⊥, { intros x hx, exact (mem_bot P).1 (this hx) }, rw ideal.span_le, intros x hx, rw [mem_coe, ideal.mem_comap, mem_bot], rcases hx with ⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩; simp only [coe_lift_hom, lift_sub, lift_of, Hg, lift_one, lift_add, lift_mul, is_ring_hom.map_one (g i), is_ring_hom.map_add (g i), is_ring_hom.map_mul (g i), sub_self] end /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f → P := lift_hom G f P g Hg instance lift_is_ring_hom : is_ring_hom (lift G f P g Hg) := (lift_hom G f P g Hg).is_ring_hom variables {G f} omit Hg @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _ @[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := (lift_hom G f P g Hg).map_zero @[simp] lemma lift_one : lift G f P g Hg 1 = 1 := (lift_hom G f P g Hg).map_one @[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := (lift_hom G f P g Hg).map_add x y @[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := (lift_hom G f P g Hg).map_neg x @[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := (lift_hom G f P g Hg).map_sub x y @[simp] lemma lift_mul (x y) : lift G f P g Hg (x * y) = lift G f P g Hg x * lift G f P g Hg y := (lift_hom G f P g Hg).map_mul x y @[simp] lemma lift_pow (x) (n : ℕ) : lift G f P g Hg (x ^ n) = lift G f P g Hg x ^ n := (lift_hom G f P g Hg).map_pow x n local attribute [instance, priority 100] is_ring_hom.comp theorem lift_unique (F : direct_limit G f → P) [is_ring_hom F] (x) : F x = lift G f P (λ i x, F $ of G f i x) (λ i j hij x, by rw [of_f]) x := direct_limit.induction_on x $ λ i x, by rw lift_of end direct_limit end ring namespace field variables [Π i, field (G i)] variables (f : Π i j, i ≤ j → G i → G j) [Π i j hij, is_ring_hom (f i j hij)] variables [directed_system G f] namespace direct_limit instance nonzero : nonzero (ring.direct_limit G f) := { zero_ne_one := nonempty.elim (by apply_instance) $ assume i : ι, begin change (0 : ring.direct_limit G f) ≠ 1, rw ← ring.direct_limit.of_one, intros H, rcases ring.direct_limit.of.zero_exact H.symm with ⟨j, hij, hf⟩, rw is_ring_hom.map_one (f i j hij) at hf, exact one_ne_zero hf end } theorem exists_inv {p : ring.direct_limit G f} : p ≠ 0 → ∃ y, p * y = 1 := ring.direct_limit.induction_on p $ λ i x H, ⟨ring.direct_limit.of G f i (x⁻¹), by erw [← ring.direct_limit.of_mul, mul_inv_cancel (assume h : x = 0, H $ by rw [h, ring.direct_limit.of_zero]), ring.direct_limit.of_one]⟩ section open_locale classical noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f := if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H) protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : p * inv G f p = 1 := by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)] protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : inv G f p * p = 1 := by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp] protected noncomputable def field : field (ring.direct_limit G f) := { inv := inv G f, mul_inv_cancel := λ p, direct_limit.mul_inv_cancel G f, inv_zero := dif_pos rfl, .. ring.direct_limit.comm_ring G f, .. direct_limit.nonzero G f } end end direct_limit end field