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
5d7676437aac061f658690515fb8444a4ab28252
fe84e287c662151bb313504482b218a503b972f3
/src/exercises/mathcomp_book/chapter_4.lean
95c4f005e3551620115163f3406eb1f7fac77757
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
1,886
lean
import tactic.interactive tactic.find data.list.basic def my_list_bexists {α : Type} (p : α → bool) : ∀ l : list α, bool | list.nil := ff | (list.cons a l) := bor (p a) (my_list_bexists l) def my_list_pexists {α : Type} (p : α → Prop) : ∀ l : list α, Prop | list.nil := false | (list.cons a l) := (p a) ∨ (my_list_pexists l) def my_list_pexists' {α : Type} (p : α → Prop) (l : list α) : Prop := ∃ (i : ℕ) (i_is_lt : i < l.length), p (l.nth_le i i_is_lt) lemma my_list_pexists_nil {α : Type} (p : α → Prop) : ¬ my_list_pexists' p list.nil := by {rintro ⟨i,⟨⟨_⟩,_⟩⟩} lemma my_list_pexists_succ {α : Type} (p : α → Prop) (a : α) (l : list α) : my_list_pexists' p (a :: l) ↔ (p a ∨ (my_list_pexists' p l)) := begin unfold my_list_pexists', split, {rintro ⟨_|i,⟨i_is_lt,pi⟩⟩, {left,exact pi}, {let i_is_lt' := nat.lt_of_succ_lt_succ i_is_lt, right,use i,use i_is_lt', exact pi,} },{ rintro (pa | ⟨i,⟨i_is_lt,pi⟩⟩), {use 0,use nat.zero_lt_succ l.length,exact pa}, {use i.succ,use nat.succ_lt_succ i_is_lt,exact pi} } end lemma my_list_pexists_iff {α : Type} (p : α → Prop) : ∀ (l : list α), my_list_pexists p l ↔ my_list_pexists' p l | list.nil := ((iff_false _).mpr (my_list_pexists_nil p)).symm | (a :: l) := by {rw[my_list_pexists_succ,← my_list_pexists_iff l],refl,} instance my_list_pexists_decidable {α : Type} (p : α → Prop) [decidable_pred p] : ∀ (l : list α), decidable (my_list_pexists p l) | list.nil := by { dsimp[my_list_pexists],apply_instance, } | (a :: l) := by { dsimp[my_list_pexists], haveI := my_list_pexists_decidable l, apply_instance, } instance my_list_pexists'_decidable {α : Type} (p : α → Prop) [decidable_pred p] (l : list α) : decidable (my_list_pexists' p l) := decidable_of_iff _ (my_list_pexists_iff p l)
dbfcae58899695273ff73a4c9910223e0488c1dc
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Init/Data/List/Basic.lean
c04cb9f7290c023a72dac1039eb3c9705b15a5b6
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
11,640
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.SimpLemmas import Init.Data.Nat.Basic open Decidable List universes u v w variable {α : Type u} {β : Type v} {γ : Type w} namespace List @[simp] theorem length_nil : length ([] : List α) = 0 := rfl def reverseAux : List α → List α → List α | [], r => r | a::l, r => reverseAux l (a::r) def reverse (as : List α) :List α := reverseAux as [] protected def append (as bs : List α) : List α := reverseAux as.reverse bs instance : Append (List α) := ⟨List.append⟩ theorem reverseAux_reverseAux_nil (as bs : List α) : reverseAux (reverseAux as bs) [] = reverseAux bs as := by induction as generalizing bs with | nil => rfl | cons a as ih => simp [reverseAux, ih] @[simp] theorem nil_append (as : List α) : [] ++ as = as := rfl @[simp] theorem append_nil (as : List α) : as ++ [] = as := by show reverseAux (reverseAux as []) [] = as simp [reverseAux_reverseAux_nil, reverseAux] theorem reverseAux_reverseAux (as bs cs : List α) : reverseAux (reverseAux as bs) cs = reverseAux bs (reverseAux (reverseAux as []) cs) := by induction as generalizing bs cs with | nil => rfl | cons a as ih => simp [reverseAux, ih (a::bs), ih [a]] @[simp] theorem cons_append (a : α) (as bs : List α) : (a::as) ++ bs = a::(as ++ bs) := reverseAux_reverseAux as [a] bs theorem append_assoc (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs) := by induction as with | nil => rfl | cons a as ih => simp [ih] instance : EmptyCollection (List α) := ⟨List.nil⟩ protected def erase {α} [BEq α] : List α → α → List α | [], b => [] | a::as, b => match a == b with | true => as | false => a :: List.erase as b def eraseIdx : List α → Nat → List α | [], _ => [] | a::as, 0 => as | a::as, n+1 => a :: eraseIdx as n def isEmpty : List α → Bool | [] => true | _ :: _ => false @[specialize] def map (f : α → β) : List α → List β | [] => [] | a::as => f a :: map f as @[specialize] def map₂ (f : α → β → γ) : List α → List β → List γ | [], _ => [] | _, [] => [] | a::as, b::bs => f a b :: map₂ f as bs def join : List (List α) → List α | [] => [] | a :: as => a ++ join as @[specialize] def filterMap (f : α → Option β) : List α → List β | [] => [] | a::as => match f a with | none => filterMap f as | some b => b :: filterMap f as @[specialize] def filterAux (p : α → Bool) : List α → List α → List α | [], rs => rs.reverse | a::as, rs => match p a with | true => filterAux p as (a::rs) | false => filterAux p as rs @[inline] def filter (p : α → Bool) (as : List α) : List α := filterAux p as [] @[specialize] def partitionAux (p : α → Bool) : List α → List α × List α → List α × List α | [], (bs, cs) => (bs.reverse, cs.reverse) | a::as, (bs, cs) => match p a with | true => partitionAux p as (a::bs, cs) | false => partitionAux p as (bs, a::cs) @[inline] def partition (p : α → Bool) (as : List α) : List α × List α := partitionAux p as ([], []) def dropWhile (p : α → Bool) : List α → List α | [] => [] | a::l => match p a with | true => dropWhile p l | false => a::l def find? (p : α → Bool) : List α → Option α | [] => none | a::as => match p a with | true => some a | false => find? p as def findSome? (f : α → Option β) : List α → Option β | [] => none | a::as => match f a with | some b => some b | none => findSome? f as def replace [BEq α] : List α → α → α → List α | [], _, _ => [] | a::as, b, c => match a == b with | true => c::as | false => a :: (replace as b c) def elem [BEq α] (a : α) : List α → Bool | [] => false | b::bs => match a == b with | true => true | false => elem a bs def notElem [BEq α] (a : α) (as : List α) : Bool := !(as.elem a) abbrev contains [BEq α] (as : List α) (a : α) : Bool := elem a as def eraseDupsAux {α} [BEq α] : List α → List α → List α | [], bs => bs.reverse | a::as, bs => match bs.elem a with | true => eraseDupsAux as bs | false => eraseDupsAux as (a::bs) def eraseDups {α} [BEq α] (as : List α) : List α := eraseDupsAux as [] def eraseRepsAux {α} [BEq α] : α → List α → List α → List α | a, [], rs => (a::rs).reverse | a, a'::as, rs => match a == a' with | true => eraseRepsAux a as rs | false => eraseRepsAux a' as (a::rs) /-- Erase repeated adjacent elements. -/ def eraseReps {α} [BEq α] : List α → List α | [] => [] | a::as => eraseRepsAux a as [] @[specialize] def spanAux (p : α → Bool) : List α → List α → List α × List α | [], rs => (rs.reverse, []) | a::as, rs => match p a with | true => spanAux p as (a::rs) | false => (rs.reverse, a::as) @[inline] def span (p : α → Bool) (as : List α) : List α × List α := spanAux p as [] @[specialize] def groupByAux (eq : α → α → Bool) : List α → List (List α) → List (List α) | a::as, (ag::g)::gs => match eq a ag with | true => groupByAux eq as ((a::ag::g)::gs) | false => groupByAux eq as ([a]::(ag::g).reverse::gs) | _, gs => gs.reverse @[specialize] def groupBy (p : α → α → Bool) : List α → List (List α) | [] => [] | a::as => groupByAux p as [[a]] def lookup [BEq α] : α → List (α × β) → Option β | _, [] => none | a, (k,b)::es => match a == k with | true => some b | false => lookup a es def removeAll [BEq α] (xs ys : List α) : List α := xs.filter (fun x => ys.notElem x) def drop : Nat → List α → List α | 0, a => a | n+1, [] => [] | n+1, a::as => drop n as def take : Nat → List α → List α | 0, a => [] | n+1, [] => [] | n+1, a::as => a :: take n as @[specialize] def foldr (f : α → β → β) (init : β) : List α → β | [] => init | a :: l => f a (foldr f init l) @[inline] def any (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a || r) false l @[inline] def all (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a && r) true l def or (bs : List Bool) : Bool := bs.any id def and (bs : List Bool) : Bool := bs.all id def zipWith (f : α → β → γ) : List α → List β → List γ | x::xs, y::ys => f x y :: zipWith f xs ys | _, _ => [] def zip : List α → List β → List (Prod α β) := zipWith Prod.mk def unzip : List (α × β) → List α × List β | [] => ([], []) | (a, b) :: t => match unzip t with | (al, bl) => (a::al, b::bl) def rangeAux : Nat → List Nat → List Nat | 0, ns => ns | n+1, ns => rangeAux n (n::ns) def range (n : Nat) : List Nat := rangeAux n [] def iota : Nat → List Nat | 0 => [] | m@(n+1) => m :: iota n def enumFrom : Nat → List α → List (Nat × α) | n, [] => nil | n, x :: xs => (n, x) :: enumFrom (n + 1) xs def enum : List α → List (Nat × α) := enumFrom 0 def init : List α → List α | [] => [] | [a] => [] | a::l => a::init l def intersperse (sep : α) : List α → List α | [] => [] | [x] => [x] | x::xs => x :: sep :: intersperse sep xs def intercalate (sep : List α) (xs : List (List α)) : List α := join (intersperse sep xs) @[inline] protected def bind {α : Type u} {β : Type v} (a : List α) (b : α → List β) : List β := join (map b a) @[inline] protected def pure {α : Type u} (a : α) : List α := [a] inductive lt [LT α] : List α → List α → Prop where | nil (b : α) (bs : List α) : lt [] (b::bs) | head {a : α} (as : List α) {b : α} (bs : List α) : a < b → lt (a::as) (b::bs) | tail {a : α} {as : List α} {b : α} {bs : List α} : ¬ a < b → ¬ b < a → lt as bs → lt (a::as) (b::bs) instance [LT α] : LT (List α) := ⟨List.lt⟩ instance hasDecidableLt [LT α] [h : DecidableRel (α:=α) (·<·)] : (l₁ l₂ : List α) → Decidable (l₁ < l₂) | [], [] => isFalse (fun h => nomatch h) | [], b::bs => isTrue (List.lt.nil _ _) | a::as, [] => isFalse (fun h => nomatch h) | a::as, b::bs => match h a b with | isTrue h₁ => isTrue (List.lt.head _ _ h₁) | isFalse h₁ => match h b a with | isTrue h₂ => isFalse (fun h => match h with | List.lt.head _ _ h₁' => absurd h₁' h₁ | List.lt.tail _ h₂' _ => absurd h₂ h₂') | isFalse h₂ => match hasDecidableLt as bs with | isTrue h₃ => isTrue (List.lt.tail h₁ h₂ h₃) | isFalse h₃ => isFalse (fun h => match h with | List.lt.head _ _ h₁' => absurd h₁' h₁ | List.lt.tail _ _ h₃' => absurd h₃' h₃) @[reducible] protected def le [LT α] (a b : List α) : Prop := ¬ b < a instance [LT α] : LE (List α) := ⟨List.le⟩ instance [LT α] [h : DecidableRel ((· < ·) : α → α → Prop)] : (l₁ l₂ : List α) → Decidable (l₁ ≤ l₂) := fun a b => inferInstanceAs (Decidable (Not _)) /-- `isPrefixOf l₁ l₂` returns `true` Iff `l₁` is a prefix of `l₂`. -/ def isPrefixOf [BEq α] : List α → List α → Bool | [], _ => true | _, [] => false | a::as, b::bs => a == b && isPrefixOf as bs /-- `isSuffixOf l₁ l₂` returns `true` Iff `l₁` is a suffix of `l₂`. -/ def isSuffixOf [BEq α] (l₁ l₂ : List α) : Bool := isPrefixOf l₁.reverse l₂.reverse @[specialize] def isEqv : List α → List α → (α → α → Bool) → Bool | [], [], _ => true | a::as, b::bs, eqv => eqv a b && isEqv as bs eqv | _, _, eqv => false protected def beq [BEq α] : List α → List α → Bool | [], [] => true | a::as, b::bs => a == b && List.beq as bs | _, _ => false instance [BEq α] : BEq (List α) := ⟨List.beq⟩ def replicate {α : Type u} (n : Nat) (a : α) : List α := let rec loop : Nat → List α → List α | 0, as => as | n+1, as => loop n (a::as) loop n [] def dropLast {α} : List α → List α | [] => [] | [a] => [] | a::as => a :: dropLast as @[simp] theorem length_replicate (n : Nat) (a : α) : (replicate n a).length = n := let rec aux (n : Nat) (as : List α) : (replicate.loop a n as).length = n + as.length := by induction n generalizing as with | zero => simp [replicate.loop] | succ n ih => simp [replicate.loop, ih, Nat.succ_add, Nat.add_succ] aux n [] @[simp] theorem length_concat (as : List α) (a : α) : (concat as a).length = as.length + 1 := by induction as with | nil => rfl | cons x xs ih => simp [concat, ih] @[simp] theorem length_set (as : List α) (i : Nat) (a : α) : (as.set i a).length = as.length := by induction as generalizing i with | nil => rfl | cons x xs ih => cases i with | zero => rfl | succ i => simp [set, ih] @[simp] theorem length_dropLast (as : List α) : as.dropLast.length = as.length - 1 := by match as with | [] => rfl | [a] => rfl | a::b::as => have ih := length_dropLast (b::as) simp[dropLast, ih] rfl def maximum? [LT α] [DecidableRel (@LT.lt α _)] : List α → Option α | [] => none | a::as => some <| as.foldl max a def minimum? [LE α] [DecidableRel (@LE.le α _)] : List α → Option α | [] => none | a::as => some <| as.foldl min a end List
8b47863cc9529ab5e4d35996f62819633a704925
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/category_theory/limits/shapes/binary_products.lean
65495b40786fb9b116b27a85aa27e6db6f72897b
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
18,227
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.terminal /-! # Binary (co)products We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. -/ universes v u open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq, derive inhabited] inductive walking_pair : Type v | left | right open walking_pair instance fintype_walking_pair : fintype walking_pair := { elems := [left, right].to_finset, complete := λ x, by { cases x; simp } } variables {C : Type u} [category.{v} C] /-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/ def pair (X Y : C) : discrete walking_pair ⥤ C := functor.of_function (λ j, walking_pair.cases_on j X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj left = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj right = Y := rfl section variables {F G : discrete walking_pair.{v} ⥤ C} (f : F.obj left ⟶ G.obj left) (g : F.obj right ⟶ G.obj right) /-- The natural transformation between two functors out of the walking pair, specified by its components. -/ def map_pair : F ⟶ G := { app := λ j, match j with | left := f | right := g end } @[simp] lemma map_pair_left : (map_pair f g).app left = f := rfl @[simp] lemma map_pair_right : (map_pair f g).app right = g := rfl /-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/ @[simps] def map_pair_iso (f : F.obj left ≅ G.obj left) (g : F.obj right ≅ G.obj right) : F ≅ G := { hom := map_pair f.hom g.hom, inv := map_pair f.inv g.inv, hom_inv_id' := begin ext j, cases j; { dsimp, simp, } end, inv_hom_id' := begin ext j, cases j; { dsimp, simp, } end } end section variables {D : Type u} [category.{v} D] /-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/ def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) end /-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/ def diagram_iso_pair (F : discrete walking_pair ⥤ C) : F ≅ pair (F.obj walking_pair.left) (F.obj walking_pair.right) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) /-- A binary fan is just a cone on a diagram indexing a product. -/ abbreviation binary_fan (X Y : C) := cone (pair X Y) /-- The first projection of a binary fan. -/ abbreviation binary_fan.fst {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.left /-- The second projection of a binary fan. -/ abbreviation binary_fan.snd {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.right lemma binary_fan.is_limit.hom_ext {W X Y : C} {s : binary_fan X Y} (h : is_limit s) {f g : W ⟶ s.X} (h₁ : f ≫ s.fst = g ≫ s.fst) (h₂ : f ≫ s.snd = g ≫ s.snd) : f = g := h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂ /-- A binary cofan is just a cocone on a diagram indexing a coproduct. -/ abbreviation binary_cofan (X Y : C) := cocone (pair X Y) /-- The first inclusion of a binary cofan. -/ abbreviation binary_cofan.inl {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.left /-- The second inclusion of a binary cofan. -/ abbreviation binary_cofan.inr {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.right lemma binary_cofan.is_colimit.hom_ext {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) {f g : s.X ⟶ W} (h₁ : s.inl ≫ f = s.inl ≫ g) (h₂ : s.inr ≫ f = s.inr ≫ g) : f = g := h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂ variables {X Y : C} /-- A binary fan with vertex `P` consists of the two projections `π₁ : P ⟶ X` and `π₂ : P ⟶ Y`. -/ def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, walking_pair.cases_on j π₁ π₂ }} /-- A binary cofan with vertex `P` consists of the two inclusions `ι₁ : X ⟶ P` and `ι₂ : Y ⟶ P`. -/ def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, walking_pair.cases_on j ι₁ ι₂ }} @[simp] lemma binary_fan.mk_π_app_left {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.left = π₁ := rfl @[simp] lemma binary_fan.mk_π_app_right {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.right = π₂ := rfl @[simp] lemma binary_cofan.mk_ι_app_left {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.left = ι₁ := rfl @[simp] lemma binary_cofan.mk_ι_app_right {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.right = ι₂ := rfl /-- If `s` is a limit binary fan over `X` and `Y`, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ s.X` satisfying `l ≫ s.fst = f` and `l ≫ s.snd = g`. -/ def binary_fan.is_limit.lift' {W X Y : C} {s : binary_fan X Y} (h : is_limit s) (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ s.X // l ≫ s.fst = f ∧ l ≫ s.snd = g} := ⟨h.lift $ binary_fan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If `s` is a colimit binary cofan over `X` and `Y`,, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : s.X ⟶ W` satisfying `s.inl ≫ l = f` and `s.inr ≫ l = g`. -/ def binary_cofan.is_colimit.desc' {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) (f : X ⟶ W) (g : Y ⟶ W) : {l : s.X ⟶ W // s.inl ≫ l = f ∧ s.inr ≫ l = g} := ⟨h.desc $ binary_cofan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If we have chosen a product of `X` and `Y`, we can access it using `prod X Y` or `X ⨯ Y`. -/ abbreviation prod (X Y : C) [has_limit (pair X Y)] := limit (pair X Y) /-- If we have chosen a coproduct of `X` and `Y`, we can access it using `coprod X Y ` or `X ⨿ Y`. -/ abbreviation coprod (X Y : C) [has_colimit (pair X Y)] := colimit (pair X Y) notation X ` ⨯ `:20 Y:20 := prod X Y notation X ` ⨿ `:20 Y:20 := coprod X Y /-- The projection map to the first component of the product. -/ abbreviation prod.fst {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ X := limit.π (pair X Y) walking_pair.left /-- The projecton map to the second component of the product. -/ abbreviation prod.snd {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ Y := limit.π (pair X Y) walking_pair.right /-- The inclusion map from the first component of the coproduct. -/ abbreviation coprod.inl {X Y : C} [has_colimit (pair X Y)] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.left /-- The inclusion map from the second component of the coproduct. -/ abbreviation coprod.inr {X Y : C} [has_colimit (pair X Y)] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.right @[ext] lemma prod.hom_ext {W X Y : C} [has_limit (pair X Y)] {f g : W ⟶ X ⨯ Y} (h₁ : f ≫ prod.fst = g ≫ prod.fst) (h₂ : f ≫ prod.snd = g ≫ prod.snd) : f = g := binary_fan.is_limit.hom_ext (limit.is_limit _) h₁ h₂ @[ext] lemma coprod.hom_ext {W X Y : C} [has_colimit (pair X Y)] {f g : X ⨿ Y ⟶ W} (h₁ : coprod.inl ≫ f = coprod.inl ≫ g) (h₂ : coprod.inr ≫ f = coprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (colimit.is_colimit _) h₁ h₂ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `prod.lift f g : W ⟶ X ⨯ Y`. -/ abbreviation prod.lift {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `coprod.desc f g : X ⨿ Y ⟶ W`. -/ abbreviation coprod.desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) @[simp, reassoc] lemma prod.lift_fst {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.fst = f := limit.lift_π _ _ @[simp, reassoc] lemma prod.lift_snd {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.snd = g := limit.lift_π _ _ @[simp, reassoc] lemma coprod.inl_desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inl ≫ coprod.desc f g = f := colimit.ι_desc _ _ @[simp, reassoc] lemma coprod.inr_desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inr ≫ coprod.desc f g = g := colimit.ι_desc _ _ instance prod.mono_lift_of_mono_left {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_fst _ _ instance prod.mono_lift_of_mono_right {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_snd _ _ instance coprod.epi_desc_of_epi_left {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inl_desc _ _ instance coprod.epi_desc_of_epi_right {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inr_desc _ _ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ X ⨯ Y` satisfying `l ≫ prod.fst = f` and `l ≫ prod.snd = g`. -/ def prod.lift' {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ X ⨯ Y // l ≫ prod.fst = f ∧ l ≫ prod.snd = g} := ⟨prod.lift f g, prod.lift_fst _ _, prod.lift_snd _ _⟩ /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : X ⨿ Y ⟶ W` satisfying `coprod.inl ≫ l = f` and `coprod.inr ≫ l = g`. -/ def coprod.desc' {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : {l : X ⨿ Y ⟶ W // coprod.inl ≫ l = f ∧ coprod.inr ≫ l = g} := ⟨coprod.desc f g, coprod.inl_desc _ _, coprod.inr_desc _ _⟩ /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : X ⟶ Z` induces a morphism `prod.map f g : W ⨯ X ⟶ Y ⨯ Z`. -/ abbreviation prod.map {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim.map (map_pair f g) /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : W ⟶ Z` induces a morphism `coprod.map f g : W ⨿ X ⟶ Y ⨿ Z`. -/ abbreviation coprod.map {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim.map (map_pair f g) @[reassoc] lemma prod.map_fst {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.fst = prod.fst ≫ f := by simp @[reassoc] lemma prod.map_snd {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.snd = prod.snd ≫ g := by simp @[reassoc] lemma coprod.inl_map {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inl ≫ coprod.map f g = f ≫ coprod.inl := by simp @[reassoc] lemma coprod.inr_map {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inr ≫ coprod.map f g = g ≫ coprod.inr := by simp variables (C) /-- `has_binary_products` represents a choice of product for every pair of objects. -/ class has_binary_products := (has_limits_of_shape : has_limits_of_shape.{v} (discrete walking_pair) C) /-- `has_binary_coproducts` represents a choice of coproduct for every pair of objects. -/ class has_binary_coproducts := (has_colimits_of_shape : has_colimits_of_shape.{v} (discrete walking_pair) C) attribute [instance] has_binary_products.has_limits_of_shape has_binary_coproducts.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance [has_finite_products.{v} C] : has_binary_products.{v} C := { has_limits_of_shape := by apply_instance } @[priority 100] -- see Note [lower instance priority] instance [has_finite_coproducts.{v} C] : has_binary_coproducts.{v} C := { has_colimits_of_shape := by apply_instance } /-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/ def has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] : has_binary_products.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } } /-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/ def has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] : has_binary_coproducts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } } section variables {C} [has_binary_products.{v} C] local attribute [tidy] tactic.case_bash /-- The binary product functor. -/ @[simps] def prod_functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨯ Y, map := λ Y Z, prod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, prod.map f (𝟙 T) }} /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } @[simp] lemma prod.symmetry' (P Q : C) : prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma prod.symmetry (P Q : C) : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } lemma prod.pentagon (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y⨯Z)).hom := by tidy lemma prod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by tidy variables [has_terminal.{v} C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } lemma prod.triangle (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts.{v} C] local attribute [tidy] tactic.case_bash /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } @[simp] lemma coprod.symmetry' (P Q : C) : coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X⨿Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W⨿X) Y Z).hom ≫ (coprod.associator W X (Y⨿Z)).hom := by tidy lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by tidy variables [has_initial.{v} C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end end category_theory.limits
df1682d62e5498b428dfc86cc3d30e06dbd4bce9
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/measure_theory/integral/integrable_on.lean
30c6ad7aa1efd498dc8fd3b63aaa1e303b86ede4
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,145
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.function.l1_space import analysis.normed_space.indicator_function /-! # Functions integrable on a set and at a filter We define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter ennreal measure_theory variables {α β E F : Type*} [measurable_space α] section variables [measurable_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α} /-- A function `f` is measurable at filter `l` w.r.t. a measure `μ` if it is ae-measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/ def measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, ae_measurable f (μ.restrict s) @[simp] lemma measurable_at_bot {f : α → β} : measurable_at_filter f ⊥ μ := ⟨∅, mem_bot, by simp⟩ protected lemma measurable_at_filter.eventually (h : measurable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, ae_measurable f (μ.restrict s) := (eventually_lift'_powerset' $ λ s t, ae_measurable.mono_set).2 h protected lemma measurable_at_filter.filter_mono (h : measurable_at_filter f l μ) (h' : l' ≤ l) : measurable_at_filter f l' μ := let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩ protected lemma ae_measurable.measurable_at_filter (h : ae_measurable f μ) : measurable_at_filter f l μ := ⟨univ, univ_mem, by rwa measure.restrict_univ⟩ lemma ae_measurable.measurable_at_filter_of_mem {s} (h : ae_measurable f (μ.restrict s)) (hl : s ∈ l) : measurable_at_filter f l μ := ⟨s, hl, h⟩ protected lemma measurable.measurable_at_filter (h : measurable f) : measurable_at_filter f l μ := h.ae_measurable.measurable_at_filter end namespace measure_theory section normed_group lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : is_finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_group E] [measurable_space E] {f g : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is almost everywhere measurable on `s` and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty : integrable_on f ∅ μ := by simp [integrable_on, integrable_zero_measure] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst (le_refl _) lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ restrict_mono_ae hst lemma integrable_on.congr_set_ae (h : integrable_on f t μ) (hst : s =ᵐ[μ] t) : integrable_on f s μ := h.mono_set_ae hst.le lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.restrict (h : integrable_on f s μ) (hs : measurable_set s) : integrable_on f s (μ.restrict t) := by { rw [integrable_on, measure.restrict_restrict hs], exact h.mono_set (inter_subset_left _ _) } lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_singleton_iff {x : α} [measurable_singleton_class α]: integrable_on f {x} μ ↔ f x = 0 ∨ μ {x} < ∞ := begin have : f =ᵐ[μ.restrict {x}] (λ y, f x), { filter_upwards [ae_restrict_mem (measurable_set_singleton x)], assume a ha, simp only [mem_singleton_iff.1 ha] }, rw [integrable_on, integrable_congr this, integrable_const_iff], simp, end @[simp] lemma integrable_on_finite_union {s : set β} (hs : finite s) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_union {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_union s.finite_to_set lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ lemma integrable_indicator_iff (hs : measurable_set s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, ae_measurable_indicator_iff hs] lemma integrable_on.indicator (h : integrable_on f s μ) (hs : measurable_set s) : integrable (indicator s f) μ := (integrable_indicator_iff hs).2 h lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) : integrable (indicator s f) μ := h.integrable_on.indicator hs lemma integrable_indicator_const_Lp {E} [normed_group E] [measurable_space E] [borel_space E] [second_countable_topology E] {p : ℝ≥0∞} {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) : integrable (indicator_const_Lp p hs hμs c) μ := begin rw [integrable_congr indicator_const_Lp_coe_fn, integrable_indicator_iff hs, integrable_on, integrable_const_iff, lt_top_iff_ne_top], right, simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply] using hμs, end lemma integrable_on_Lp_of_measure_ne_top {E} [normed_group E] [measurable_space E] [borel_space E] [second_countable_topology E] {p : ℝ≥0∞} {s : set α} (f : Lp E p μ) (hp : 1 ≤ p) (hμs : μ s ≠ ∞) : integrable_on f s μ := begin refine mem_ℒp_one_iff_integrable.mp _, have hμ_restrict_univ : (μ.restrict s) set.univ < ∞, by simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply, lt_top_iff_ne_top], haveI hμ_finite : is_finite_measure (μ.restrict s) := ⟨hμ_restrict_univ⟩, exact ((Lp.mem_ℒp _).restrict s).mem_ℒp_of_exponent_le hp, end /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, integrable_on f s μ := by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst } lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, rfl⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in (l.lift' powerset), ∀ x ∈ s, ∥f x∥ ≤ C, from hf.imp (λ C hC, eventually_lift'_powerset.2 ⟨_, hC, λ t, id⟩), rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_lift' with ⟨s, hsl, hsm, hfm, hμ, hC⟩, refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩, exact C, rw [ae_restrict_eq hsm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left) hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter variables [borel_space E] [second_countable_topology E] lemma integrable_add_of_disjoint {f g : α → E} (h : disjoint (support f) (support g)) (hf : measurable f) (hg : measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩, { rw ← indicator_add_eq_left h, exact hfg.indicator (measurable_set_support hf) }, { rw ← indicator_add_eq_right h, exact hfg.indicator (measurable_set_support hg) } end end normed_group end measure_theory open measure_theory variables [measurable_space E] [normed_group E] /-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is integrable on `s`. -/ lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α} (hs : is_compact s) {f : α → E} (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) : integrable_on f s μ := is_compact.induction_on hs integrable_on_empty (λ s t hst ht, ht.mono_set hst) (λ s t hs ht, hs.union ht) hf /-- A function which is continuous on a set `s` is almost everywhere measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [borel_space E] {f : α → E} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_measurable f (μ.restrict s) := begin refine ⟨indicator s f, _, (indicator_ae_eq_restrict hs).symm⟩, apply measurable_of_is_open, assume t ht, obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := _root_.continuous_on_iff'.1 hf t ht, rw [indicator_preimage, set.ite, hu], exact (u_open.measurable_set.inter hs).union ((measurable_zero ht.measurable_set).diff hs) end lemma continuous_on.integrable_at_nhds_within [topological_space α] [opens_measurable_space α] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _; exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_measurable ht⟩ (μ.finite_at_nhds_within _ _) /-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any locally finite measure. -/ lemma continuous_on.integrable_on_compact [topological_space α] [opens_measurable_space α] [borel_space E] [t2_space α] {μ : measure α} [is_locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : integrable_on f s μ := hs.integrable_on_of_nhds_within $ λ x hx, hf.integrable_at_nhds_within hs.measurable_set hx lemma continuous_on.integrable_on_Icc [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous_on f (Icc a b)) : integrable_on f (Icc a b) μ := hf.integrable_on_compact is_compact_Icc lemma continuous_on.integrable_on_interval [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous_on f (interval a b)) : integrable_on f (interval a b) μ := hf.integrable_on_compact is_compact_interval /-- A continuous function `f` is integrable on any compact set with respect to any locally finite measure. -/ lemma continuous.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous f) : integrable_on f s μ := hf.continuous_on.integrable_on_compact hs lemma continuous.integrable_on_Icc [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous f) : integrable_on f (Icc a b) μ := hf.integrable_on_compact is_compact_Icc lemma continuous.integrable_on_interval [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous f) : integrable_on f (interval a b) μ := hf.integrable_on_compact is_compact_interval /-- A continuous function with compact closure of the support is integrable on the whole space. -/ lemma continuous.integrable_of_compact_closure_support [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {f : α → E} (hf : continuous f) (hfc : is_compact (closure $ support f)) : integrable f μ := begin rw [← indicator_eq_self.2 (@subset_closure _ _ (support f)), integrable_indicator_iff is_closed_closure.measurable_set], { exact hf.integrable_on_compact hfc }, { apply_instance } end section variables [topological_space α] [opens_measurable_space α] {μ : measure α} {s t : set α} {f g : α → ℝ} lemma measure_theory.integrable_on.mul_continuous_on_of_subset (hf : integrable_on f s μ) (hg : continuous_on g t) (hs : measurable_set s) (ht : is_compact t) (hst : s ⊆ t) : integrable_on (λ x, f x * g x) s μ := begin rcases is_compact.exists_bound_of_continuous_on ht hg with ⟨C, hC⟩, rw [integrable_on, ← mem_ℒp_one_iff_integrable] at hf ⊢, have : ∀ᵐ x ∂(μ.restrict s), ∥f x * g x∥ ≤ C * ∥f x∥, { filter_upwards [ae_restrict_mem hs], assume x hx, rw [real.norm_eq_abs, abs_mul, mul_comm, real.norm_eq_abs], apply mul_le_mul_of_nonneg_right (hC x (hst hx)) (abs_nonneg _) }, exact mem_ℒp.of_le_mul hf (hf.ae_measurable.mul ((hg.mono hst).ae_measurable hs)) this, end lemma measure_theory.integrable_on.mul_continuous_on [t2_space α] (hf : integrable_on f s μ) (hg : continuous_on g s) (hs : is_compact s) : integrable_on (λ x, f x * g x) s μ := hf.mul_continuous_on_of_subset hg hs.measurable_set hs (subset.refl _) lemma measure_theory.integrable_on.continuous_on_mul_of_subset (hf : integrable_on f s μ) (hg : continuous_on g t) (hs : measurable_set s) (ht : is_compact t) (hst : s ⊆ t) : integrable_on (λ x, g x * f x) s μ := by simpa [mul_comm] using hf.mul_continuous_on_of_subset hg hs ht hst lemma measure_theory.integrable_on.continuous_on_mul [t2_space α] (hf : integrable_on f s μ) (hg : continuous_on g s) (hs : is_compact s) : integrable_on (λ x, g x * f x) s μ := hf.continuous_on_mul_of_subset hg hs.measurable_set hs (subset.refl _) end section monotone variables [topological_space α] [borel_space α] [borel_space E] [conditionally_complete_linear_order α] [conditionally_complete_linear_order E] [order_topology α] [order_topology E] [second_countable_topology E] {μ : measure α} [is_locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} include hs lemma integrable_on_compact_of_monotone_on (hmono : ∀ ⦃x y⦄, x ∈ s → y ∈ s → x ≤ y → f x ≤ f y) : integrable_on f s μ := begin by_cases h : s.nonempty, { have hbelow : bdd_below (f '' s) := ⟨f (Inf s), λ x ⟨y, hy, hyx⟩, hyx ▸ hmono (hs.Inf_mem h) hy (cInf_le hs.bdd_below hy)⟩, have habove : bdd_above (f '' s) := ⟨f (Sup s), λ x ⟨y, hy, hyx⟩, hyx ▸ hmono hy (hs.Sup_mem h) (le_cSup hs.bdd_above hy)⟩, have : metric.bounded (f '' s) := metric.bounded_of_bdd_above_of_bdd_below habove hbelow, rcases bounded_iff_forall_norm_le.mp this with ⟨C, hC⟩, exact integrable.mono' (continuous_const.integrable_on_compact hs) (ae_measurable_restrict_of_monotone_on hs.measurable_set hmono) ((ae_restrict_iff' hs.measurable_set).mpr $ ae_of_all _ $ λ y hy, hC (f y) (mem_image_of_mem f hy)) }, { rw set.not_nonempty_iff_eq_empty at h, rw h, exact integrable_on_empty } end lemma integrable_on_compact_of_antimono_on (hmono : ∀ ⦃x y⦄, x ∈ s → y ∈ s → x ≤ y → f y ≤ f x) : integrable_on f s μ := @integrable_on_compact_of_monotone_on α (order_dual E) _ _ ‹_› _ _ ‹_› _ _ _ _ ‹_› _ _ _ hs _ hmono lemma integrable_on_compact_of_monotone (hmono : monotone f) : integrable_on f s μ := integrable_on_compact_of_monotone_on hs (λ x y _ _ hxy, hmono hxy) alias integrable_on_compact_of_monotone ← monotone.integrable_on_compact lemma integrable_on_compact_of_antimono (hmono : ∀ ⦃x y⦄, x ≤ y → f y ≤ f x) : integrable_on f s μ := @integrable_on_compact_of_monotone α (order_dual E) _ _ ‹_› _ _ ‹_› _ _ _ _ ‹_› _ _ _ hs _ hmono end monotone
0941d0d8321c6897301cdc971a044399d65b6991
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/types.lean
661940114190dc6a86f451dcd73b18c01821775d
[ "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
15,180
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.limits.shapes.images import category_theory.filtered import tactic.equiv_rw universes u open category_theory open category_theory.limits namespace category_theory.limits.types variables {J : Type u} [small_category J] /-- (internal implementation) the limit cone of a functor, implemented as flat sections of a pi type -/ def limit_cone (F : J ⥤ Type u) : cone F := { X := F.sections, π := { app := λ j u, u.val j } } local attribute [elab_simple] congr_fun /-- (internal implementation) the fact that the proposed limit cone is the limit -/ def limit_cone_is_limit (F : J ⥤ Type u) : is_limit (limit_cone F) := { lift := λ s v, ⟨λ j, s.π.app j v, λ j j' f, congr_fun (cone.w s f) _⟩, uniq' := by { intros, ext x j, exact congr_fun (w j) x } } /-- The category of types has all limits. See https://stacks.math.columbia.edu/tag/002U. -/ instance : has_limits (Type u) := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } /-- The equivalence between a limiting cone of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ def is_limit_equiv_sections {F : J ⥤ Type u} {c : cone F} (t : is_limit c) : c.X ≃ F.sections := (is_limit.cone_point_unique_up_to_iso t (limit_cone_is_limit F)).to_equiv @[simp] lemma is_limit_equiv_sections_apply {F : J ⥤ Type u} {c : cone F} (t : is_limit c) (j : J) (x : c.X) : (((is_limit_equiv_sections t) x) : Π j, F.obj j) j = c.π.app j x := rfl @[simp] lemma is_limit_equiv_sections_symm_apply {F : J ⥤ Type u} {c : cone F} (t : is_limit c) (x : F.sections) (j : J) : c.π.app j ((is_limit_equiv_sections t).symm x) = (x : Π j, F.obj j) j := begin equiv_rw (is_limit_equiv_sections t).symm at x, simp, end /-- The equivalence between the abstract limit of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ noncomputable def limit_equiv_sections (F : J ⥤ Type u) : (limit F : Type u) ≃ F.sections := is_limit_equiv_sections (limit.is_limit _) @[simp] lemma limit_equiv_sections_apply (F : J ⥤ Type u) (x : limit F) (j : J) : (((limit_equiv_sections F) x) : Π j, F.obj j) j = limit.π F j x := rfl @[simp] lemma limit_equiv_sections_symm_apply (F : J ⥤ Type u) (x : F.sections) (j : J) : limit.π F j ((limit_equiv_sections F).symm x) = (x : Π j, F.obj j) j := is_limit_equiv_sections_symm_apply _ _ _ /-- Construct a term of `limit F : Type u` from a family of terms `x : Π j, F.obj j` which are "coherent": `∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j'`. -/ @[ext] noncomputable def limit.mk (F : J ⥤ Type u) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') : (limit F : Type u) := (limit_equiv_sections F).symm ⟨x, h⟩ @[simp] lemma limit.π_mk (F : J ⥤ Type u) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') (j) : limit.π F j (limit.mk F x h) = x j := by { dsimp [limit.mk], simp, } -- PROJECT: prove this for concrete categories where the forgetful functor preserves limits @[ext] lemma limit_ext (F : J ⥤ Type u) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) : x = y := begin apply (limit_equiv_sections F).injective, ext j, simp [w j], end lemma limit_ext_iff (F : J ⥤ Type u) (x y : limit F) : x = y ↔ (∀ j, limit.π F j x = limit.π F j y) := ⟨λ t _, t ▸ rfl, limit_ext _ _ _⟩ -- TODO: are there other limits lemmas that should have `_apply` versions? -- Can we generate these like with `@[reassoc]`? -- PROJECT: prove these for any concrete category where the forgetful functor preserves limits? @[simp] lemma limit.w_apply {F : J ⥤ Type u} {j j' : J} {x : limit F} (f : j ⟶ j') : F.map f (limit.π F j x) = limit.π F j' x := congr_fun (limit.w F f) x @[simp] lemma limit.lift_π_apply (F : J ⥤ Type u) (s : cone F) (j : J) (x : s.X) : limit.π F j (limit.lift F s x) = s.π.app j x := congr_fun (limit.lift_π s j) x @[simp] lemma limit.map_π_apply {F G : J ⥤ Type u} (α : F ⟶ G) (j : J) (x) : limit.π G j (lim_map α x) = α.app j (limit.π F j x) := congr_fun (lim_map_π α j) x /-- The relation defining the quotient type which implements the colimit of a functor `F : J ⥤ Type u`. See `category_theory.limits.types.quot`. -/ def quot.rel (F : J ⥤ Type u) : (Σ j, F.obj j) → (Σ j, F.obj j) → Prop := (λ p p', ∃ f : p.1 ⟶ p'.1, p'.2 = F.map f p.2) /-- A quotient type implementing the colimit of a functor `F : J ⥤ Type u`, as pairs `⟨j, x⟩` where `x : F.obj j`, modulo the equivalence relation generated by `⟨j, x⟩ ~ ⟨j', x'⟩` whenever there is a morphism `f : j ⟶ j'` so `F.map f x = x'`. -/ @[nolint has_inhabited_instance] def quot (F : J ⥤ Type u) : Type u := @quot (Σ j, F.obj j) (quot.rel F) /-- (internal implementation) the colimit cocone of a functor, implemented as a quotient of a sigma type -/ def colimit_cocone (F : J ⥤ Type u) : cocone F := { X := quot F, ι := { app := λ j x, quot.mk _ ⟨j, x⟩, naturality' := λ j j' f, funext $ λ x, eq.symm (quot.sound ⟨f, rfl⟩) } } local attribute [elab_with_expected_type] quot.lift /-- (internal implementation) the fact that the proposed colimit cocone is the colimit -/ def colimit_cocone_is_colimit (F : J ⥤ Type u) : is_colimit (colimit_cocone F) := { desc := λ s, quot.lift (λ (p : Σ j, F.obj j), s.ι.app p.1 p.2) (assume ⟨j, x⟩ ⟨j', x'⟩ ⟨f, hf⟩, by rw hf; exact (congr_fun (cocone.w s f) x).symm) } /-- The category of types has all colimits. See https://stacks.math.columbia.edu/tag/002U. -/ instance : has_colimits (Type u) := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } } /-- The equivalence between the abstract colimit of `F` in `Type u` and the "concrete" definition as a quotient. -/ noncomputable def colimit_equiv_quot (F : J ⥤ Type u) : (colimit F : Type u) ≃ quot F := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone_is_colimit F)).to_equiv @[simp] lemma colimit_equiv_quot_symm_apply (F : J ⥤ Type u) (j : J) (x : F.obj j) : (colimit_equiv_quot F).symm (quot.mk _ ⟨j, x⟩) = colimit.ι F j x := rfl @[simp] lemma colimit_equiv_quot_apply (F : J ⥤ Type u) (j : J) (x : F.obj j) : (colimit_equiv_quot F) (colimit.ι F j x) = quot.mk _ ⟨j, x⟩ := begin apply (colimit_equiv_quot F).symm.injective, simp, end @[simp] lemma colimit.w_apply {F : J ⥤ Type u} {j j' : J} {x : F.obj j} (f : j ⟶ j') : colimit.ι F j' (F.map f x) = colimit.ι F j x := congr_fun (colimit.w F f) x @[simp] lemma colimit.ι_desc_apply (F : J ⥤ Type u) (s : cocone F) (j : J) (x : F.obj j) : colimit.desc F s (colimit.ι F j x) = s.ι.app j x := congr_fun (colimit.ι_desc s j) x @[simp] lemma colimit.ι_map_apply {F G : J ⥤ Type u} (α : F ⟶ G) (j : J) (x) : colim.map α (colimit.ι F j x) = colimit.ι G j (α.app j x) := congr_fun (colimit.ι_map α j) x lemma colimit_sound {F : J ⥤ Type u} {j j' : J} {x : F.obj j} {x' : F.obj j'} (f : j ⟶ j') (w : F.map f x = x') : colimit.ι F j x = colimit.ι F j' x' := begin rw [←w], simp, end lemma colimit_sound' {F : J ⥤ Type u} {j j' : J} {x : F.obj j} {x' : F.obj j'} {j'' : J} (f : j ⟶ j'') (f' : j' ⟶ j'') (w : F.map f x = F.map f' x') : colimit.ι F j x = colimit.ι F j' x' := begin rw [←colimit.w _ f, ←colimit.w _ f'], rw [types_comp_apply, types_comp_apply, w], end lemma colimit_eq {F : J ⥤ Type u } {j j' : J} {x : F.obj j} {x' : F.obj j'} (w : colimit.ι F j x = colimit.ι F j' x') : eqv_gen (quot.rel F) ⟨j, x⟩ ⟨j', x'⟩ := begin apply quot.eq.1, simpa using congr_arg (colimit_equiv_quot F) w, end lemma jointly_surjective (F : J ⥤ Type u) {t : cocone F} (h : is_colimit t) (x : t.X) : ∃ j y, t.ι.app j y = x := begin suffices : (λ (x : t.X), ulift.up (∃ j y, t.ι.app j y = x)) = (λ _, ulift.up true), { have := congr_fun this x, have H := congr_arg ulift.down this, dsimp at H, rwa eq_true at H }, refine h.hom_ext _, intro j, ext y, erw iff_true, exact ⟨j, y, rfl⟩ end /-- A variant of `jointly_surjective` for `x : colimit F`. -/ lemma jointly_surjective' {F : J ⥤ Type u} (x : colimit F) : ∃ j y, colimit.ι F j y = x := jointly_surjective F (colimit.is_colimit _) x namespace filtered_colimit /- For filtered colimits of types, we can give an explicit description of the equivalence relation generated by the relation used to form the colimit. -/ variables (F : J ⥤ Type u) /-- An alternative relation on `Σ j, F.obj j`, which generates the same equivalence relation as we use to define the colimit in `Type` above, but that is more convenient when working with filtered colimits. Elements in `F.obj j` and `F.obj j'` are equivalent if there is some `k : J` to the right where their images are equal. -/ protected def r (x y : Σ j, F.obj j) : Prop := ∃ k (f : x.1 ⟶ k) (g : y.1 ⟶ k), F.map f x.2 = F.map g y.2 protected lemma r_ge (x y : Σ j, F.obj j) : (∃ f : x.1 ⟶ y.1, y.2 = F.map f x.2) → filtered_colimit.r F x y := λ ⟨f, hf⟩, ⟨y.1, f, 𝟙 y.1, by simp [hf]⟩ variables (t : cocone F) local attribute [elab_simple] nat_trans.app /-- Recognizing filtered colimits of types. -/ noncomputable def is_colimit_of (hsurj : ∀ (x : t.X), ∃ i xi, x = t.ι.app i xi) (hinj : ∀ i j xi xj, t.ι.app i xi = t.ι.app j xj → ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj) : is_colimit t := -- Strategy: Prove that the map from "the" colimit of F (defined above) to t.X -- is a bijection. begin apply is_colimit.of_iso_colimit (colimit.is_colimit F), refine cocones.ext (equiv.to_iso (equiv.of_bijective _ _)) _, { exact colimit.desc F t }, { split, { show function.injective _, intros a b h, rcases jointly_surjective F (colimit.is_colimit F) a with ⟨i, xi, rfl⟩, rcases jointly_surjective F (colimit.is_colimit F) b with ⟨j, xj, rfl⟩, change (colimit.ι F i ≫ colimit.desc F t) xi = (colimit.ι F j ≫ colimit.desc F t) xj at h, rw [colimit.ι_desc, colimit.ι_desc] at h, rcases hinj i j xi xj h with ⟨k, f, g, h'⟩, change colimit.ι F i xi = colimit.ι F j xj, rw [←colimit.w F f, ←colimit.w F g], change colimit.ι F k (F.map f xi) = colimit.ι F k (F.map g xj), rw h' }, { show function.surjective _, intro x, rcases hsurj x with ⟨i, xi, rfl⟩, use colimit.ι F i xi, simp } }, { intro j, apply colimit.ι_desc } end variables [is_filtered_or_empty J] protected lemma r_equiv : equivalence (filtered_colimit.r F) := ⟨λ x, ⟨x.1, 𝟙 x.1, 𝟙 x.1, rfl⟩, λ x y ⟨k, f, g, h⟩, ⟨k, g, f, h.symm⟩, λ x y z ⟨k, f, g, h⟩ ⟨k', f', g', h'⟩, let ⟨l, fl, gl, _⟩ := is_filtered_or_empty.cocone_objs k k', ⟨m, n, hn⟩ := is_filtered_or_empty.cocone_maps (g ≫ fl) (f' ≫ gl) in ⟨m, f ≫ fl ≫ n, g' ≫ gl ≫ n, calc F.map (f ≫ fl ≫ n) x.2 = F.map (fl ≫ n) (F.map f x.2) : by simp ... = F.map (fl ≫ n) (F.map g y.2) : by rw h ... = F.map ((g ≫ fl) ≫ n) y.2 : by simp ... = F.map ((f' ≫ gl) ≫ n) y.2 : by rw hn ... = F.map (gl ≫ n) (F.map f' y.2) : by simp ... = F.map (gl ≫ n) (F.map g' z.2) : by rw h' ... = F.map (g' ≫ gl ≫ n) z.2 : by simp⟩⟩ protected lemma r_eq : filtered_colimit.r F = eqv_gen (λ x y, ∃ f : x.1 ⟶ y.1, y.2 = F.map f x.2) := begin apply le_antisymm, { rintros ⟨i, x⟩ ⟨j, y⟩ ⟨k, f, g, h⟩, exact eqv_gen.trans _ ⟨k, F.map f x⟩ _ (eqv_gen.rel _ _ ⟨f, rfl⟩) (eqv_gen.symm _ _ (eqv_gen.rel _ _ ⟨g, h⟩)) }, { intros x y, convert relation.eqv_gen_mono (filtered_colimit.r_ge F), apply propext, symmetry, exact relation.eqv_gen_iff_of_equivalence (filtered_colimit.r_equiv F) } end lemma colimit_eq_iff_aux {i j : J} {xi : F.obj i} {xj : F.obj j} : (colimit_cocone F).ι.app i xi = (colimit_cocone F).ι.app j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := begin change quot.mk _ _ = quot.mk _ _ ↔ _, rw [quot.eq, quot.rel, ←filtered_colimit.r_eq], refl end variables {t} (ht : is_colimit t) lemma is_colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} : t.ι.app i xi = t.ι.app j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := let t' := colimit_cocone F, e : t' ≅ t := is_colimit.unique_up_to_iso (colimit_cocone_is_colimit F) ht, e' : t'.X ≅ t.X := (cocones.forget _).map_iso e in begin refine iff.trans _ (colimit_eq_iff_aux F), convert e'.to_equiv.apply_eq_iff_eq; rw ←e.hom.w; refl end lemma colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} : colimit.ι F i xi = colimit.ι F j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := is_colimit_eq_iff _ (colimit.is_colimit F) end filtered_colimit variables {α β : Type u} (f : α ⟶ β) section -- implementation of `has_image` /-- the image of a morphism in Type is just `set.range f` -/ def image : Type u := set.range f instance [inhabited α] : inhabited (image f) := { default := ⟨f (default α), ⟨_, rfl⟩⟩ } /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ β := subtype.val instance : mono (image.ι f) := (mono_iff_injective _).2 subtype.val_injective variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I) lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in Type through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := set.range_factorization f } /-- the facorisation through a mono has the universal property of the image. -/ noncomputable def is_image : is_image (mono_factorisation f) := { lift := image.lift, lift_fac' := image.lift_fac } instance : has_image f := has_image.mk ⟨_, is_image f⟩ instance : has_images (Type u) := { has_image := by apply_instance } instance : has_image_maps (Type u) := { has_image_map := λ f g st, has_image_map.transport st (mono_factorisation f.hom) (is_image g.hom) (λ x, ⟨st.right x.1, ⟨st.left (classical.some x.2), begin have p := st.w, replace p := congr_fun p (classical.some x.2), simp only [functor.id_map, types_comp_apply, subtype.val_eq_coe] at p, erw [p, classical.some_spec x.2], end⟩⟩) rfl } end category_theory.limits.types
713401f000b7afb1d314f07792eacbf4ef492582
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/notation_error_pos.lean
9a1394b7466f9fa45b54a3e20c94418d6f58580e
[ "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
170
lean
notation `foo` := "a" + 1 notation `bla` a := a + 1 notation `boo` a := 1 + a notation `cmd` a := λ x, x + a #check foo #check bla "a" #check boo "a" #check cmd "b"
25f5ac9028df80d6c5668def738d6d8983c1147a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/LinearArith/Main.lean
7145f38cc335306885bd81ff4ffdb656bb15fed3
[ "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
254
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.LinearArith.Nat namespace Lean.Meta.Linear end Lean.Meta.Linear
d5082b39e93bc1173a5cf9676d97a6c8ff6d2506
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/order/copy.lean
70552c27e5ea3be5a5e3991f68f3a1873e755c86
[ "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
4,534
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import order.conditionally_complete_lattice /-! # Tooling to make copies of lattice structures Sometimes it is useful to make a copy of a lattice structure where one replaces the data parts with provably equal definitions that have better definitional properties. -/ universe variable u variables {α : Type u} /-- A function to create a provable equal copy of a bounded lattice with possibly different definitional equalities. -/ def bounded_lattice.copy (c : bounded_lattice α) (le : α → α → Prop) (eq_le : le = @bounded_lattice.le α c) (top : α) (eq_top : top = @bounded_lattice.top α c) (bot : α) (eq_bot : bot = @bounded_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @bounded_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @bounded_lattice.inf α c) : bounded_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, .. }, all_goals { subst_vars, unfreezeI, cases c, assumption } end /-- A function to create a provable equal copy of a distributive lattice with possibly different definitional equalities. -/ def distrib_lattice.copy (c : distrib_lattice α) (le : α → α → Prop) (eq_le : le = @distrib_lattice.le α c) (sup : α → α → α) (eq_sup : sup = @distrib_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @distrib_lattice.inf α c) : distrib_lattice α := begin refine { le := le, sup := sup, inf := inf, .. }, all_goals { subst_vars, unfreezeI, cases c, assumption } end /-- A function to create a provable equal copy of a complete lattice with possibly different definitional equalities. -/ def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, .. bounded_lattice.copy (@complete_lattice.to_bounded_lattice α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf, .. }, all_goals { subst_vars, unfreezeI, cases c, assumption } end /-- A function to create a provable equal copy of a complete distributive lattice with possibly different definitional equalities. -/ def complete_distrib_lattice.copy (c : complete_distrib_lattice α) (le : α → α → Prop) (eq_le : le = @complete_distrib_lattice.le α c) (top : α) (eq_top : top = @complete_distrib_lattice.top α c) (bot : α) (eq_bot : bot = @complete_distrib_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_distrib_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_distrib_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_distrib_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_distrib_lattice.Inf α c) : complete_distrib_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, .. complete_lattice.copy (@complete_distrib_lattice.to_complete_lattice α c) le eq_le top eq_top bot eq_bot sup eq_sup inf eq_inf Sup eq_Sup Inf eq_Inf, .. }, all_goals { subst_vars, unfreezeI, cases c, assumption } end /-- A function to create a provable equal copy of a conditionally complete lattice with possibly different definitional equalities. -/ def conditionally_complete_lattice.copy (c : conditionally_complete_lattice α) (le : α → α → Prop) (eq_le : le = @conditionally_complete_lattice.le α c) (sup : α → α → α) (eq_sup : sup = @conditionally_complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @conditionally_complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @conditionally_complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @conditionally_complete_lattice.Inf α c) : conditionally_complete_lattice α := begin refine { le := le, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}, all_goals { subst_vars, unfreezeI, cases c, assumption } end
c82d43b26844eaa2bcb6f25f6d0632cb386f4b57
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/ring_theory/localization.lean
445a7bbfb832ad22ce4c99cc7854f2d180459080
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
24,599
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin -/ import tactic.ring data.quot data.equiv.algebra ring_theory.ideal_operations group_theory.submonoid universes u v namespace localization variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] def r (x y : α × S) : Prop := ∃ t ∈ S, ((x.2 : α) * y.1 - y.2 * x.1) * t = 0 local infix ≈ := r α S section variables {α S} theorem r_of_eq {a₀ a₁ : α × S} (h : (a₀.2 : α) * a₁.1 = a₁.2 * a₀.1) : a₀ ≈ a₁ := ⟨1, is_submonoid.one_mem S, by rw [h, sub_self, mul_one]⟩ end theorem refl (x : α × S) : x ≈ x := r_of_eq rfl theorem symm (x y : α × S) : x ≈ y → y ≈ x := λ ⟨t, hts, ht⟩, ⟨t, hts, by rw [← neg_sub, ← neg_mul_eq_neg_mul, ht, neg_zero]⟩ theorem trans : ∀ (x y z : α × S), x ≈ y → y ≈ z → x ≈ z := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨t, hts, ht⟩ ⟨t', hts', ht'⟩, ⟨s₂ * t' * t, is_submonoid.mul_mem (is_submonoid.mul_mem hs₂ hts') hts, calc (s₁ * r₃ - s₃ * r₁) * (s₂ * t' * t) = t' * s₃ * ((s₁ * r₂ - s₂ * r₁) * t) + t * s₁ * ((s₂ * r₃ - s₃ * r₂) * t') : by simp [mul_left_comm, mul_add, mul_comm] ... = 0 : by simp only [subtype.coe_mk] at ht ht'; rw [ht, ht']; simp⟩ instance : setoid (α × S) := ⟨r α S, refl α S, symm α S, trans α S⟩ end localization /-- The localization of a ring at a submonoid: the elements of the submonoid become invertible in the localization.-/ def localization (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] := quotient $ localization.setoid α S namespace localization variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] instance : has_add (localization α S) := ⟨quotient.lift₂ (λ x y : α × S, (⟦⟨x.2 * y.1 + y.2 * x.1, x.2 * y.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc (s₁ * s₂ * (s₃ * r₄ + s₄ * r₃) - s₃ * s₄ * (s₁ * r₂ + s₂ * r₁)) * (t₆ * t₅) = s₁ * s₃ * ((s₂ * r₄ - s₄ * r₂) * t₆) * t₅ + s₂ * s₄ * ((s₁ * r₃ - s₃ * r₁) * t₅) * t₆ : by ring ... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₆, ht₅]; simp⟩⟩ instance : has_neg (localization α S) := ⟨quotient.lift (λ x : α × S, (⟦⟨-x.1, x.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, quotient.sound ⟨t, hts, calc (s₁ * -r₂ - s₂ * -r₁) * t = -((s₁ * r₂ - s₂ * r₁) * t) : by ring ... = 0 : by simp only [subtype.coe_mk] at ht; rw ht; simp⟩⟩ instance : has_mul (localization α S) := ⟨quotient.lift₂ (λ x y : α × S, (⟦⟨x.1 * y.1, x.2 * y.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc ((s₁ * s₂) * (r₃ * r₄) - (s₃ * s₄) * (r₁ * r₂)) * (t₆ * t₅) = t₆ * ((s₁ * r₃ - s₃ * r₁) * t₅) * r₂ * s₄ + t₅ * ((s₂ * r₄ - s₄ * r₂) * t₆) * r₃ * s₁ : by simp [mul_left_comm, mul_add, mul_comm] ... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₅, ht₆]; simp⟩⟩ variables {α S} def mk (r : α) (s : S) : localization α S := ⟦(r, s)⟧ /-- The natural map from the ring to the localization.-/ def of (r : α) : localization α S := mk r 1 instance : comm_ring (localization α S) := by refine { add := has_add.add, add_assoc := λ m n k, quotient.induction_on₃ m n k _, zero := of 0, zero_add := quotient.ind _, add_zero := quotient.ind _, neg := has_neg.neg, add_left_neg := quotient.ind _, add_comm := quotient.ind₂ _, mul := has_mul.mul, mul_assoc := λ m n k, quotient.induction_on₃ m n k _, one := of 1, one_mul := quotient.ind _, mul_one := quotient.ind _, left_distrib := λ m n k, quotient.induction_on₃ m n k _, right_distrib := λ m n k, quotient.induction_on₃ m n k _, mul_comm := quotient.ind₂ _ }; { intros, try {rcases a with ⟨r₁, s₁, hs₁⟩}, try {rcases b with ⟨r₂, s₂, hs₂⟩}, try {rcases c with ⟨r₃, s₃, hs₃⟩}, refine (quotient.sound $ r_of_eq _), simp [mul_left_comm, mul_add, mul_comm] } instance of.is_ring_hom : is_ring_hom (of : α → localization α S) := { map_add := λ x y, quotient.sound $ by simp, map_mul := λ x y, quotient.sound $ by simp, map_one := rfl } variables {S} instance : has_coe α (localization α S) := ⟨of⟩ instance coe.is_ring_hom : is_ring_hom (coe : α → localization α S) := localization.of.is_ring_hom /-- The natural map from the submonoid to the unit group of the localization.-/ def to_units (s : S) : units (localization α S) := { val := s, inv := mk 1 s, val_inv := quotient.sound $ r_of_eq $ mul_assoc _ _ _, inv_val := quotient.sound $ r_of_eq $ show s.val * 1 * 1 = 1 * (1 * s.val), by simp } @[simp] lemma to_units_coe (s : S) : ((to_units s) : localization α S) = s := rfl section variables (α S) (x y : α) (n : ℕ) @[simp] lemma of_zero : (of 0 : localization α S) = 0 := rfl @[simp] lemma of_one : (of 1 : localization α S) = 1 := rfl @[simp] lemma of_add : (of (x + y) : localization α S) = of x + of y := by apply is_ring_hom.map_add @[simp] lemma of_sub : (of (x - y) : localization α S) = of x - of y := by apply is_ring_hom.map_sub @[simp] lemma of_mul : (of (x * y) : localization α S) = of x * of y := by apply is_ring_hom.map_mul @[simp] lemma of_neg : (of (-x) : localization α S) = -of x := by apply is_ring_hom.map_neg @[simp] lemma of_pow : (of (x ^ n) : localization α S) = (of x) ^ n := by apply is_semiring_hom.map_pow @[simp] lemma of_is_unit (s : S) : is_unit (of s : localization α S) := is_unit_unit $ to_units s @[simp] lemma of_is_unit' (s ∈ S) : is_unit (of s : localization α S) := is_unit_unit $ to_units ⟨s, ‹s ∈ S›⟩ @[simp] lemma coe_zero : ((0 : α) : localization α S) = 0 := rfl @[simp] lemma coe_one : ((1 : α) : localization α S) = 1 := rfl @[simp] lemma coe_add : (↑(x + y) : localization α S) = x + y := of_add _ _ _ _ @[simp] lemma coe_sub : (↑(x - y) : localization α S) = x - y := of_sub _ _ _ _ @[simp] lemma coe_mul : (↑(x * y) : localization α S) = x * y := of_mul _ _ _ _ @[simp] lemma coe_neg : (↑(-x) : localization α S) = -x := of_neg _ _ _ @[simp] lemma coe_pow : (↑(x ^ n) : localization α S) = x ^ n := of_pow _ _ _ _ @[simp] lemma coe_is_unit (s : S) : is_unit (s : localization α S) := of_is_unit _ _ _ @[simp] lemma coe_is_unit' (s ∈ S) : is_unit (s : localization α S) := of_is_unit' _ _ _ ‹s ∈ S› end @[simp] lemma mk_self {x : α} {hx : x ∈ S} : (mk x ⟨x, hx⟩ : localization α S) = 1 := quotient.sound ⟨1, is_submonoid.one_mem S, by simp only [subtype.coe_mk, is_submonoid.coe_one, mul_one, one_mul, sub_self]⟩ @[simp] lemma mk_self' {s : S} : (mk s s : localization α S) = 1 := by cases s; exact mk_self @[simp] lemma mk_self'' {s : S} : (mk s.1 s : localization α S) = 1 := mk_self' @[simp] lemma coe_mul_mk (x y : α) (s : S) : ↑x * mk y s = mk (x * y) s := quotient.sound $ r_of_eq $ by rw one_mul lemma mk_eq_mul_mk_one (r : α) (s : S) : mk r s = r * mk 1 s := by rw [coe_mul_mk, mul_one] @[simp] lemma mk_mul_mk (x y : α) (s t : S) : mk x s * mk y t = mk (x * y) (s * t) := rfl @[simp] lemma mk_mul_cancel_left (r : α) (s : S) : mk (↑s * r) s = r := by rw [mk_eq_mul_mk_one, mul_comm ↑s, coe_mul, mul_assoc, ← mk_eq_mul_mk_one, mk_self', mul_one] @[simp] lemma mk_mul_cancel_right (r : α) (s : S) : mk (r * s) s = r := by rw [mul_comm, mk_mul_cancel_left] @[simp] lemma mk_eq (r : α) (s : S) : mk r s = r * ((to_units s)⁻¹ : units _) := quotient.sound $ by simp @[elab_as_eliminator] protected theorem induction_on {C : localization α S → Prop} (x : localization α S) (ih : ∀ r s, C (mk r s : localization α S)) : C x := by rcases x with ⟨r, s⟩; exact ih r s section variables {β : Type v} [comm_ring β] {T : set β} [is_submonoid T] (f : α → β) [is_ring_hom f] @[elab_with_expected_type] def lift' (g : S → units β) (hg : ∀ s, (g s : β) = f s) (x : localization α S) : β := quotient.lift_on x (λ p, f p.1 * ((g p.2)⁻¹ : units β)) $ λ ⟨r₁, s₁⟩ ⟨r₂, s₂⟩ ⟨t, hts, ht⟩, show f r₁ * ↑(g s₁)⁻¹ = f r₂ * ↑(g s₂)⁻¹, from calc f r₁ * ↑(g s₁)⁻¹ = (f r₁ * g s₂ + ((g s₁ * f r₂ - g s₂ * f r₁) * g ⟨t, hts⟩) * ↑(g ⟨t, hts⟩)⁻¹) * ↑(g s₁)⁻¹ * ↑(g s₂)⁻¹ : by simp only [hg, subtype.coe_mk, (is_ring_hom.map_mul f).symm, (is_ring_hom.map_sub f).symm, ht, is_ring_hom.map_zero f, zero_mul, add_zero]; rw [is_ring_hom.map_mul f, ← hg, mul_right_comm, mul_assoc (f r₁), ← units.coe_mul, mul_inv_self]; rw [units.coe_one, mul_one] ... = f r₂ * ↑(g s₂)⁻¹ : by rw [mul_assoc, mul_assoc, ← units.coe_mul, mul_inv_self, units.coe_one, mul_one, mul_comm ↑(g s₂), add_sub_cancel'_right]; rw [mul_comm ↑(g s₁), ← mul_assoc, mul_assoc (f r₂), ← units.coe_mul, mul_inv_self, units.coe_one, mul_one] instance lift'.is_ring_hom (g : S → units β) (hg : ∀ s, (g s : β) = f s) : is_ring_hom (localization.lift' f g hg) := { map_one := have g 1 = 1, from units.ext (by rw hg; exact is_ring_hom.map_one f), show f 1 * ↑(g 1)⁻¹ = 1, by rw [this, one_inv, units.coe_one, mul_one, is_ring_hom.map_one f], map_mul := λ x y, localization.induction_on x $ λ r₁ s₁, localization.induction_on y $ λ r₂ s₂, have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f), show _ * ↑(g (_ * _))⁻¹ = (_ * _) * (_ * _), by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev]; rw [is_ring_hom.map_mul f, units.coe_mul, ← mul_assoc, ← mul_assoc]; simp only [mul_right_comm], map_add := λ x y, localization.induction_on x $ λ r₁ s₁, localization.induction_on y $ λ r₂ s₂, have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f), show _ * ↑(g (_ * _))⁻¹ = _ * _ + _ * _, by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev]; simp only [is_ring_hom.map_mul f, is_ring_hom.map_add f, add_mul, (hg _).symm]; simp only [mul_assoc, mul_comm, mul_left_comm, (units.coe_mul _ _).symm]; rw [mul_inv_cancel_left, mul_left_comm, ← mul_assoc, mul_inv_cancel_right, add_comm] } noncomputable def lift (h : ∀ s ∈ S, is_unit (f s)) : localization α S → β := localization.lift' f (λ s, classical.some $ h s.1 s.2) (λ s, by rw [← classical.some_spec (h s.1 s.2)]; refl) instance lift.is_ring_hom (h : ∀ s ∈ S, is_unit (f s)) : is_ring_hom (lift f h) := lift'.is_ring_hom _ _ _ @[simp] lemma lift'_mk (g : S → units β) (hg : ∀ s, (g s : β) = f s) (r : α) (s : S) : lift' f g hg (mk r s) = f r * ↑(g s)⁻¹ := rfl @[simp] lemma lift'_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) : lift' f g hg (of a) = f a := have g 1 = 1, from units.ext_iff.2 $ by simp [hg, is_ring_hom.map_one f], by simp [lift', quotient.lift_on_beta, of, mk, this] @[simp] lemma lift'_coe (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) : lift' f g hg a = f a := lift'_of _ _ _ _ @[simp] lemma lift_of (h : ∀ s ∈ S, is_unit (f s)) (a : α) : lift f h (of a) = f a := lift'_of _ _ _ _ @[simp] lemma lift_coe (h : ∀ s ∈ S, is_unit (f s)) (a : α) : lift f h a = f a := lift'_of _ _ _ _ @[simp] lemma lift'_comp_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) : lift' f g hg ∘ of = f := funext $ λ a, lift'_of _ _ _ a @[simp] lemma lift_comp_of (h : ∀ s ∈ S, is_unit (f s)) : lift f h ∘ of = f := lift'_comp_of _ _ _ @[simp] lemma lift'_apply_coe (f : localization α S → β) [is_ring_hom f] (g : S → units β) (hg : ∀ s, (g s : β) = f s) : lift' (λ a : α, f a) g hg = f := have g = (λ s, units.map f (to_units s)), from funext $ λ x, units.ext_iff.2 $ (hg x).symm ▸ rfl, funext $ λ x, localization.induction_on x (λ r s, by subst this; rw [lift'_mk, ← is_group_hom.inv (units.map f), units.coe_map]; simp [is_ring_hom.map_mul f]) @[simp] lemma lift_apply_coe (f : localization α S → β) [is_ring_hom f] : lift (λ a : α, f a) (λ s hs, is_unit_unit (units.map f (to_units ⟨s, hs⟩))) = f := by rw [lift, lift'_apply_coe] /-- Function extensionality for localisations: two functions are equal if they agree on elements that are coercions.-/ protected lemma funext (f g : localization α S → β) [is_ring_hom f] [is_ring_hom g] (h : ∀ a : α, f a = g a) : f = g := begin rw [← lift_apply_coe f, ← lift_apply_coe g], congr' 1, exact funext h end variables {α S T} def map (hf : ∀ s ∈ S, f s ∈ T) : localization α S → localization β T := lift' (of ∘ f) (to_units ∘ subtype.map f hf) (λ s, rfl) instance map.is_ring_hom (hf : ∀ s ∈ S, f s ∈ T) : is_ring_hom (map f hf) := lift'.is_ring_hom _ _ _ @[simp] lemma map_of (hf : ∀ s ∈ S, f s ∈ T) (a : α) : map f hf (of a) = of (f a) := lift'_of _ _ _ _ @[simp] lemma map_coe (hf : ∀ s ∈ S, f s ∈ T) (a : α) : map f hf a = (f a) := lift'_of _ _ _ _ @[simp] lemma map_comp_of (hf : ∀ s ∈ S, f s ∈ T) : map f hf ∘ of = of ∘ f := funext $ λ a, map_of _ _ _ @[simp] lemma map_id : map id (λ s (hs : s ∈ S), hs) = id := localization.funext _ _ $ map_coe _ _ lemma map_comp_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ) [is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) : map g hg ∘ map f hf = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) := localization.funext _ _ $ by simp lemma map_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ) [is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) (x) : map g hg (map f hf x) = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) x := congr_fun (map_comp_map _ _ _ _ _) x def equiv_of_equiv (h₁ : α ≃r β) (h₂ : h₁.to_equiv '' S = T) : localization α S ≃r localization β T := { to_fun := map h₁.to_equiv $ λ s hs, by {rw ← h₂, simp [hs]}, inv_fun := map h₁.symm.to_equiv $ λ t ht, by simp [equiv.image_eq_preimage, set.preimage, set.ext_iff, *] at *, left_inv := λ _, by simp only [map_map, ring_equiv.to_equiv_symm_apply, equiv.symm_apply_apply]; erw map_id; refl, right_inv := λ _, by simp only [map_map, ring_equiv.to_equiv_symm_apply, equiv.apply_symm_apply]; erw map_id; refl, hom := map.is_ring_hom _ _ } end section away variables {β : Type v} [comm_ring β] (f : α → β) [is_ring_hom f] @[reducible] def away (x : α) := localization α (powers x) @[simp] def away.inv_self (x : α) : away x := mk 1 ⟨x, 1, pow_one x⟩ @[elab_with_expected_type] noncomputable def away.lift {x : α} (hfx : is_unit (f x)) : away x → β := localization.lift' f (λ s, classical.some hfx ^ classical.some s.2) $ λ s, by rw [units.coe_pow, ← classical.some_spec hfx, ← is_semiring_hom.map_pow f, classical.some_spec s.2]; refl instance away.lift.is_ring_hom {x : α} (hfx : is_unit (f x)) : is_ring_hom (localization.away.lift f hfx) := lift'.is_ring_hom _ _ _ @[simp] lemma away.lift_of {x : α} (hfx : is_unit (f x)) (a : α) : away.lift f hfx (of a) = f a := lift'_of _ _ _ _ @[simp] lemma away.lift_coe {x : α} (hfx : is_unit (f x)) (a : α) : away.lift f hfx a = f a := lift'_of _ _ _ _ @[simp] lemma away.lift_comp_of {x : α} (hfx : is_unit (f x)) : away.lift f hfx ∘ of = f := lift'_comp_of _ _ _ noncomputable def away_to_away_right (x y : α) : away x → away (x * y) := localization.away.lift coe $ is_unit_of_mul_one x (y * away.inv_self (x * y)) $ by rw [away.inv_self, coe_mul_mk, coe_mul_mk, mul_one, mk_self] instance away_to_away_right.is_ring_hom (x y : α) : is_ring_hom (away_to_away_right x y) := away.lift.is_ring_hom _ _ end away section at_prime variables (P : ideal α) [hp : ideal.is_prime P] include hp instance prime.is_submonoid : is_submonoid (-P : set α) := { one_mem := P.ne_top_iff_one.1 hp.1, mul_mem := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } @[reducible] def at_prime := localization α (-P) instance at_prime.local_ring : is_local_ring (at_prime P) := local_of_nonunits_ideal (λ hze, let ⟨t, hts, ht⟩ := quotient.exact hze in hts $ have htz : t = 0, by simpa using ht, suffices (0:α) ∈ P, by rwa htz, P.zero_mem) (begin rintro ⟨⟨r₁, s₁, hs₁⟩⟩ ⟨⟨r₂, s₂, hs₂⟩⟩ hx hy hu, rcases is_unit_iff_exists_inv.1 hu with ⟨⟨⟨r₃, s₃, hs₃⟩⟩, hz⟩, rcases quotient.exact hz with ⟨t, hts, ht⟩, simp at ht, have : ∀ {r s hs}, (⟦⟨r, s, hs⟩⟧ : at_prime P) ∈ nonunits (at_prime P) → r ∈ P, { haveI := classical.dec, exact λ r s hs, not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨⟦⟨s, r, nr⟩⟧, quotient.sound $ r_of_eq $ by simp [mul_comm]⟩) }, have hr₃ := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right hts, have := (ideal.add_mem_iff_left _ _).1 hr₃, { exact not_or (mt hp.mem_or_mem (not_or hs₁ hs₂)) hs₃ (hp.mem_or_mem this) }, { exact P.neg_mem (P.mul_mem_right (P.add_mem (P.mul_mem_left (this hy)) (P.mul_mem_left (this hx)))) } end) end at_prime variable (α) def non_zero_divisors : set α := {x | ∀ z, z * x = 0 → z = 0} instance non_zero_divisors.is_submonoid : is_submonoid (non_zero_divisors α) := { one_mem := λ z hz, by rwa mul_one at hz, mul_mem := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } @[simp] lemma non_zero_divisors_one_val : (1 : non_zero_divisors α).val = 1 := rfl /-- The field of fractions of an integral domain.-/ @[reducible] def fraction_ring := localization α (non_zero_divisors α) namespace fraction_ring open function variables {β : Type u} [integral_domain β] [decidable_eq β] lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : β} : x ≠ 0 → y * x = 0 → y = 0 := λ hnx hxy, or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : β} : x ∈ non_zero_divisors β ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩ variable (β) def inv_aux (x : β × (non_zero_divisors β)) : fraction_ring β := if h : x.1 = 0 then 0 else ⟦⟨x.2, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ instance : has_inv (fraction_ring β) := ⟨quotient.lift (inv_aux β) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, begin have hrs : s₁ * r₂ = 0 + s₂ * r₁, from sub_eq_iff_eq_add.1 (hts _ ht), by_cases hr₁ : r₁ = 0; by_cases hr₂ : r₂ = 0; simp [hr₁, hr₂] at hrs; simp only [inv_aux, hr₁, hr₂, dif_pos, dif_neg, not_false_iff, subtype.coe_mk, quotient.eq], { exfalso, exact mem_non_zero_divisors_iff_ne_zero.mp hs₁ hrs }, { exfalso, exact mem_non_zero_divisors_iff_ne_zero.mp hs₂ hrs }, { apply r_of_eq, simpa [mul_comm] using hrs.symm } end⟩ lemma mk_inv {r s} : (mk r s : fraction_ring β)⁻¹ = if h : r = 0 then 0 else ⟦⟨s, r, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ := rfl lemma mk_inv' : ∀ (x : β × (non_zero_divisors β)), (⟦x⟧⁻¹ : fraction_ring β) = if h : x.1 = 0 then 0 else ⟦⟨x.2.val, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ | ⟨r,s,hs⟩ := rfl instance : decidable_eq (fraction_ring β) := @quotient.decidable_eq (β × non_zero_divisors β) (localization.setoid β (non_zero_divisors β)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, show decidable (∃ t ∈ non_zero_divisors β, (s₁ * r₂ - s₂ * r₁) * t = 0), from decidable_of_iff (s₁ * r₂ - s₂ * r₁ = 0) ⟨λ H, ⟨1, λ y, (mul_one y).symm ▸ id, H.symm ▸ zero_mul _⟩, λ ⟨t, ht1, ht2⟩, or.resolve_right (mul_eq_zero.1 ht2) $ λ ht, one_ne_zero (ht1 1 ((one_mul t).symm ▸ ht))⟩ instance : discrete_field (fraction_ring β) := by refine { inv := has_inv.inv, zero_ne_one := λ hzo, let ⟨t, hts, ht⟩ := quotient.exact hzo in zero_ne_one (by simpa using hts _ ht : 0 = 1), mul_inv_cancel := quotient.ind _, inv_mul_cancel := quotient.ind _, has_decidable_eq := fraction_ring.decidable_eq β, inv_zero := dif_pos rfl, .. localization.comm_ring }; { intros x hnx, rcases x with ⟨x, z, hz⟩, have : x ≠ 0, from assume hx, hnx (quotient.sound $ r_of_eq $ by simp [hx]), simp only [has_inv.inv, inv_aux, quotient.lift_beta, dif_neg this], exact (quotient.sound $ r_of_eq $ by simp [mul_comm]) } @[simp] lemma mk_eq_div {r s} : (mk r s : fraction_ring β) = (r / s : fraction_ring β) := show _ = _ * dite (s.1 = 0) _ _, by rw [dif_neg (mem_non_zero_divisors_iff_ne_zero.mp s.2)]; exact localization.mk_eq_mul_mk_one _ _ variables {β} @[simp] lemma mk_eq_div' (x : β × (non_zero_divisors β)) : (⟦x⟧ : fraction_ring β) = ((x.1) / ((x.2).val) : fraction_ring β) := by erw ← mk_eq_div; cases x; refl lemma eq_zero_of (x : β) (h : (of x : fraction_ring β) = 0) : x = 0 := begin rcases quotient.exact h with ⟨t, ht, ht'⟩, simpa [mem_non_zero_divisors_iff_ne_zero.mp ht] using ht' end lemma of.injective : function.injective (of : β → fraction_ring β) := (is_add_group_hom.injective_iff _).mpr eq_zero_of section map open function is_ring_hom variables {A : Type u} [integral_domain A] [decidable_eq A] variables {B : Type v} [integral_domain B] [decidable_eq B] variables (f : A → B) [is_ring_hom f] def map (hf : injective f) : fraction_ring A → fraction_ring B := localization.map f $ λ s h, by rw [mem_non_zero_divisors_iff_ne_zero, ← map_zero f, ne.def, hf.eq_iff]; exact mem_non_zero_divisors_iff_ne_zero.1 h @[simp] lemma map_of (hf : injective f) (a : A) : map f hf (of a) = of (f a) := localization.map_of _ _ _ @[simp] lemma map_coe (hf : injective f) (a : A) : map f hf a = f a := localization.map_coe _ _ _ @[simp] lemma map_comp_of (hf : injective f) : map f hf ∘ (of : A → fraction_ring A) = (of : B → fraction_ring B) ∘ f := localization.map_comp_of _ _ instance map.is_field_hom (hf : injective f) : is_field_hom (map f hf) := localization.map.is_ring_hom _ _ def equiv_of_equiv (h : A ≃r B) : fraction_ring A ≃r fraction_ring B := localization.equiv_of_equiv h begin ext b, rw [equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero, ne.def], exact ⟨mt (λ h, h.symm ▸ is_ring_hom.map_zero _), mt ((is_add_group_hom.injective_iff _).1 h.to_equiv.symm.injective _)⟩ end end map end fraction_ring section ideals theorem map_comap (J : ideal (localization α S)) : ideal.map coe (ideal.comap (coe : α → localization α S) J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x, localization.induction_on x $ λ r s hJ, (submodule.mem_coe _).2 $ mul_one r ▸ coe_mul_mk r 1 s ▸ (ideal.mul_mem_right _ $ ideal.mem_map_of_mem $ have _ := @ideal.mul_mem_left (localization α S) _ _ s _ hJ, by rwa [coe_coe, coe_mul_mk, mk_mul_cancel_left] at this) def le_order_embedding : ((≤) : ideal (localization α S) → ideal (localization α S) → Prop) ≼o ((≤) : ideal α → ideal α → Prop) := { to_fun := λ J, ideal.comap coe J, inj := function.injective_of_left_inverse (map_comap α), ord := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, map_comap α J₁ ▸ map_comap α J₂ ▸ ideal.map_mono hJ⟩ } end ideals end localization
75763fd18aea230c810c7160c117a33ac46b1a92
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/server/diags.lean
71895faf51e3e9c101b25e8b6431242200c17757
[ "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,176
lean
import Lean.Data.Lsp open IO Lean Lsp def main : IO Unit := do Ipc.runWith (←IO.appPath) #["--server"] do let hIn ← Ipc.stdin hIn.write (←FS.readBinFile "init_vscode_1_47_2.log") hIn.flush discard $ Ipc.readResponseAs 0 InitializeResult Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩ hIn.write (←FS.readBinFile "open_content.log") hIn.flush let diags ← Ipc.collectDiagnostics 1 "file:///test.lean" 1 if diags.isEmpty then throw $ userError "Test failed, no diagnostics received." else let diag := diags.getLast! FS.writeFile "content_diag.json.produced" (toString <| toJson (diag : JsonRpc.Message)) if let some (refDiag : JsonRpc.Notification PublishDiagnosticsParams) := (Json.parse $ ←FS.readFile "content_diag.json") >>= fromJson? then assert! (diag == refDiag) else throw $ userError "Failed parsing test file." Ipc.writeRequest ⟨2, "shutdown", Json.null⟩ let shutResp ← Ipc.readResponseAs 2 Json assert! shutResp.result.isNull Ipc.writeNotification ⟨"exit", Json.null⟩ discard $ Ipc.waitForExit
6c04825b29be3ec7ffc049df6439f739bd99b771
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/instances/ennreal.lean
3efe8bb66fd6a5b56ff4b6227b7aa9c5f95441f8
[ "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
73,112
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 topology.instances.nnreal import topology.algebra.order.monotone_continuity import analysis.normed.group.basic /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical topological_space ennreal nnreal big_operators filter variables {α : Type*} {β : Type*} {γ : Type*} namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} section topological_space open topological_space /-- Topology on `ℝ≥0∞`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ℝ≥0∞ := preorder.topology ℝ≥0∞ instance : order_topology ℝ≥0∞ := ⟨rfl⟩ instance : t2_space ℝ≥0∞ := by apply_instance -- short-circuit type class inference instance : normal_space ℝ≥0∞ := normal_of_compact_t2 instance : second_countable_topology ℝ≥0∞ := order_iso_unit_interval_birational.to_homeomorph.embedding.second_countable_topology lemma embedding_coe : embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ≥0 | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : ℝ≥0 | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ℝ≥0∞ | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma open_embedding_coe : open_embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩ lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ℝ≥0∞) ∈ 𝓝 (r : ℝ≥0∞) := is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _ @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} : tendsto (λa, (m a : ℝ≥0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ≥0∞) := embedding_coe.continuous lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} : continuous (λa, (f a : ℝ≥0∞)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ℝ≥0∞) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma tendsto_nhds_coe_iff {α : Type*} {l : filter α} {x : ℝ≥0} {f : ℝ≥0∞ → α} : tendsto f (𝓝 ↑x) l ↔ tendsto (f ∘ coe : ℝ≥0 → α) (𝓝 x) l := show _ ≤ _ ↔ _ ≤ _, by rw [nhds_coe, filter.map_map] lemma continuous_at_coe_iff {α : Type*} [topological_space α] {x : ℝ≥0} {f : ℝ≥0∞ → α} : continuous_at f (↑x) ↔ continuous_at (f ∘ coe : ℝ≥0 → α) x := tendsto_nhds_coe_iff lemma nhds_coe_coe {r p : ℝ≥0} : 𝓝 ((r : ℝ≥0∞), (p : ℝ≥0∞)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe_iff.2 continuous_id).comp continuous_real_to_nnreal lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) := begin lift a to ℝ≥0 using ha, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma eventually_eq_of_to_real_eventually_eq {l : filter α} {f g : α → ℝ≥0∞} (hfi : ∀ᶠ x in l, f x ≠ ∞) (hgi : ∀ᶠ x in l, g x ≠ ∞) (hfg : (λ x, (f x).to_real) =ᶠ[l] (λ x, (g x).to_real)) : f =ᶠ[l] g := begin filter_upwards [hfi, hgi, hfg] with _ hfx hgx _, rwa ← ennreal.to_real_eq_to_real hfx hgx, end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := λ a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha) lemma tendsto_to_real {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) := nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_coe.subtype_mk _, .. ne_top_equiv_nnreal } /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) := nhds_top.trans $ infi_ne_top _ lemma nhds_top_basis : (𝓝 ∞).has_basis (λ a, a < ∞) (λ a, Ioi a) := nhds_top_basis lemma tendsto_nhds_top_iff_nnreal {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi] lemma tendsto_nhds_top_iff_nat {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a := tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n, λ h x, let ⟨n, hn⟩ := exists_nat_gt x in (h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩ lemma tendsto_nhds_top {m : α → ℝ≥0∞} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_top_iff_nat.2 h lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ @[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} : tendsto (λ x, (f x : ℝ≥0∞)) l (𝓝 ∞) ↔ tendsto f l at_top := by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff]; [simp, apply_instance, apply_instance] lemma tendsto_of_real_at_top : tendsto ennreal.of_real at_top (𝓝 ∞) := tendsto_coe_nhds_top.2 tendsto_real_to_nnreal_at_top lemma nhds_zero : 𝓝 (0 : ℝ≥0∞) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) (λ a, Iio a) := nhds_bot_basis lemma nhds_zero_basis_Iic : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) Iic := nhds_bot_basis_Iic @[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝ≥0} : (𝓝[>] (r : ℝ≥0∞)).ne_bot := nhds_within_Ioi_self_ne_bot' ⟨⊤, ennreal.coe_lt_top⟩ @[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[>] (0 : ℝ≥0∞)).ne_bot := nhds_within_Ioi_coe_ne_bot -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds (xt : x ≠ ⊤) (ε0 : ε ≠ 0) : Icc (x - ε) (x + ε) ∈ 𝓝 x := begin rw _root_.mem_nhds_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top (xt : x ≠ ⊤) : 𝓝 x = ⨅ ε > 0, 𝓟 (Icc (x - ε) (x + ε)) := begin refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0.lt.ne', -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), rcases hs with ⟨xs, ⟨a, (rfl : s = Ioi a)|(rfl : s = Iio a)⟩⟩, { rcases exists_between xs with ⟨b, ab, bx⟩, have xb_pos : 0 < x - b := tsub_pos_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel xt bx.le, refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rcases exists_between xs with ⟨b, xb, ba⟩, have bx_pos : 0 < b - x := tsub_pos_iff_lt.2 xb, have xbx : x + (b - x) = b := add_tsub_cancel_of_le xb.le, refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ℝ≥0∞` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter α} {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_nhds_zero {f : filter α} {u : α → ℝ≥0∞} : tendsto u f (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in f, u x ≤ ε := begin rw ennreal.tendsto_nhds zero_ne_top, simp only [true_and, zero_tsub, zero_le, zero_add, set.mem_Icc], end protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] instance : has_continuous_add ℝ≥0∞ := begin refine ⟨continuous_iff_continuous_at.2 _⟩, rintro ⟨(_|a), b⟩, { exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) }, rcases b with (_|b), { exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) }, simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] end protected lemma tendsto_at_top_zero [hβ : nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} : filter.at_top.tendsto f (𝓝 0) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, f n ≤ ε := begin rw ennreal.tendsto_at_top zero_ne_top, { simp_rw [set.mem_Icc, zero_add, zero_tsub, zero_le _, true_and], }, { exact hβ, }, end lemma tendsto_sub {a b : ℝ≥0∞} (h : a ≠ ∞ ∨ b ≠ ∞) : tendsto (λ p : ℝ≥0∞ × ℝ≥0∞, p.1 - p.2) (𝓝 (a, b)) (𝓝 (a - b)) := begin cases a; cases b, { simp only [eq_self_iff_true, not_true, ne.def, none_eq_top, or_self] at h, contradiction }, { simp only [some_eq_coe, with_top.top_sub_coe, none_eq_top], apply tendsto_nhds_top_iff_nnreal.2 (λ n, _), rw [nhds_prod_eq, eventually_prod_iff], refine ⟨λ z, ((n + (b + 1)) : ℝ≥0∞) < z, Ioi_mem_nhds (by simp only [one_lt_top, add_lt_top, coe_lt_top, and_self]), λ z, z < b + 1, Iio_mem_nhds ((ennreal.lt_add_right coe_ne_top one_ne_zero)), λ x hx y hy, _⟩, dsimp, rw lt_tsub_iff_right, have : ((n : ℝ≥0∞) + y) + (b + 1) < x + (b + 1) := calc ((n : ℝ≥0∞) + y) + (b + 1) = ((n : ℝ≥0∞) + (b + 1)) + y : by abel ... < x + (b + 1) : ennreal.add_lt_add hx hy, exact lt_of_add_lt_add_right this }, { simp only [some_eq_coe, with_top.sub_top, none_eq_top], suffices H : ∀ᶠ (p : ℝ≥0∞ × ℝ≥0∞) in 𝓝 (a, ∞), 0 = p.1 - p.2, from tendsto_const_nhds.congr' H, rw [nhds_prod_eq, eventually_prod_iff], refine ⟨λ z, z < a + 1, Iio_mem_nhds (ennreal.lt_add_right coe_ne_top one_ne_zero), λ z, (a : ℝ≥0∞) + 1 < z, Ioi_mem_nhds (by simp only [one_lt_top, add_lt_top, coe_lt_top, and_self]), λ x hx y hy, _⟩, rw eq_comm, simp only [tsub_eq_zero_iff_le, (has_lt.lt.trans hx hy).le], }, { simp only [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, function.comp, ← ennreal.coe_sub, tendsto_coe], exact continuous.tendsto (by continuity) _ } end protected lemma tendsto.sub {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (hmb : tendsto mb f (𝓝 b)) (h : a ≠ ∞ ∨ b ≠ ∞) : tendsto (λ a, ma a - mb a) f (𝓝 (a - b)) := show tendsto ((λ p : ℝ≥0∞ × ℝ≥0∞, p.1 - p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a - b)), from tendsto.comp (ennreal.tendsto_sub h) (hma.prod_mk_nhds hmb) protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ℝ≥0∞, b ≠ 0 → tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 ((⊤:ℝ≥0∞), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _, rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩, have : ∀ᶠ c : ℝ≥0∞ × ℝ≥0∞ in 𝓝 (∞, b), ↑n / ↑ε < c.1 ∧ ↑ε < c.2, from (lt_mem_nhds $ div_lt_top coe_ne_top hε.ne').prod_nhds (lt_mem_nhds hεb), refine this.mono (λ c hc, _), exact (div_mul_cancel hε.ne' coe_ne_top).symm.trans_lt (mul_lt_mul hc.1 hc.2) end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ℝ≥0∞) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) lemma _root_.continuous_on.ennreal_mul [topological_space α] {f g : α → ℝ≥0∞} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) (h₁ : ∀ x ∈ s, f x ≠ 0 ∨ g x ≠ ∞) (h₂ : ∀ x ∈ s, g x ≠ 0 ∨ f x ≠ ∞) : continuous_on (λ x, f x * g x) s := λ x hx, ennreal.tendsto.mul (hf x hx) (h₁ x hx) (hg x hx) (h₂ x hx) lemma _root_.continuous.ennreal_mul [topological_space α] {f g : α → ℝ≥0∞} (hf : continuous f) (hg : continuous g) (h₁ : ∀ x, f x ≠ 0 ∨ g x ≠ ∞) (h₂ : ∀ x, g x ≠ 0 ∨ f x ≠ ∞) : continuous (λ x, f x * g x) := continuous_iff_continuous_at.2 $ λ x, ennreal.tendsto.mul hf.continuous_at (h₁ x) hg.continuous_at (h₂ x) protected lemma tendsto.const_mul {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha lemma tendsto_finset_prod_of_ne_top {ι : Type*} {f : ι → α → ℝ≥0∞} {x : filter α} {a : ι → ℝ≥0∞} (s : finset ι) (h : ∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) (h' : ∀ i ∈ s, a i ≠ ∞): tendsto (λ b, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := begin induction s using finset.induction with a s has IH, { simp [tendsto_const_nhds] }, simp only [finset.prod_insert has], apply tendsto.mul (h _ (finset.mem_insert_self _ _)), { right, exact (prod_lt_top (λ i hi, h' _ (finset.mem_insert_of_mem hi))).ne }, { exact IH (λ i hi, h _ (finset.mem_insert_of_mem hi)) (λ i hi, h' _ (finset.mem_insert_of_mem hi)) }, { exact or.inr (h' _ (finset.mem_insert_self _ _)) } end protected lemma continuous_at_const_mul {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at ((*) a) b := tendsto.const_mul tendsto_id h.symm protected lemma continuous_at_mul_const {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (λ x, x * a) b := tendsto.mul_const tendsto_id h.symm protected lemma continuous_const_mul {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha) protected lemma continuous_mul_const {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous (λ x, x * a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha) protected lemma continuous_div_const (c : ℝ≥0∞) (c_ne_zero : c ≠ 0) : continuous (λ (x : ℝ≥0∞), x / c) := begin simp_rw [div_eq_mul_inv, continuous_iff_continuous_at], intro x, exact ennreal.continuous_at_mul_const (or.intro_left _ (inv_ne_top.mpr c_ne_zero)), end @[continuity] lemma continuous_pow (n : ℕ) : continuous (λ a : ℝ≥0∞, a ^ n) := begin induction n with n IH, { simp [continuous_const] }, simp_rw [nat.succ_eq_add_one, pow_add, pow_one, continuous_iff_continuous_at], assume x, refine ennreal.tendsto.mul (IH.tendsto _) _ tendsto_id _; by_cases H : x = 0, { simp only [H, zero_ne_top, ne.def, or_true, not_false_iff]}, { exact or.inl (λ h, H (pow_eq_zero h)) }, { simp only [H, pow_eq_top_iff, zero_ne_top, false_or, eq_self_iff_true, not_true, ne.def, not_false_iff, false_and], }, { simp only [H, true_or, ne.def, not_false_iff] } end lemma continuous_on_sub : continuous_on (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) { p : ℝ≥0∞ × ℝ≥0∞ | p ≠ ⟨∞, ∞⟩ } := begin rw continuous_on, rintros ⟨x, y⟩ hp, simp only [ne.def, set.mem_set_of_eq, prod.mk.inj_iff] at hp, refine tendsto_nhds_within_of_tendsto_nhds (tendsto_sub (not_and_distrib.mp hp)), end lemma continuous_sub_left {a : ℝ≥0∞} (a_ne_top : a ≠ ⊤) : continuous (λ x, a - x) := begin rw (show (λ x, a - x) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨a, x⟩), by refl), apply continuous_on.comp_continuous continuous_on_sub (continuous.prod.mk a), intro x, simp only [a_ne_top, ne.def, mem_set_of_eq, prod.mk.inj_iff, false_and, not_false_iff], end lemma continuous_nnreal_sub {a : ℝ≥0} : continuous (λ (x : ℝ≥0∞), (a : ℝ≥0∞) - x) := continuous_sub_left coe_ne_top lemma continuous_on_sub_left (a : ℝ≥0∞) : continuous_on (λ x, a - x) {x : ℝ≥0∞ | x ≠ ∞} := begin rw (show (λ x, a - x) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨a, x⟩), by refl), apply continuous_on.comp continuous_on_sub (continuous.continuous_on (continuous.prod.mk a)), rintros _ h (_|_), exact h none_eq_top, end lemma continuous_sub_right (a : ℝ≥0∞) : continuous (λ x : ℝ≥0∞, x - a) := begin by_cases a_infty : a = ∞, { simp [a_infty, continuous_const], }, { rw (show (λ x, x - a) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨x, a⟩), by refl), apply continuous_on.comp_continuous continuous_on_sub (continuous_id'.prod_mk continuous_const), intro x, simp only [a_infty, ne.def, mem_set_of_eq, prod.mk.inj_iff, and_false, not_false_iff], }, end protected lemma tendsto.pow {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} {n : ℕ} (hm : tendsto m f (𝓝 a)) : tendsto (λ x, (m x) ^ n) f (𝓝 (a ^ n)) := ((continuous_pow n).tendsto a).comp hm lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0∞} (h : ∀ a < 1, a * x ≤ y) : x ≤ y := begin have : tendsto (* x) (𝓝[<] 1) (𝓝 (1 * x)) := (ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left, rw one_mul at this, haveI : (𝓝[<] (1 : ℝ≥0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ⟨0, ennreal.zero_lt_one⟩, exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h) end lemma infi_mul_left' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, a * f i) = a * ⨅ i, f i := begin by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0, { rcases h H.1 H.2 with ⟨i, hi⟩, rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot], exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ }, { rw not_and_distrib at H, casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, mul_top, if_neg], exact mt h0 (not_nonempty_iff.2 ‹_›) }, { exact (ennreal.mul_left_mono.map_infi_of_continuous_at' (ennreal.continuous_at_const_mul H)).symm } } end lemma infi_mul_left {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, a * f i) = a * ⨅ i, f i := infi_mul_left' h (λ _, ‹nonempty ι›) lemma infi_mul_right' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, f i * a) = (⨅ i, f i) * a := by simpa only [mul_comm a] using infi_mul_left' h h0 lemma infi_mul_right {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, f i * a) = (⨅ i, f i) * a := infi_mul_right' h (λ _, ‹nonempty ι›) lemma inv_map_infi {ι : Sort*} {x : ι → ℝ≥0∞} : (infi x)⁻¹ = (⨆ i, (x i)⁻¹) := order_iso.inv_ennreal.map_infi x lemma inv_map_supr {ι : Sort*} {x : ι → ℝ≥0∞} : (supr x)⁻¹ = (⨅ i, (x i)⁻¹) := order_iso.inv_ennreal.map_supr x lemma inv_limsup {ι : Sort*} {x : ι → ℝ≥0∞} {l : filter ι} : (limsup x l)⁻¹ = liminf (λ i, (x i)⁻¹) l := by simp only [limsup_eq_infi_supr, inv_map_infi, inv_map_supr, liminf_eq_supr_infi] lemma inv_liminf {ι : Sort*} {x : ι → ℝ≥0∞} {l : filter ι} : (liminf x l)⁻¹ = limsup (λ i, (x i)⁻¹) l := by simp only [limsup_eq_infi_supr, inv_map_infi, inv_map_supr, liminf_eq_supr_infi] instance : has_continuous_inv ℝ≥0∞ := ⟨order_iso.inv_ennreal.continuous⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [inv_inv] using tendsto.inv h, tendsto.inv⟩ protected lemma tendsto.div {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ℝ≥0∞)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma supr_add {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : supr s + a = ⨆b, s b + a := monotone.map_supr_of_continuous_at' (continuous_at_id.add continuous_at_const) $ monotone_id.add monotone_const lemma bsupr_add' {ι : Sort*} {p : ι → Prop} (h : ∃ i, p i) {f : ι → ℝ≥0∞} : (⨆ i (hi : p i), f i) + a = ⨆ i (hi : p i), f i + a := by { haveI : nonempty {i // p i} := nonempty_subtype.2 h, simp only [supr_subtype', supr_add] } lemma add_bsupr' {ι : Sort*} {p : ι → Prop} (h : ∃ i, p i) {f : ι → ℝ≥0∞} : a + (⨆ i (hi : p i), f i) = ⨆ i (hi : p i), a + f i := by simp only [add_comm a, bsupr_add' h] lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := bsupr_add' hs lemma add_bsupr {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : a + (⨆ i ∈ s, f i) = ⨆ i ∈ s, a + f i := add_bsupr' hs lemma Sup_add {s : set ℝ≥0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := by rw [Sup_eq_supr, bsupr_add hs] lemma add_supr {ι : Sort*} {s : ι → ℝ≥0∞} [nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr_le {ι ι' : Sort*} [nonempty ι] [nonempty ι'] {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ i j, f i + g j ≤ a) : supr f + supr g ≤ a := by simpa only [add_supr, supr_add] using supr₂_le h lemma bsupr_add_bsupr_le' {ι ι'} {p : ι → Prop} {q : ι' → Prop} (hp : ∃ i, p i) (hq : ∃ j, q j) {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ i (hi : p i) j (hj : q j), f i + g j ≤ a) : (⨆ i (hi : p i), f i) + (⨆ j (hj : q j), g j) ≤ a := by { simp_rw [bsupr_add' hp, add_bsupr' hq], exact supr₂_le (λ i hi, supr₂_le (h i hi)) } lemma bsupr_add_bsupr_le {ι ι'} {s : set ι} {t : set ι'} (hs : s.nonempty) (ht : t.nonempty) {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ (i ∈ s) (j ∈ t), f i + g j ≤ a) : (⨆ i ∈ s, f i) + (⨆ j ∈ t, g j) ≤ a := bsupr_add_bsupr_le' hs ht h lemma supr_add_supr {ι : Sort*} {f g : ι → ℝ≥0∞} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin casesI is_empty_or_nonempty ι, { simp only [supr_of_empty, bot_eq_zero, zero_add] }, { refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)), refine supr_add_supr_le (λ i j, _), rcases h i j with ⟨k, hk⟩, exact le_supr_of_le k hk } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ℝ≥0∞} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ℝ≥0∞} (hf : ∀a, monotone (f a)) : ∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) := begin refine finset.induction_on s _ _, { simp, }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end lemma mul_supr {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : a * supr f = ⨆i, a * f i := begin by_cases hf : ∀ i, f i = 0, { obtain rfl : f = (λ _, 0), from funext hf, simp only [supr_zero_eq_zero, mul_zero] }, { refine (monotone_id.const_mul' _).map_supr_of_continuous_at _ (mul_zero a), refine ennreal.tendsto.const_mul tendsto_id (or.inl _), exact mt supr_eq_zero.1 hf } end lemma mul_Sup {s : set ℝ≥0∞} {a : ℝ≥0∞} : a * Sup s = ⨆i∈s, a * i := by simp only [Sup_eq_supr, mul_supr] lemma supr_mul {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] lemma supr_div {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f / a = ⨆i, f i / a := supr_mul protected lemma tendsto_coe_sub : ∀{b:ℝ≥0∞}, tendsto (λb:ℝ≥0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine forall_ennreal.2 ⟨λ a, _, _⟩, { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, ← with_top.coe_sub], exact tendsto_const_nhds.sub tendsto_id }, simp, exact (tendsto.congr' (mem_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [nonempty ι] {b : ι → ℝ≥0∞} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto (assume x _ y _, tsub_le_tsub (le_refl (r : ℝ≥0∞))) (range_nonempty _) (ennreal.tendsto_coe_sub.comp (tendsto_id'.2 inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_rfl lemma exists_countable_dense_no_zero_top : ∃ (s : set ℝ≥0∞), s.countable ∧ dense s ∧ 0 ∉ s ∧ ∞ ∉ s := begin obtain ⟨s, s_count, s_dense, hs⟩ : ∃ s : set ℝ≥0∞, s.countable ∧ dense s ∧ (∀ x, is_bot x → x ∉ s) ∧ (∀ x, is_top x → x ∉ s) := exists_countable_dense_no_bot_top ℝ≥0∞, exact ⟨s, s_count, s_dense, λ h, hs.1 0 (by simp) h, λ h, hs.2 ∞ (by simp) h⟩, end lemma exists_lt_add_of_lt_add {x y z : ℝ≥0∞} (h : x < y + z) (hy : y ≠ 0) (hz : z ≠ 0) : ∃ y' z', y' < y ∧ z' < z ∧ x < y' + z' := begin haveI : ne_bot (𝓝[<] y) := nhds_within_Iio_self_ne_bot' ⟨0, pos_iff_ne_zero.2 hy⟩, haveI : ne_bot (𝓝[<] z) := nhds_within_Iio_self_ne_bot' ⟨0, pos_iff_ne_zero.2 hz⟩, have A : tendsto (λ (p : ℝ≥0∞ × ℝ≥0∞), p.1 + p.2) ((𝓝[<] y).prod (𝓝[<] z)) (𝓝 (y + z)), { apply tendsto.mono_left _ (filter.prod_mono nhds_within_le_nhds nhds_within_le_nhds), rw ← nhds_prod_eq, exact tendsto_add }, rcases (((tendsto_order.1 A).1 x h).and (filter.prod_mem_prod self_mem_nhds_within self_mem_nhds_within)).exists with ⟨⟨y', z'⟩, hx, hy', hz'⟩, exact ⟨y', z', hy', hz', hx⟩, end end topological_space section liminf lemma exists_frequently_lt_of_liminf_ne_top {ι : Type*} {l : filter ι} {x : ι → ℝ} (hx : liminf (λ n, (‖x n‖₊ : ℝ≥0∞)) l ≠ ∞) : ∃ R, ∃ᶠ n in l, x n < R := begin by_contra h, simp_rw [not_exists, not_frequently, not_lt] at h, refine hx (ennreal.eq_top_of_forall_nnreal_le $ λ r, le_Liminf_of_le (by is_bounded_default) _), simp only [eventually_map, ennreal.coe_le_coe], filter_upwards [h r] with i hi using hi.trans ((coe_nnnorm (x i)).symm ▸ le_abs_self (x i)), end lemma exists_frequently_lt_of_liminf_ne_top' {ι : Type*} {l : filter ι} {x : ι → ℝ} (hx : liminf (λ n, (‖x n‖₊ : ℝ≥0∞)) l ≠ ∞) : ∃ R, ∃ᶠ n in l, R < x n := begin by_contra h, simp_rw [not_exists, not_frequently, not_lt] at h, refine hx (ennreal.eq_top_of_forall_nnreal_le $ λ r, le_Liminf_of_le (by is_bounded_default) _), simp only [eventually_map, ennreal.coe_le_coe], filter_upwards [h (-r)] with i hi using (le_neg.1 hi).trans (neg_le_abs_self _), end lemma exists_upcrossings_of_not_bounded_under {ι : Type*} {l : filter ι} {x : ι → ℝ} (hf : liminf (λ i, (‖x i‖₊ : ℝ≥0∞)) l ≠ ∞) (hbdd : ¬ is_bounded_under (≤) l (λ i, |x i|)) : ∃ a b : ℚ, a < b ∧ (∃ᶠ i in l, x i < a) ∧ (∃ᶠ i in l, ↑b < x i) := begin rw [is_bounded_under_le_abs, not_and_distrib] at hbdd, obtain hbdd | hbdd := hbdd, { obtain ⟨R, hR⟩ := exists_frequently_lt_of_liminf_ne_top hf, obtain ⟨q, hq⟩ := exists_rat_gt R, refine ⟨q, q + 1, (lt_add_iff_pos_right _).2 zero_lt_one, _, _⟩, { refine λ hcon, hR _, filter_upwards [hcon] with x hx using not_lt.2 (lt_of_lt_of_le hq (not_lt.1 hx)).le }, { simp only [is_bounded_under, is_bounded, eventually_map, eventually_at_top, ge_iff_le, not_exists, not_forall, not_le, exists_prop] at hbdd, refine λ hcon, hbdd ↑(q + 1) _, filter_upwards [hcon] with x hx using not_lt.1 hx } }, { obtain ⟨R, hR⟩ := exists_frequently_lt_of_liminf_ne_top' hf, obtain ⟨q, hq⟩ := exists_rat_lt R, refine ⟨q - 1, q, (sub_lt_self_iff _).2 zero_lt_one, _, _⟩, { simp only [is_bounded_under, is_bounded, eventually_map, eventually_at_top, ge_iff_le, not_exists, not_forall, not_le, exists_prop] at hbdd, refine λ hcon, hbdd ↑(q - 1) _, filter_upwards [hcon] with x hx using not_lt.1 hx }, { refine λ hcon, hR _, filter_upwards [hcon] with x hx using not_lt.2 ((not_lt.1 hx).trans hq.le) } } end end liminf section tsum variables {f g : α → ℝ≥0∞} @[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ≥0∞)) ↑r ↔ has_sum f r := have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ℝ≥0∞) ∘ (λs:finset α, ∑ a in s, f a), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ℝ≥0∞) = r := (ennreal.has_sum_coe.2 h).tsum_eq protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ℝ≥0∞) | ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) := tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} : ∑' b, (f b:ℝ≥0∞) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ℝ≥0∞)) to ℝ≥0 using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) := ennreal.has_sum.tsum_eq protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) : ∑' a, f a = ⨆ i, ∑ a in s i, f a := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ℝ≥0∞) : ∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ℝ≥0∞) : ∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ℝ≥0∞} : ∑'p:α×β, f p.1 p.2 = ∑'a, ∑'b, f a b := tsum_prod' ennreal.summable $ λ _, ennreal.summable protected lemma tsum_comm {f : α → β → ℝ≥0∞} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b := tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable) protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma sum_le_tsum {f : α → ℝ≥0∞} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x := sum_le_tsum s (λ x hx, zero_le _) ennreal.summable protected lemma tsum_eq_supr_nat' {f : ℕ → ℝ≥0∞} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) := ennreal.tsum_eq_supr_sum' _ $ λ t, let ⟨n, hn⟩ := t.exists_nat_subset_range, ⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in ⟨k, finset.subset.trans hn (finset.range_mono hk)⟩ protected lemma tsum_eq_supr_nat {f : ℕ → ℝ≥0∞} : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma tsum_eq_liminf_sum_nat {f : ℕ → ℝ≥0∞} : ∑' i, f i = liminf (λ n, ∑ i in finset.range n, f i) at_top := begin rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat], congr, refine funext (λ n, le_antisymm _ _), { refine le_infi₂ (λ i hi, finset.sum_le_sum_of_subset_of_nonneg _ (λ _ _ _, zero_le _)), simpa only [finset.range_subset, add_le_add_iff_right] using hi, }, { refine le_trans (infi_le _ n) _, simp [le_refl n, le_refl ((finset.range n).sum f)], }, end protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a := le_tsum' ennreal.summable a @[simp] protected lemma tsum_eq_zero : ∑' i, f i = 0 ↔ ∀ i, f i = 0 := ⟨λ h i, nonpos_iff_eq_zero.1 $ h ▸ ennreal.le_tsum i, λ h, by simp [h]⟩ protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞ | ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a protected lemma lt_top_of_tsum_ne_top {a : α → ℝ≥0∞} (tsum_ne_top : ∑' i, a i ≠ ∞) (j : α) : a j < ∞ := begin have key := not_imp_not.mpr ennreal.tsum_eq_top_of_eq_top, simp only [not_exists] at key, exact lt_top_iff_ne_top.mpr (key tsum_ne_top j), end @[simp] protected lemma tsum_top [nonempty α] : ∑' a : α, ∞ = ∞ := let ⟨a⟩ := ‹nonempty α› in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩ lemma tsum_const_eq_top_of_ne_zero {α : Type*} [infinite α] {c : ℝ≥0∞} (hc : c ≠ 0) : (∑' (a : α), c) = ∞ := begin have A : tendsto (λ (n : ℕ), (n : ℝ≥0∞) * c) at_top (𝓝 (∞ * c)), { apply ennreal.tendsto.mul_const tendsto_nat_nhds_top, simp only [true_or, top_ne_zero, ne.def, not_false_iff] }, have B : ∀ (n : ℕ), (n : ℝ≥0∞) * c ≤ (∑' (a : α), c), { assume n, rcases infinite.exists_subset_card_eq α n with ⟨s, hs⟩, simpa [hs] using @ennreal.sum_le_tsum α (λ i, c) s }, simpa [hc] using le_of_tendsto' A B, end protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ ∑'i, f i : ennreal.le_tsum _, have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)), by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j, from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), has_sum.tsum_eq this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ℝ≥0∞} : ∑'b:α, (⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0∞} (r : ℝ≥0∞) : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end lemma tendsto_nat_tsum (f : ℕ → ℝ≥0∞) : tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 (∑' n, f n)) := by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum } lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) (x : α) : (((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ℝ≥0∞) = f x := coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _ lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) : summable (ennreal.to_nnreal ∘ f) := by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf lemma tendsto_cofinite_zero_of_tsum_ne_top {α} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f cofinite (𝓝 0) := begin have f_ne_top : ∀ n, f n ≠ ∞, from ennreal.ne_top_of_tsum_ne_top hf, have h_f_coe : f = λ n, ((f n).to_nnreal : ennreal), from funext (λ n, (coe_to_nnreal (f_ne_top n)).symm), rw [h_f_coe, ←@coe_zero, tendsto_coe], exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf), end lemma tendsto_at_top_zero_of_tsum_ne_top {f : ℕ → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_ne_top hf } /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto (λ (s : finset α), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, convert ennreal.tendsto_coe.2 (nnreal.tendsto_tsum_compl_at_top_zero f), ext1 s, rw ennreal.coe_tsum, exact nnreal.summable_comp_injective (tsum_coe_ne_top_iff_summable.1 hf) subtype.coe_injective end protected lemma tsum_apply {ι α : Type*} {f : ι → α → ℝ≥0∞} {x : α} : (∑' i, f i) x = ∑' i, f i x := tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable lemma tsum_sub {f : ℕ → ℝ≥0∞} {g : ℕ → ℝ≥0∞} (h₁ : ∑' i, g i ≠ ∞) (h₂ : g ≤ f) : ∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) := begin have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i, { rw [ennreal.tsum_add, ennreal.add_sub_cancel_right h₁]}, have h₄:(λ i, (f i - g i) + (g i)) = f, { ext n, rw tsub_add_cancel_of_le (h₂ n)}, rw h₄ at h₃, apply h₃, end lemma tsum_mono_subtype (f : α → ℝ≥0∞) {s t : set α} (h : s ⊆ t) : ∑' (x : s), f x ≤ ∑' (x : t), f x := begin simp only [tsum_subtype], apply ennreal.tsum_le_tsum, exact indicator_le_indicator_of_subset h (λ _, zero_le _), end lemma tsum_union_le (f : α → ℝ≥0∞) (s t : set α) : ∑' (x : s ∪ t), f x ≤ ∑' (x : s), f x + ∑' (x : t), f x := calc ∑' (x : s ∪ t), f x = ∑' (x : s ∪ (t \ s)), f x : by { apply tsum_congr_subtype, rw union_diff_self } ... = ∑' (x : s), f x + ∑' (x : t \ s), f x : tsum_union_disjoint disjoint_diff ennreal.summable ennreal.summable ... ≤ ∑' (x : s), f x + ∑' (x : t), f x : add_le_add le_rfl (tsum_mono_subtype _ (diff_subset _ _)) lemma tsum_bUnion_le {ι : Type*} (f : α → ℝ≥0∞) (s : finset ι) (t : ι → set α) : ∑' (x : ⋃ (i ∈ s), t i), f x ≤ ∑ i in s, ∑' (x : t i), f x := begin classical, induction s using finset.induction_on with i s hi ihs h, { simp }, have : (⋃ (j ∈ insert i s), t j) = t i ∪ (⋃ (j ∈ s), t j), by simp, rw tsum_congr_subtype f this, calc ∑' (x : (t i ∪ (⋃ (j ∈ s), t j))), f x ≤ ∑' (x : t i), f x + ∑' (x : ⋃ (j ∈ s), t j), f x : tsum_union_le _ _ _ ... ≤ ∑' (x : t i), f x + ∑ i in s, ∑' (x : t i), f x : add_le_add le_rfl ihs ... = ∑ j in insert i s, ∑' (x : t j), f x : (finset.sum_insert hi).symm end lemma tsum_Union_le {ι : Type*} [fintype ι] (f : α → ℝ≥0∞) (t : ι → set α) : ∑' (x : ⋃ i, t i), f x ≤ ∑ i, ∑' (x : t i), f x := begin classical, have : (⋃ i, t i) = (⋃ (i ∈ (finset.univ : finset ι)), t i), by simp, rw tsum_congr_subtype f this, exact tsum_bUnion_le _ _ _ end lemma tsum_add_one_eq_top {f : ℕ → ℝ≥0∞} (hf : ∑' n, f n = ∞) (hf0 : f 0 ≠ ∞) : ∑' n, f (n + 1) = ∞ := begin rw ← tsum_eq_tsum_of_has_sum_iff_has_sum (λ _, (not_mem_range_equiv 1).has_sum_iff), swap, { apply_instance }, have h₁ : (∑' b : {n // n ∈ finset.range 1}, f b) + (∑' b : {n // n ∉ finset.range 1}, f b) = ∑' b, f b, { exact tsum_add_tsum_compl ennreal.summable ennreal.summable }, rw [finset.tsum_subtype, finset.sum_range_one, hf, ennreal.add_eq_top] at h₁, rw ← h₁.resolve_left hf0, apply tsum_congr, rintro ⟨i, hi⟩, simp only [multiset.mem_range, not_lt] at hi, simp only [tsub_add_cancel_of_le hi, coe_not_mem_range_equiv, function.comp_app, subtype.coe_mk], end /-- A sum of extended nonnegative reals which is finite can have only finitely many terms above any positive threshold.-/ lemma finite_const_le_of_tsum_ne_top {ι : Type*} {a : ι → ℝ≥0∞} (tsum_ne_top : ∑' i, a i ≠ ∞) {ε : ℝ≥0∞} (ε_ne_zero : ε ≠ 0) : {i : ι | ε ≤ a i}.finite := begin by_cases ε_infty : ε = ∞, { rw ε_infty, by_contra maybe_infinite, obtain ⟨j, hj⟩ := set.infinite.nonempty maybe_infinite, exact tsum_ne_top (le_antisymm le_top (le_trans hj (le_tsum' (@ennreal.summable _ a) j))), }, have key := (nnreal.summable_coe.mpr (summable_to_nnreal_of_tsum_ne_top tsum_ne_top)).tendsto_cofinite_zero (Iio_mem_nhds (to_real_pos ε_ne_zero ε_infty)), simp only [filter.mem_map, filter.mem_cofinite, preimage] at key, have obs : {i : ι | ↑((a i).to_nnreal) ∈ Iio ε.to_real}ᶜ = {i : ι | ε ≤ a i}, { ext i, simpa only [mem_Iio, mem_compl_iff, mem_set_of_eq, not_lt] using to_real_le_to_real ε_infty (ennreal.ne_top_of_tsum_ne_top tsum_ne_top _), }, rwa obs at key, end /-- Markov's inequality for `finset.card` and `tsum` in `ℝ≥0∞`. -/ lemma finset_card_const_le_le_of_tsum_le {ι : Type*} {a : ι → ℝ≥0∞} {c : ℝ≥0∞} (c_ne_top : c ≠ ∞) (tsum_le_c : ∑' i, a i ≤ c) {ε : ℝ≥0∞} (ε_ne_zero : ε ≠ 0) : ∃ hf : {i : ι | ε ≤ a i}.finite, ↑hf.to_finset.card ≤ c / ε := begin by_cases ε = ∞, { have obs : {i : ι | ε ≤ a i} = ∅, { rw eq_empty_iff_forall_not_mem, intros i hi, have oops := (le_trans hi (le_tsum' (@ennreal.summable _ a) i)).trans tsum_le_c, rw h at oops, exact c_ne_top (le_antisymm le_top oops), }, simp only [obs, finite_empty, finite_empty_to_finset, finset.card_empty, algebra_map.coe_zero, zero_le', exists_true_left], }, have hf : {i : ι | ε ≤ a i}.finite, from ennreal.finite_const_le_of_tsum_ne_top (lt_of_le_of_lt tsum_le_c c_ne_top.lt_top).ne ε_ne_zero, use hf, have at_least : ∀ i ∈ hf.to_finset, ε ≤ a i, { intros i hi, simpa only [finite.mem_to_finset, mem_set_of_eq] using hi, }, have partial_sum := @sum_le_tsum _ _ _ _ _ a hf.to_finset (λ _ _, zero_le') (@ennreal.summable _ a), have lower_bound := finset.sum_le_sum at_least, simp only [finset.sum_const, nsmul_eq_mul] at lower_bound, have key := (ennreal.le_div_iff_mul_le (or.inl ε_ne_zero) (or.inl h)).mpr lower_bound, exact le_trans key (ennreal.div_le_div_right (partial_sum.trans tsum_le_c) _), end end tsum lemma tendsto_to_real_iff {ι} {fi : filter ι} {f : ι → ℝ≥0∞} (hf : ∀ i, f i ≠ ∞) {x : ℝ≥0∞} (hx : x ≠ ∞) : fi.tendsto (λ n, (f n).to_real) (𝓝 x.to_real) ↔ fi.tendsto f (𝓝 x) := begin refine ⟨λ h, _, λ h, tendsto.comp (ennreal.tendsto_to_real hx) h⟩, have h_eq : f = (λ n, ennreal.of_real (f n).to_real), by { ext1 n, rw ennreal.of_real_to_real (hf n), }, rw [h_eq, ← ennreal.of_real_to_real hx], exact ennreal.tendsto_of_real h, end lemma tsum_coe_ne_top_iff_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) ≠ ∞ ↔ summable (λ a, (f a : ℝ)) := begin rw nnreal.summable_coe, exact tsum_coe_ne_top_iff_summable, end lemma tsum_coe_eq_top_iff_not_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) = ∞ ↔ ¬ summable (λ a, (f a : ℝ)) := begin rw [← @not_not (∑' a, ↑(f a) = ⊤)], exact not_congr tsum_coe_ne_top_iff_summable_coe end lemma has_sum_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : has_sum (λ x, (f x).to_real) (∑' x, (f x).to_real) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hsum, simp only [coe_to_real, ← nnreal.coe_tsum, nnreal.has_sum_coe], exact (tsum_coe_ne_top_iff_summable.1 hsum).has_sum end lemma summable_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : summable (λ x, (f x).to_real) := (has_sum_to_real hsum).summable end ennreal namespace nnreal open_locale nnreal lemma tsum_eq_to_nnreal_tsum {f : β → ℝ≥0} : (∑' b, f b) = (∑' b, (f b : ℝ≥0∞)).to_nnreal := begin by_cases h : summable f, { rw [← ennreal.coe_tsum h, ennreal.to_nnreal_coe] }, { have A := tsum_eq_zero_of_not_summable h, simp only [← ennreal.tsum_coe_ne_top_iff_summable, not_not] at h, simp only [h, ennreal.top_to_nnreal, A] } end /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have ∑'b, (g b : ℝ≥0∞) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin split, { intros h, refine ((tendsto_of_monotone _).resolve_right h).comp _, exacts [finset.sum_mono_set _, tendsto_finset_range] }, { rintros hnat ⟨r, hr⟩, exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) } end lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top] lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := tsum_le_of_sum_range_le (summable_of_sum_range_le h) h lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_rfl) (summable_comp_injective hf hi) hf lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := begin split, { simp only [← nnreal.summable_coe, nnreal.coe_tsum], exact λ h, ⟨h.sigma_factor, h.sigma⟩ }, { rintro ⟨h₁, h₂⟩, simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁] using h₂ } end lemma indicator_summable {f : α → ℝ≥0} (hf : summable f) (s : set α) : summable (s.indicator f) := begin refine nnreal.summable_of_le (λ a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf, split_ifs, exact le_refl (f a), exact zero_le_coe, end lemma tsum_indicator_ne_zero {f : α → ℝ≥0} (hf : summable f) {s : set α} (h : ∃ a ∈ s, f a ≠ 0) : ∑' x, (s.indicator f) x ≠ 0 := λ h', let ⟨a, ha, hap⟩ := h in hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm (((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a)) open finset /-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin rw ← tendsto_coe, convert tendsto_sum_nat_add (λ i, (f i : ℝ)), norm_cast, end lemma has_sum_lt {f g : α → ℝ≥0} {sf sg : ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hf : has_sum f sf) (hg : has_sum g sg) : sf < sg := begin have A : ∀ (a : α), (f a : ℝ) ≤ g a := λ a, nnreal.coe_le_coe.2 (h a), have : (sf : ℝ) < sg := has_sum_lt A (nnreal.coe_lt_coe.2 hi) (has_sum_coe.2 hf) (has_sum_coe.2 hg), exact nnreal.coe_lt_coe.1 this end @[mono] lemma has_sum_strict_mono {f g : α → ℝ≥0} {sf sg : ℝ≥0} (hf : has_sum f sf) (hg : has_sum g sg) (h : f < g) : sf < sg := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {f g : α → ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi (summable_of_le h hg).has_sum hg.has_sum @[mono] lemma tsum_strict_mono {f g : α → ℝ≥0} (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hg lemma tsum_pos {g : α → ℝ≥0} (hg : summable g) (i : α) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum (λ a, zero_le _) hi hg } end nnreal namespace ennreal lemma tsum_to_nnreal_eq {f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) : (∑' a, f a).to_nnreal = ∑' a, (f a).to_nnreal := (congr_arg ennreal.to_nnreal (tsum_congr $ λ x, (coe_to_nnreal (hf x)).symm)).trans nnreal.tsum_eq_to_nnreal_tsum.symm lemma tsum_to_real_eq {f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) : (∑' a, f a).to_real = ∑' a, (f a).to_real := by simp only [ennreal.to_real, tsum_to_nnreal_eq hf, nnreal.coe_tsum] lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0∞) (hf : ∑' i, f i ≠ ∞) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin lift f to ℕ → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf, simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero], exact_mod_cast nnreal.tendsto_sum_nat_add f end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0∞} {c : ℝ≥0∞} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := tsum_le_of_sum_range_le ennreal.summable h lemma has_sum_lt {f g : α → ℝ≥0∞} {sf sg : ℝ≥0∞} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hsf : sf ≠ ⊤) (hf : has_sum f sf) (hg : has_sum g sg) : sf < sg := begin by_cases hsg : sg = ⊤, { exact hsg.symm ▸ lt_of_le_of_ne le_top hsf }, { have hg' : ∀ x, g x ≠ ⊤:= ennreal.ne_top_of_tsum_ne_top (hg.tsum_eq.symm ▸ hsg), lift f to α → ℝ≥0 using λ x, ne_of_lt (lt_of_le_of_lt (h x) $ lt_of_le_of_ne le_top (hg' x)), lift g to α → ℝ≥0 using hg', lift sf to ℝ≥0 using hsf, lift sg to ℝ≥0 using hsg, simp only [coe_le_coe, coe_lt_coe] at h hi ⊢, exact nnreal.has_sum_lt h hi (ennreal.has_sum_coe.1 hf) (ennreal.has_sum_coe.1 hg) } end lemma tsum_lt_tsum {f g : α → ℝ≥0∞} {i : α} (hfi : tsum f ≠ ⊤) (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) : ∑' x, f x < ∑' x, g x := has_sum_lt h hi hfi ennreal.summable.has_sum ennreal.summable.has_sum end ennreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin lift f to α → ℝ≥0 using hn, rw nnreal.summable_coe at hf, simpa only [(∘), ← nnreal.coe_tsum] using nnreal.tsum_comp_le_tsum_of_inj hf hi end /-- Comparison test of convergence of series of non-negative real numbers. -/ lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := begin lift f to β → ℝ≥0 using λ b, (hg b).trans (hgf b), lift g to β → ℝ≥0 using hg, rw nnreal.summable_coe at hf ⊢, exact nnreal.summable_of_le (λ b, nnreal.coe_le_coe.1 (hgf b)) hf end lemma summable.to_nnreal {f : α → ℝ} (hf : summable f) : summable (λ n, (f n).to_nnreal) := begin apply nnreal.summable_coe.1, refine summable_of_nonneg_of_le (λ n, nnreal.coe_nonneg _) (λ n, _) hf.abs, simp only [le_abs_self, real.coe_to_nnreal', max_le_iff, abs_nonneg, and_self] end /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin lift f to ℕ → ℝ≥0 using hf, simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'], exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat) end lemma ennreal.of_real_tsum_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : ennreal.of_real (∑' n, f n) = ∑' n, ennreal.of_real (f n) := by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq (nnreal.has_sum_real_to_nnreal_of_nonneg hf_nonneg hf)] lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin lift f to ℕ → ℝ≥0 using hf, exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top end lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf] lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma } lemma summable_of_sum_le {ι : Type*} {f : ι → ℝ} {c : ℝ} (hf : 0 ≤ f) (h : ∀ u : finset ι, ∑ x in u, f x ≤ c) : summable f := ⟨ ⨆ u : finset ι, ∑ x in u, f x, tendsto_at_top_csupr (finset.sum_mono_set_of_nonneg hf) ⟨c, λ y ⟨u, hu⟩, hu ▸ h u⟩ ⟩ lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma real.tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := tsum_le_of_sum_range_le (summable_of_sum_range_le hf h) h /-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable series and at least one term of `f` is strictly smaller than the corresponding term in `g`, then the series of `f` is strictly smaller than the series of `g`. -/ lemma tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ} (h0 : ∀ (b : ℕ), 0 ≤ f b) (h : ∀ (b : ℕ), f b ≤ g b) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ℝ≥0∞} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ℝ≥0∞) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ℝ≥0∞) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm end section variable [pseudo_emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ℝ≥0∞ β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ℝ≥0∞), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p (le_trans hn hp) q (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λ m hm n hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ℝ≥0∞} (C : ℝ≥0∞) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin rcases eq_or_ne C 0 with (rfl|C0), { simp only [zero_mul, add_zero] at h, exact continuous_of_const (λ x y, le_antisymm (h _ _) (h _ _)) }, { refine continuous_iff_continuous_at.2 (λ x, _), by_cases hx : f x = ∞, { have : f =ᶠ[𝓝 x] (λ _, ∞), { filter_upwards [emetric.ball_mem_nhds x ennreal.coe_lt_top], refine λ y (hy : edist y x < ⊤), _, rw edist_comm at hy, simpa [hx, hC, hy.ne] using h x y }, exact this.continuous_at }, { refine (ennreal.tendsto_nhds hx).2 (λ ε (ε0 : 0 < ε), _), filter_upwards [emetric.closed_ball_mem_nhds x (ennreal.div_pos_iff.2 ⟨ε0.ne', hC⟩)], have hεC : C * (ε / C) = ε := ennreal.mul_div_cancel' C0 hC, refine λ y (hy : edist y x ≤ ε / C), ⟨tsub_le_iff_right.2 _, _⟩, { rw edist_comm at hy, calc f x ≤ f y + C * edist x y : h x y ... ≤ f y + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f y) ... = f y + ε : by rw hεC }, { calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f x) ... = f x + ε : by rw hεC } } } end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by norm_num), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end @[continuity] theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg : _) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end lemma emetric.is_closed_ball {a : α} {r : ℝ≥0∞} : is_closed (closed_ball a r) := is_closed_le (continuous_id.edist continuous_const) continuous_const @[simp] lemma emetric.diam_closure (s : set α) : diam (closure s) = diam s := begin refine le_antisymm (diam_le $ λ x hx y hy, _) (diam_mono subset_closure), have : edist x y ∈ closure (Iic (diam s)), from map_mem_closure₂ continuous_edist hx hy (λ x hx y hy, edist_le_diam_of_mem hx hy), rwa closure_Iic at this end @[simp] lemma metric.diam_closure {α : Type*} [pseudo_metric_space α] (s : set α) : metric.diam (closure s) = diam s := by simp only [metric.diam, emetric.diam_closure] lemma is_closed_set_of_lipschitz_on_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (s : set α) : is_closed {f : α → β | lipschitz_on_with K f s} := begin simp only [lipschitz_on_with, set_of_forall], refine is_closed_bInter (λ x hx, is_closed_bInter $ λ y hy, is_closed_le _ _), exacts [continuous.edist (continuous_apply x) (continuous_apply y), continuous_const] end lemma is_closed_set_of_lipschitz_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) : is_closed {f : α → β | lipschitz_with K f} := by simp only [← lipschitz_on_univ, is_closed_set_of_lipschitz_on_with] namespace real /-- For a bounded set `s : set ℝ`, its `emetric.diam` is equal to `Sup s - Inf s` reinterpreted as `ℝ≥0∞`. -/ lemma ediam_eq {s : set ℝ} (h : bounded s) : emetric.diam s = ennreal.of_real (Sup s - Inf s) := begin rcases eq_empty_or_nonempty s with rfl|hne, { simp }, refine le_antisymm (metric.ediam_le_of_forall_dist_le $ λ x hx y hy, _) _, { have := real.subset_Icc_Inf_Sup_of_bounded h, exact real.dist_le_of_mem_Icc (this hx) (this hy) }, { apply ennreal.of_real_le_of_le_to_real, rw [← metric.diam, ← metric.diam_closure], have h' := real.bounded_iff_bdd_below_bdd_above.1 h, calc Sup s - Inf s ≤ dist (Sup s) (Inf s) : le_abs_self _ ... ≤ diam (closure s) : dist_le_diam_of_mem h.closure (cSup_mem_closure hne h'.2) (cInf_mem_closure hne h'.1) } end /-- For a bounded set `s : set ℝ`, its `metric.diam` is equal to `Sup s - Inf s`. -/ lemma diam_eq {s : set ℝ} (h : bounded s) : metric.diam s = Sup s - Inf s := begin rw [metric.diam, real.ediam_eq h, ennreal.to_real_of_real], rw real.bounded_iff_bdd_below_bdd_above at h, exact sub_nonneg.2 (real.Inf_le_Sup s h.1 h.2) end @[simp] lemma ediam_Ioo (a b : ℝ) : emetric.diam (Ioo a b) = ennreal.of_real (b - a) := begin rcases le_or_lt b a with h|h, { simp [h] }, { rw [real.ediam_eq (bounded_Ioo _ _), cSup_Ioo h, cInf_Ioo h] }, end @[simp] lemma ediam_Icc (a b : ℝ) : emetric.diam (Icc a b) = ennreal.of_real (b - a) := begin rcases le_or_lt a b with h|h, { rw [real.ediam_eq (bounded_Icc _ _), cSup_Icc h, cInf_Icc h] }, { simp [h, h.le] } end @[simp] lemma ediam_Ico (a b : ℝ) : emetric.diam (Ico a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ico_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ico_self) @[simp] lemma ediam_Ioc (a b : ℝ) : emetric.diam (Ioc a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ioc_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ioc_self) lemma diam_Icc {a b : ℝ} (h : a ≤ b) : metric.diam (Icc a b) = b - a := by simp [metric.diam, ennreal.to_real_of_real, sub_nonneg.2 h] lemma diam_Ico {a b : ℝ} (h : a ≤ b) : metric.diam (Ico a b) = b - a := by simp [metric.diam, ennreal.to_real_of_real, sub_nonneg.2 h] lemma diam_Ioc {a b : ℝ} (h : a ≤ b) : metric.diam (Ioc a b) = b - a := by simp [metric.diam, ennreal.to_real_of_real, sub_nonneg.2 h] lemma diam_Ioo {a b : ℝ} (h : a ≤ b) : metric.diam (Ioo a b) = b - a := by simp [metric.diam, ennreal.to_real_of_real, sub_nonneg.2 h] end real /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
a6ab7c5a976bbc7bf1e06942223c4890153025ed
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/defeq_simp2.lean
0a5d968c906c4cb439aabde4f9e9ca1b7ca46b4a
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,204
lean
open tactic constant f (n : nat) : n ≥ 0 → nat axiom foo1 (n : nat) : n ≥ 0 axiom foo2 (n : nat) : n ≥ 0 axiom foo3 (n : nat) : n ≥ 0 -- by default we dont canonize proofs example (a b : nat) (H : f a (foo1 a) = f a (foo2 a)) : true := by do s ← simp_lemmas.mk_default, e ← get_local `H >>= infer_type, s^.dsimplify [] e {fail_if_unchanged := ff} >>= trace, constructor constant x1 : nat -- update the environment to force defeq_canonize cache to be reset example (a b : nat) (H : f a (foo1 a) = f a (foo2 a)) : true := by do s ← simp_lemmas.mk_default, e ← get_local `H >>= infer_type, s^.dsimplify [] e {fail_if_unchanged := ff} >>= trace, constructor constant x2 : nat -- update the environment to force defeq_canonize cache to be reset example (a b : nat) (H : f a (id (id (id (foo1 a)))) = f a (foo2 a)) : true := by do s ← simp_lemmas.mk_default, get_local `H >>= infer_type >>= s^.dsimplify >>= trace, constructor -- Example that does not work example (a b : nat) (H : (λ x, f x (id (id (id (foo1 x))))) = (λ x, f x (foo2 x))) : true := by do s ← simp_lemmas.mk_default, get_local `H >>= infer_type >>= s^.dsimplify >>= trace, constructor
12d0007172b9383febc47c30c82fbd2faf6015d1
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/order/complete_lattice.lean
bf56d5bb70cb49ebfe0cfbda5e579d47ec82250e
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,809
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Theory of complete lattices. -/ import order.bounds set_option old_structure_cmd true open set universes u v w w₂ variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂} /-- class for the `Sup` operator -/ class has_Sup (α : Type u) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type u) := (Inf : set α → α) /-- Supremum of a set -/ def Sup [has_Sup α] : set α → α := has_Sup.Sup /-- Infimum of a set -/ def Inf [has_Inf α] : set α → α := has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] (s : ι → α) : α := Inf (range s) lemma has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ lemma has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r section prio set_option default_priority 100 -- see Note [default priority] /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ 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) /-- 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, so it should be used with `.. complete_lattice_of_Inf α _`. -/ def complete_lattice_of_Inf (α : Type u) [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 _ _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, 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 } /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type u) extends complete_lattice α, decidable_linear_order α end prio 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 := Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha) theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha) @[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 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) := by finish /- le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t)) -/ @[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 -- 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) @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := iff.intro (assume h a ha, bot_unique $ h ▸ le_Sup ha) (assume h, bot_unique $ Sup_le $ assume a ha, le_bot_iff.2 $ h a ha) 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) := iff.intro (assume (h : Inf s = ⊥) b (hb : ⊥ < b), by rwa [←h, Inf_lt_iff] at hb) (assume h, bot_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_lt_of_le h (Inf_le ha)) lemma lt_supr_iff {ι : Sort*} {f : ι → α} : a < supr f ↔ (∃i, a < f i) := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {ι : Sort*} {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 supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h 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 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 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.map_supr_ge [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.map_supr2_ge [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.map_supr_ge ... ≤ f (⨆ i (h : ι' i), s i h) : hf.map_supr_ge -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type u} [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 unfold supr, apply congr_arg, ext, simp, split, exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩, exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩ 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⟩ /- I wanted to see if this would help for infi_comm; it doesn't. @[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂) : (: ⨅ i j, s i j :) ≤ (: s i j :) := begin transitivity, apply (infi_le (λ i, ⨅ j, s i j) i), apply infi_le end -/ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h 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 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⟩ 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)) := calc f (⨅ i (h : ι' i), s i h) ≤ (⨅ i, f (⨅ h, s i h)) : hf.map_infi_le ... ≤ (⨅ i h, f (s i h)) : infi_le_infi $ λ i, hf.map_infi_le @[congr] theorem infi_congr_Prop {α : Type u} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := begin unfold infi, apply congr_arg, ext, simp, split, exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩, exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩ end -- 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 := by rw [supr, range_const, Sup_singleton] @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := bot_unique $ supr_le $ assume i, le_refl _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := iff.intro (assume eq i, top_unique $ eq ▸ infi_le _ _) (assume h, top_unique $ le_infi $ assume i, top_le_iff.2 $ h i) @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := iff.intro (assume eq i, bot_unique $ eq ▸ le_supr _ _) (assume h, bot_unique $ supr_le $ assume i, le_bot_iff.2 $ h i) @[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 ⊥) := by rw [supr_eq_dif, dif_eq_if] lemma infi_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 infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := by rw [infi_eq_dif, dif_eq_if] -- 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) := le_antisymm (supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i) (supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j) @[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 := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) attribute [ematch] le_refl 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 {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := le_antisymm (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right) (le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right)) lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf i]; simp [inf_comm] lemma binfi_inf {ι : Sort*} {p : ι → Prop} {f : Πi, p i → α} {a : α} {i : ι} (hi : p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right) (le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left) (infi_le_of_le i $ infi_le_of_le hi $ inf_le_right)) theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := le_antisymm (supr_le $ assume i, sup_le (le_sup_left_of_le $ le_supr _ _) (le_sup_right_of_le $ le_supr _ _)) (sup_le (supr_le $ assume i, le_supr_of_le i le_sup_left) (supr_le $ assume i, le_supr_of_le i le_sup_right)) /- 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⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) 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 _ _) theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) 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)) := le_antisymm (supr_le $ assume s, match s with | or.inl i := le_sup_left_of_le $ le_supr _ i | or.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩)) theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := le_antisymm (le_infi $ assume b, le_infi $ assume h, Inf_le h) (le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h) theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma Sup_range {α : Type u} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type u} [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)) := le_antisymm (le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _)) (le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i) theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi ... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm] ... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm] ... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm] ... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr ... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm] ... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm] ... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm] ... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left] /- 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) := calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or ... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq 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) := calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or ... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := by rw [(union_eq_self_of_subset_left h).symm, supr_union]; exact le_sup_left 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 [show {a, b} = (insert b {a} : set β), from rfl, infi_insert, inf_comm], simp } theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := by simp theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by { rw [show {a, b} = (insert b {a} : set β), from rfl, supr_insert, sup_comm], simp } lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := le_antisymm (le_infi $ assume b, le_infi $ assume hbt, infi_le_of_le (f b) $ infi_le (λ_, g (f b)) (mem_image_of_mem f hbt)) (le_infi $ assume c, le_infi $ assume ⟨b, hbt, eq⟩, eq ▸ infi_le_of_le b $ infi_le (λ_, g (f b)) hbt) lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := le_antisymm (supr_le $ assume c, supr_le $ assume ⟨b, hbt, eq⟩, eq ▸ le_supr_of_le b $ le_supr (λ_, g (f b)) hbt) (supr_le $ assume b, supr_le $ assume hbt, le_supr_of_le (f b) $ le_supr (λ_, g (f b)) (mem_image_of_mem f hbt)) /- supr and infi under Type -/ @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i) @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le @[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) 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 := le_antisymm (le_inf (infi_le _ _) (infi_le _ _)) (le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end) 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.val 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 supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x.val x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm theorem infi_sigma {p : β → Type w} {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 w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_prod {γ : Type w} {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 w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) theorem infi_sum {γ : Type w} {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 w} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := le_antisymm (supr_le $ assume s, match s with | sum.inl i := le_sup_left_of_le $ le_supr _ i | sum.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩)) end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by rw [← Sup_range, Sup_eq_top]; from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff)) lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, b > f i) := by rw [← Inf_range, Inf_eq_bot]; from forall_congr (assume b, forall_congr (assume hb, 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_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 (assume ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (assume ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.complete_lattice {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := by { pi_instance; { intros, intro, apply_field, intros, simp at H, rcases H with ⟨ x, H₀, H₁ ⟩, subst b, apply a_1 _ H₀ i, } } lemma Inf_apply {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅f∈s, (f : Πa, β a) a) := by rw [← Inf_image]; refl lemma infi_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by erw [← Inf_range, Inf_apply, infi_range] lemma Sup_apply {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f∈s, (f : Πa, β a) a) := by rw [← Sup_image]; refl lemma supr_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := by erw [← Sup_range, Sup_apply, supr_range] 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, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h end complete_lattice section ord_continuous variables [complete_lattice α] [complete_lattice β] /-- A function `f` between complete lattices is order-continuous if it preserves all suprema. -/ def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i) lemma ord_continuous.sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ := by rw [← Sup_pair, ← Sup_pair, hf {a₁, a₂}, ← Sup_image, image_pair] lemma ord_continuous.mono {f : α → β} (hf : ord_continuous f) : monotone f := assume a₁ a₂ h, by rw [← sup_eq_right, ← hf.sup, sup_of_le_right h] end ord_continuous namespace order_dual variable (α) instance [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ 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.decidable_linear_order α } end order_dual 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
5b8ca01efa2267b9be65f7ff901bacfb9b036f82
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/category/constructions/product.hlean
cef0b991111e34c9092164b87c6d520ae576bfa4
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
5,470
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Product precategory and (TODO) category -/ import ..category ..nat_trans hit.trunc open eq prod is_trunc functor sigma trunc iso prod.ops nat_trans namespace category definition precategory_prod [constructor] [reducible] [instance] (obC obD : Type) [C : precategory obC] [D : precategory obD] : precategory (obC × obD) := precategory.mk' (λ a b, hom a.1 b.1 × hom a.2 b.2) (λ a b c g f, (g.1 ∘ f.1, g.2 ∘ f.2)) (λ a, (id, id)) (λ a b c d h g f, pair_eq !assoc !assoc ) (λ a b c d h g f, pair_eq !assoc' !assoc' ) (λ a b f, prod_eq !id_left !id_left ) (λ a b f, prod_eq !id_right !id_right) (λ a, prod_eq !id_id !id_id) _ definition Precategory_prod [reducible] [constructor] (C D : Precategory) : Precategory := precategory.Mk (precategory_prod C D) infixr ` ×c `:70 := Precategory_prod variables {C C' D D' X : Precategory} {u v : carrier (C ×c D)} theorem prod_hom_of_eq (p : u.1 = v.1) (q : u.2 = v.2) : hom_of_eq (prod_eq p q) = (hom_of_eq p, hom_of_eq q) := by induction u; induction v; esimp at *; induction p; induction q; reflexivity theorem prod_inv_of_eq (p : u.1 = v.1) (q : u.2 = v.2) : inv_of_eq (prod_eq p q) = (inv_of_eq p, inv_of_eq q) := by induction u; induction v; esimp at *; induction p; induction q; reflexivity theorem pr1_hom_of_eq (p : u.1 = v.1) (q : u.2 = v.2) : (hom_of_eq (prod_eq p q)).1 = hom_of_eq p := by exact ap pr1 !prod_hom_of_eq theorem pr1_inv_of_eq (p : u.1 = v.1) (q : u.2 = v.2) : (inv_of_eq (prod_eq p q)).1 = inv_of_eq p := by exact ap pr1 !prod_inv_of_eq theorem pr2_hom_of_eq (p : u.1 = v.1) (q : u.2 = v.2) : (hom_of_eq (prod_eq p q)).2 = hom_of_eq q := by exact ap pr2 !prod_hom_of_eq theorem pr2_inv_of_eq (p : u.1 = v.1) (q : u.2 = v.2) : (inv_of_eq (prod_eq p q)).2 = inv_of_eq q := by exact ap pr2 !prod_inv_of_eq definition pr1_functor [constructor] : C ×c D ⇒ C := functor.mk pr1 (λa b, pr1) (λa, idp) (λa b c g f, idp) definition pr2_functor [constructor] : C ×c D ⇒ D := functor.mk pr2 (λa b, pr2) (λa, idp) (λa b c g f, idp) definition functor_prod [constructor] [reducible] (F : X ⇒ C) (G : X ⇒ D) : X ⇒ C ×c D := functor.mk (λ a, pair (F a) (G a)) (λ a b f, pair (F f) (G f)) (λ a, abstract pair_eq !respect_id !respect_id end) (λ a b c g f, abstract pair_eq !respect_comp !respect_comp end) infixr ` ×f `:70 := functor_prod definition prod_functor_eta (F : X ⇒ C ×c D) : pr1_functor ∘f F ×f pr2_functor ∘f F = F := begin fapply functor_eq: esimp, { intro e, apply prod_eq: reflexivity}, { intro e e' f, apply prod_eq: esimp, { refine ap (λx, x ∘ _ ∘ _) !pr1_hom_of_eq ⬝ _, refine ap (λx, _ ∘ _ ∘ x) !pr1_inv_of_eq ⬝ _, esimp, apply id_leftright}, { refine ap (λx, x ∘ _ ∘ _) !pr2_hom_of_eq ⬝ _, refine ap (λx, _ ∘ _ ∘ x) !pr2_inv_of_eq ⬝ _, esimp, apply id_leftright}} end definition pr1_functor_prod (F : X ⇒ C) (G : X ⇒ D) : pr1_functor ∘f (F ×f G) = F := functor_eq (λx, idp) (λx y f, !id_leftright) definition pr2_functor_prod (F : X ⇒ C) (G : X ⇒ D) : pr2_functor ∘f (F ×f G) = G := functor_eq (λx, idp) (λx y f, !id_leftright) -- definition universal_property_prod {C D X : Precategory} (F : X ⇒ C) (G : X ⇒ D) -- : is_contr (Σ(H : X ⇒ C ×c D), pr1_functor ∘f H = F × pr2_functor ∘f H = G) := -- is_contr.mk -- ⟨functor_prod F G, (pr1_functor_prod F G, pr2_functor_prod F G)⟩ -- begin -- intro v, induction v with H w, induction w with p q, -- symmetry, fapply sigma_eq: esimp, -- { fapply functor_eq, -- { intro x, apply prod_eq: esimp, -- { exact ap010 to_fun_ob p x}, -- { exact ap010 to_fun_ob q x}}, -- { intro x y f, apply prod_eq: esimp, -- { exact sorry}, -- { exact sorry}}}, -- { exact sorry} -- end definition prod_functor_prod [constructor] (F : C ⇒ D) (G : C' ⇒ D') : C ×c C' ⇒ D ×c D' := (F ∘f pr1_functor) ×f (G ∘f pr2_functor) definition prod_nat_trans [constructor] {C D D' : Precategory} {F F' : C ⇒ D} {G G' : C ⇒ D'} (η : F ⟹ F') (θ : G ⟹ G') : F ×f G ⟹ F' ×f G' := begin fapply nat_trans.mk: esimp, { intro c, exact (η c, θ c)}, { intro c c' f, apply prod_eq: esimp:apply naturality} end infixr ` ×n `:70 := prod_nat_trans definition prod_flip_functor [constructor] (C D : Precategory) : C ×c D ⇒ D ×c C := functor.mk (λp, (p.2, p.1)) (λp p' h, (h.2, h.1)) (λp, idp) (λp p' p'' h' h, idp) definition functor_prod_flip_functor_prod_flip (C D : Precategory) : prod_flip_functor D C ∘f (prod_flip_functor C D) = functor.id := begin fapply functor_eq, { intro p, apply prod.eta}, { intro p p' h, cases p with c d, cases p' with c' d', apply id_leftright} end end category
24d43102a6fd36ed9b635781e2d71a77c859055f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/gen_fail.lean
1cfe577816fb70e6468c89cba25b44da63c8ceac
[ "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
116
lean
import data.examples.vector open nat theorem tst (n : nat) (v : vector nat n) : v = v := begin generalize n, end
2f8d727f208f81c618867f7cef3a664716a2f4f8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/lattice.lean
9590c769b0c133460b5e44894a582b6efdcc06af
[ "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
5,536
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Floris van Doorn, Gabriel Ebner, Yury Kudryashov -/ import data.nat.enat import order.conditionally_complete_lattice /-! # Conditionally complete linear order structure on `ℕ` In this file we * define a `conditionally_complete_linear_order_bot` structure on `ℕ`; * define a `complete_linear_order` structure on `enat`; * prove a few lemmas about `supr`/`infi`/`set.Union`/`set.Inter` and natural numbers. -/ open set namespace nat open_locale classical noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_def {s : set ℕ} (h : s.nonempty) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ @[simp] lemma Inf_eq_zero {s : set ℕ} : Inf s = 0 ↔ 0 ∈ s ∨ s = ∅ := begin cases eq_empty_or_nonempty s, { subst h, simp only [or_true, eq_self_iff_true, iff_true, Inf, has_Inf.Inf, mem_empty_eq, exists_false, dif_neg, not_false_iff] }, { have := ne_empty_iff_nonempty.mpr h, simp only [this, or_false, nat.Inf_def, h, nat.find_eq_zero] } end lemma Inf_mem {s : set ℕ} (h : s.nonempty) : Inf s ∈ s := by { rw [nat.Inf_def h], exact nat.find_spec h } lemma not_mem_of_lt_Inf {s : set ℕ} {m : ℕ} (hm : m < Inf s) : m ∉ s := begin cases eq_empty_or_nonempty s, { subst h, apply not_mem_empty }, { rw [nat.Inf_def h] at hm, exact nat.find_min h hm } end protected lemma Inf_le {s : set ℕ} {m : ℕ} (hm : m ∈ s) : Inf s ≤ m := by { rw [nat.Inf_def ⟨m, hm⟩], exact nat.find_min' ⟨m, hm⟩ hm } lemma nonempty_of_pos_Inf {s : set ℕ} (h : 0 < Inf s) : s.nonempty := begin by_contradiction contra, rw set.not_nonempty_iff_eq_empty at contra, have h' : Inf s ≠ 0, { exact ne_of_gt h, }, apply h', rw nat.Inf_eq_zero, right, assumption, end lemma nonempty_of_Inf_eq_succ {s : set ℕ} {k : ℕ} (h : Inf s = k + 1) : s.nonempty := nonempty_of_pos_Inf (h.symm ▸ (succ_pos k) : Inf s > 0) lemma eq_Ici_of_nonempty_of_upward_closed {s : set ℕ} (hs : s.nonempty) (hs' : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s) : s = Ici (Inf s) := ext (λ n, ⟨λ H, nat.Inf_le H, λ H, hs' (Inf s) n H (Inf_mem hs)⟩) lemma Inf_upward_closed_eq_succ_iff {s : set ℕ} (hs : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s) (k : ℕ) : Inf s = k + 1 ↔ k + 1 ∈ s ∧ k ∉ s := begin split, { intro H, rw [eq_Ici_of_nonempty_of_upward_closed (nonempty_of_Inf_eq_succ H) hs, H, mem_Ici, mem_Ici], exact ⟨le_refl _, k.not_succ_le_self⟩, }, { rintro ⟨H, H'⟩, rw [Inf_def (⟨_, H⟩ : s.nonempty), find_eq_iff], exact ⟨H, λ n hnk hns, H' $ hs n k (lt_succ_iff.mp hnk) hns⟩, }, end /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := lattice_of_linear_order noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_def hs]; exact hb (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (lattice_of_linear_order : lattice ℕ), .. (infer_instance : linear_order ℕ) } section variables {α : Type*} [complete_lattice α] lemma supr_lt_succ (u : ℕ → α) (n : ℕ) : (⨆ k < n + 1, u k) = (⨆ k < n, u k) ⊔ u n := by simp [nat.lt_succ_iff_lt_or_eq, supr_or, supr_sup_eq] lemma supr_lt_succ' (u : ℕ → α) (n : ℕ) : (⨆ k < n + 1, u k) = u 0 ⊔ (⨆ k < n, u (k + 1)) := by { rw ← sup_supr_nat_succ, simp } lemma infi_lt_succ (u : ℕ → α) (n : ℕ) : (⨅ k < n + 1, u k) = (⨅ k < n, u k) ⊓ u n := @supr_lt_succ (order_dual α) _ _ _ lemma infi_lt_succ' (u : ℕ → α) (n : ℕ) : (⨅ k < n + 1, u k) = u 0 ⊓ (⨅ k < n, u (k + 1)) := @supr_lt_succ' (order_dual α) _ _ _ end end nat namespace set variable {α : Type*} lemma bUnion_lt_succ (u : ℕ → set α) (n : ℕ) : (⋃ k < n + 1, u k) = (⋃ k < n, u k) ∪ u n := nat.supr_lt_succ u n lemma bUnion_lt_succ' (u : ℕ → set α) (n : ℕ) : (⋃ k < n + 1, u k) = u 0 ∪ (⋃ k < n, u (k + 1)) := nat.supr_lt_succ' u n lemma bInter_lt_succ (u : ℕ → set α) (n : ℕ) : (⋂ k < n + 1, u k) = (⋂ k < n, u k) ∩ u n := nat.infi_lt_succ u n lemma bInter_lt_succ' (u : ℕ → set α) (n : ℕ) : (⋂ k < n + 1, u k) = u 0 ∩ (⋂ k < n, u (k + 1)) := nat.infi_lt_succ' u n end set namespace enat open_locale classical noncomputable instance : complete_linear_order enat := { .. enat.linear_order, .. with_top_order_iso.symm.to_galois_insertion.lift_complete_lattice } end enat
cdbdde611478a7bd5a32c112afb53597b0da813e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/100-theorems-list/73_ascending_descending_sequences.lean
e909d44087044eae5dd7912606864d56a48eddf9
[ "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
8,145
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import tactic.basic import data.fintype.basic /-! # Erdős–Szekeres theorem This file proves Theorem 73 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also known as the Erdős–Szekeres theorem: given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. We use the proof outlined at https://en.wikipedia.org/wiki/Erdos-Szekeres_theorem#Pigeonhole_principle. ## Tags sequences, increasing, decreasing, Ramsey, Erdos-Szekeres, Erdős–Szekeres, Erdős-Szekeres -/ variables {α : Type*} [linear_order α] {β : Type*} open function finset open_locale classical /-- Given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. Proof idea: We label each value in the sequence with two numbers specifying the longest increasing subsequence ending there, and the longest decreasing subsequence ending there. We then show the pair of labels must be unique. Now if there is no increasing sequence longer than `r` and no decreasing sequence longer than `s`, then there are at most `r * s` possible labels, which is a contradiction if there are more than `r * s` elements. -/ theorem erdos_szekeres {r s n : ℕ} {f : fin n → α} (hn : r * s < n) (hf : injective f) : (∃ (t : finset (fin n)), r < t.card ∧ strict_mono_incr_on f ↑t) ∨ (∃ (t : finset (fin n)), s < t.card ∧ strict_mono_decr_on f ↑t) := begin -- Given an index `i`, produce the set of increasing (resp., decreasing) subsequences which ends -- at `i`. let inc_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = some i ∧ strict_mono_incr_on f ↑t), let dec_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = some i ∧ strict_mono_decr_on f ↑t), -- The singleton sequence is in both of the above collections. -- (This is useful to show that the maximum length subsequence is at least 1, and that the set -- of subsequences is nonempty.) have inc_i : ∀ i, {i} ∈ inc_sequences_ending_in i := λ i, by simp [strict_mono_incr_on], have dec_i : ∀ i, {i} ∈ dec_sequences_ending_in i := λ i, by simp [strict_mono_decr_on], -- Define the pair of labels: at index `i`, the pair is the maximum length of an increasing -- subsequence ending at `i`, paired with the maximum length of a decreasing subsequence ending -- at `i`. -- We call these labels `(a_i, b_i)`. let ab : fin n → ℕ × ℕ, { intro i, apply (max' ((inc_sequences_ending_in i).image card) (nonempty.image ⟨{i}, inc_i i⟩ _), max' ((dec_sequences_ending_in i).image card) (nonempty.image ⟨{i}, dec_i i⟩ _)) }, -- It now suffices to show that one of the labels is 'big' somewhere. In particular, if the -- first in the pair is more than `r` somewhere, then we have an increasing subsequence in our -- set, and if the second is more than `s` somewhere, then we have a decreasing subsequence. suffices : ∃ i, r < (ab i).1 ∨ s < (ab i).2, { obtain ⟨i, hi⟩ := this, apply or.imp _ _ hi, work_on_goal 0 { have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 1 { have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { intro hi, rw mem_image at this, obtain ⟨t, ht₁, ht₂⟩ := this, refine ⟨t, by rwa ht₂, _⟩, rw mem_filter at ht₁, apply ht₁.2.2 } }, -- Show first that the pair of labels is unique. have : injective ab, { apply injective_of_lt_imp_ne, intros i j k q, injection q with q₁ q₂, -- We have two cases: `f i < f j` or `f j < f i`. -- In the former we'll show `a_i < a_j`, and in the latter we'll show `b_i < b_j`. cases lt_or_gt_of_ne (λ _, ne_of_lt ‹i < j› (hf ‹f i = f j›)), work_on_goal 0 { apply ne_of_lt _ q₁, have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 1 { apply ne_of_lt _ q₂, have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { -- Reduce to showing there is a subsequence of length `a_i + 1` which ends at `j`. rw nat.lt_iff_add_one_le, apply le_max', rw mem_image at this ⊢, -- In particular we take the subsequence `t` of length `a_i` which ends at `i`, by definition -- of `a_i` rcases this with ⟨t, ht₁, ht₂⟩, rw mem_filter at ht₁, -- Ensure `t` ends at `i`. have : i ∈ t.max, simp [ht₁.2.1], -- Now our new subsequence is given by adding `j` at the end of `t`. refine ⟨insert j t, _, _⟩, -- First make sure it's valid, i.e., that this subsequence ends at `j` and is increasing { rw mem_filter, refine ⟨_, _, _⟩, { rw mem_powerset, apply subset_univ }, -- It ends at `j` since `i < j`. { convert max_insert, rw [ht₁.2.1, option.lift_or_get_some_some, max_eq_left, with_top.some_eq_coe], apply le_of_lt ‹i < j› }, -- To show it's increasing (i.e., `f` is monotone increasing on `t.insert j`), we do cases -- on what the possibilities could be - either in `t` or equals `j`. simp only [strict_mono_incr_on, strict_mono_decr_on, coe_insert, set.mem_insert_iff, mem_coe], -- Most of the cases are just bashes. rintros x ⟨rfl | _⟩ y ⟨rfl | _⟩ _, { apply (irrefl _ ‹j < j›).elim }, { exfalso, apply not_le_of_lt (trans ‹i < j› ‹j < y›) (le_max_of_mem ‹y ∈ t› ‹i ∈ t.max›) }, { apply lt_of_le_of_lt _ ‹f i < f j› <|> apply lt_of_lt_of_le ‹f j < f i› _, rcases lt_or_eq_of_le (le_max_of_mem ‹x ∈ t› ‹i ∈ t.max›) with _ | rfl, { apply le_of_lt (ht₁.2.2 ‹x ∈ t› (mem_of_max ‹i ∈ t.max›) ‹x < i›) }, { refl } }, { apply ht₁.2.2 ‹x ∈ t› ‹y ∈ t› ‹x < y› } }, -- Finally show that this new subsequence is one longer than the old one. { rw [card_insert_of_not_mem, ht₂], intro _, apply not_le_of_lt ‹i < j› (le_max_of_mem ‹j ∈ t› ‹i ∈ t.max›) } } }, -- Finished both goals! -- Now that we have uniqueness of each label, it remains to do some counting to finish off. -- Suppose all the labels are small. by_contra q, push_neg at q, -- Then the labels `(a_i, b_i)` all fit in the following set: `{ (x,y) | 1 ≤ x ≤ r, 1 ≤ y ≤ s }` let ran : finset (ℕ × ℕ) := ((range r).image nat.succ).product ((range s).image nat.succ), -- which we prove here. have : image ab univ ⊆ ran, -- First some logical shuffling { rintro ⟨x₁, x₂⟩, simp only [mem_image, exists_prop, mem_range, mem_univ, mem_product, true_and, prod.mk.inj_iff], rintros ⟨i, rfl, rfl⟩, specialize q i, -- Show `1 ≤ a_i` and `1 ≤ b_i`, which is easy from the fact that `{i}` is a increasing and -- decreasing subsequence which we did right near the top. have z : 1 ≤ (ab i).1 ∧ 1 ≤ (ab i).2, { split; { apply le_max', rw mem_image, refine ⟨{i}, by solve_by_elim, card_singleton i⟩ } }, refine ⟨_, _⟩, -- Need to get `a_i ≤ r`, here phrased as: there is some `a < r` with `a+1 = a_i`. { refine ⟨(ab i).1 - 1, _, nat.succ_pred_eq_of_pos z.1⟩, rw nat.sub_lt_right_iff_lt_add z.1, apply nat.lt_succ_of_le q.1 }, { refine ⟨(ab i).2 - 1, _, nat.succ_pred_eq_of_pos z.2⟩, rw nat.sub_lt_right_iff_lt_add z.2, apply nat.lt_succ_of_le q.2 } }, -- To get our contradiction, it suffices to prove `n ≤ r * s` apply not_le_of_lt hn, -- Which follows from considering the cardinalities of the subset above, since `ab` is injective. simpa [nat.succ_injective, card_image_of_injective, ‹injective ab›] using card_le_of_subset this, end
ea646a716039ef077b04df892565bdf86bb0ed0c
a047a4718edfa935d17231e9e6ecec8c7b701e05
/test/linarith.lean
6dba126d8961c5ef303faa08e233ba34e7cd76e0
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
8,302
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 (u v r s t : ℚ) (h : 0 < u*(t*v + t*r + s)) : 0 < (t*(r + v) + s)*3*u := by linarith example (A B : ℚ) (h : 0 < A * B) : 0 < 8*A*B := begin linarith end example (A B : ℚ) (h : 0 < A * B) : 0 < A*8*B := begin linarith end example (A B : ℚ) (h : 0 < A * B) : 0 < A*B/8 := begin linarith end example (A B : ℚ) (h : 0 < A * B) : 0 < A/8*B := begin linarith end 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 example (u v x y A B : ℚ) (a : 0 < A) (a_1 : 0 <= 1 - A) (a_2 : 0 <= B - 1) (a_3 : 0 <= B - x) (a_4 : 0 <= B - y) (a_5 : 0 <= u) (a_6 : 0 <= v) (a_7 : 0 < A - u) (a_8 : 0 < A - v) : u * y + v * x + u * v < 3 * A * B := by nlinarith example (u v x y A B : ℚ) : (0 < A) → (A ≤ 1) → (1 ≤ B) → (x ≤ B) → ( y ≤ B) → (0 ≤ u ) → (0 ≤ v ) → (u < A) → ( v < A) → (u * y + v * x + u * v < 3 * A * B) := begin intros, nlinarith end example (u v x y A B : ℚ) (a : 0 < A) (a_1 : 0 <= 1 - A) (a_2 : 0 <= B - 1) (a_3 : 0 <= B - x) (a_4 : 0 <= B - y) (a_5 : 0 <= u) (a_6 : 0 <= v) (a_7 : 0 < A - u) (a_8 : 0 < A - v) : (0 < A * A) -> (0 <= A * (1 - A)) -> (0 <= A * (B - 1)) -> (0 <= A * (B - x)) -> (0 <= A * (B - y)) -> (0 <= A * u) -> (0 <= A * v) -> (0 < A * (A - u)) -> (0 < A * (A - v)) -> (0 <= (1 - A) * A) -> (0 <= (1 - A) * (1 - A)) -> (0 <= (1 - A) * (B - 1)) -> (0 <= (1 - A) * (B - x)) -> (0 <= (1 - A) * (B - y)) -> (0 <= (1 - A) * u) -> (0 <= (1 - A) * v) -> (0 <= (1 - A) * (A - u)) -> (0 <= (1 - A) * (A - v)) -> (0 <= (B - 1) * A) -> (0 <= (B - 1) * (1 - A)) -> (0 <= (B - 1) * (B - 1)) -> (0 <= (B - 1) * (B - x)) -> (0 <= (B - 1) * (B - y)) -> (0 <= (B - 1) * u) -> (0 <= (B - 1) * v) -> (0 <= (B - 1) * (A - u)) -> (0 <= (B - 1) * (A - v)) -> (0 <= (B - x) * A) -> (0 <= (B - x) * (1 - A)) -> (0 <= (B - x) * (B - 1)) -> (0 <= (B - x) * (B - x)) -> (0 <= (B - x) * (B - y)) -> (0 <= (B - x) * u) -> (0 <= (B - x) * v) -> (0 <= (B - x) * (A - u)) -> (0 <= (B - x) * (A - v)) -> (0 <= (B - y) * A) -> (0 <= (B - y) * (1 - A)) -> (0 <= (B - y) * (B - 1)) -> (0 <= (B - y) * (B - x)) -> (0 <= (B - y) * (B - y)) -> (0 <= (B - y) * u) -> (0 <= (B - y) * v) -> (0 <= (B - y) * (A - u)) -> (0 <= (B - y) * (A - v)) -> (0 <= u * A) -> (0 <= u * (1 - A)) -> (0 <= u * (B - 1)) -> (0 <= u * (B - x)) -> (0 <= u * (B - y)) -> (0 <= u * u) -> (0 <= u * v) -> (0 <= u * (A - u)) -> (0 <= u * (A - v)) -> (0 <= v * A) -> (0 <= v * (1 - A)) -> (0 <= v * (B - 1)) -> (0 <= v * (B - x)) -> (0 <= v * (B - y)) -> (0 <= v * u) -> (0 <= v * v) -> (0 <= v * (A - u)) -> (0 <= v * (A - v)) -> (0 < (A - u) * A) -> (0 <= (A - u) * (1 - A)) -> (0 <= (A - u) * (B - 1)) -> (0 <= (A - u) * (B - x)) -> (0 <= (A - u) * (B - y)) -> (0 <= (A - u) * u) -> (0 <= (A - u) * v) -> (0 < (A - u) * (A - u)) -> (0 < (A - u) * (A - v)) -> (0 < (A - v) * A) -> (0 <= (A - v) * (1 - A)) -> (0 <= (A - v) * (B - 1)) -> (0 <= (A - v) * (B - x)) -> (0 <= (A - v) * (B - y)) -> (0 <= (A - v) * u) -> (0 <= (A - v) * v) -> (0 < (A - v) * (A - u)) -> (0 < (A - v) * (A - v)) -> u * y + v * x + u * v < 3 * A * B := begin intros, linarith end example (A B : ℚ) : (0 < A) → (1 ≤ B) → (0 < A / 8 * B) := begin intros, nlinarith end example (x y : ℚ) : 0 ≤ x ^2 + y ^2 := by nlinarith example (x y : ℚ) : 0 ≤ x*x + y*y := by nlinarith example (x y : ℚ) : x = 0 → y = 0 → x*x + y*y = 0 := by intros; nlinarith /- lemma norm_eq_zero_iff {x y : ℚ} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := begin split, { intro h, split; sorry }, -- should be solved after refactor { rintro ⟨⟩, nlinarith } end -/ -- should be solved after refactor /- lemma norm_nonpos_right {x y : ℚ} (h1 : x * x + y * y ≤ 0) : y = 0 := by nlinarith lemma norm_nonpos_left (x y : ℚ) (h1 : x * x + y * y ≤ 0) : x = 0 := by nlinarith -/
6e685a4c0c3e756cea9d13da2f78ebe0958878be
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/lcnfInferProjTypeBug.lean
e680089cc13fe734d1b9c88297e2d4a36b1b7ab7
[ "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
103
lean
import Lean set_option trace.Compiler.result true #eval Lean.Compiler.compile #[``Lean.Meta.mapMetaM]
8c710630e33aa29e5a20c5156f57b25d9203da7d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/shapes/terminal.lean
dd524d6093fc292521cc38beb20ac6882d377537
[ "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
12,890
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.pempty import category_theory.limits.has_limits import category_theory.epi_mono /-! # Initial and terminal objects in a category. ## References * [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B) -/ noncomputable theory universes v u u₂ open category_theory namespace category_theory.limits variables {C : Type u} [category.{v} C] /-- Construct a cone for the empty diagram given an object. -/ @[simps] def as_empty_cone (X : C) : cone (functor.empty C) := { X := X, π := by tidy } /-- Construct a cocone for the empty diagram given an object. -/ @[simps] def as_empty_cocone (X : C) : cocone (functor.empty C) := { X := X, ι := by tidy } /-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/ abbreviation is_terminal (X : C) := is_limit (as_empty_cone X) /-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/ abbreviation is_initial (X : C) := is_colimit (as_empty_cocone X) /-- An object `Y` is terminal if for every `X` there is a unique morphism `X ⟶ Y`. -/ def is_terminal.of_unique (Y : C) [h : Π X : C, unique (X ⟶ Y)] : is_terminal Y := { lift := λ s, (h s.X).default } /-- Transport a term of type `is_terminal` across an isomorphism. -/ def is_terminal.of_iso {Y Z : C} (hY : is_terminal Y) (i : Y ≅ Z) : is_terminal Z := is_limit.of_iso_limit hY { hom := { hom := i.hom }, inv := { hom := i.symm.hom } } /-- An object `X` is initial if for every `Y` there is a unique morphism `X ⟶ Y`. -/ def is_initial.of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : is_initial X := { desc := λ s, (h s.X).default } /-- Transport a term of type `is_initial` across an isomorphism. -/ def is_initial.of_iso {X Y : C} (hX : is_initial X) (i : X ≅ Y) : is_initial Y := is_colimit.of_iso_colimit hX { hom := { hom := i.hom }, inv := { hom := i.symm.hom } } /-- Give the morphism to a terminal object from any other. -/ def is_terminal.from {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X := t.lift (as_empty_cone Y) /-- Any two morphisms to a terminal object are equal. -/ lemma is_terminal.hom_ext {X Y : C} (t : is_terminal X) (f g : Y ⟶ X) : f = g := t.hom_ext (by tidy) @[simp] lemma is_terminal.comp_from {Z : C} (t : is_terminal Z) {X Y : C} (f : X ⟶ Y) : f ≫ t.from Y = t.from X := t.hom_ext _ _ @[simp] lemma is_terminal.from_self {X : C} (t : is_terminal X) : t.from X = 𝟙 X := t.hom_ext _ _ /-- Give the morphism from an initial object to any other. -/ def is_initial.to {X : C} (t : is_initial X) (Y : C) : X ⟶ Y := t.desc (as_empty_cocone Y) /-- Any two morphisms from an initial object are equal. -/ lemma is_initial.hom_ext {X Y : C} (t : is_initial X) (f g : X ⟶ Y) : f = g := t.hom_ext (by tidy) @[simp] lemma is_initial.to_comp {X : C} (t : is_initial X) {Y Z : C} (f : Y ⟶ Z) : t.to Y ≫ f = t.to Z := t.hom_ext _ _ @[simp] lemma is_initial.to_self {X : C} (t : is_initial X) : t.to X = 𝟙 X := t.hom_ext _ _ /-- Any morphism from a terminal object is split mono. -/ def is_terminal.split_mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : split_mono f := ⟨t.from _, t.hom_ext _ _⟩ /-- Any morphism to an initial object is split epi. -/ def is_initial.split_epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : split_epi f := ⟨t.to _, t.hom_ext _ _⟩ /-- Any morphism from a terminal object is mono. -/ lemma is_terminal.mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f := by haveI := t.split_mono_from f; apply_instance /-- Any morphism to an initial object is epi. -/ lemma is_initial.epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f := by haveI := t.split_epi_to f; apply_instance variable (C) /-- A category has a terminal object if it has a limit over the empty diagram. Use `has_terminal_of_unique` to construct instances. -/ abbreviation has_terminal := has_limits_of_shape (discrete pempty) C /-- A category has an initial object if it has a colimit over the empty diagram. Use `has_initial_of_unique` to construct instances. -/ abbreviation has_initial := has_colimits_of_shape (discrete pempty) C /-- An arbitrary choice of terminal object, if one exists. You can use the notation `⊤_ C`. This object is characterized by having a unique morphism from any object. -/ abbreviation terminal [has_terminal C] : C := limit (functor.empty C) /-- An arbitrary choice of initial object, if one exists. You can use the notation `⊥_ C`. This object is characterized by having a unique morphism to any object. -/ abbreviation initial [has_initial C] : C := colimit (functor.empty C) notation `⊤_` C:20 := terminal C notation `⊥_` C:20 := initial C section variables {C} /-- We can more explicitly show that a category has a terminal object by specifying the object, and showing there is a unique morphism to it from any other object. -/ lemma has_terminal_of_unique (X : C) [h : Π Y : C, unique (Y ⟶ X)] : has_terminal C := { has_limit := λ F, has_limit.mk { cone := { X := X, π := { app := pempty.rec _ } }, is_limit := { lift := λ s, (h s.X).default } } } /-- We can more explicitly show that a category has an initial object by specifying the object, and showing there is a unique morphism from it to any other object. -/ lemma has_initial_of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : has_initial C := { has_colimit := λ F, has_colimit.mk { cocone := { X := X, ι := { app := pempty.rec _ } }, is_colimit := { desc := λ s, (h s.X).default } } } /-- The map from an object to the terminal object. -/ abbreviation terminal.from [has_terminal C] (P : C) : P ⟶ ⊤_ C := limit.lift (functor.empty C) (as_empty_cone P) /-- The map to an object from the initial object. -/ abbreviation initial.to [has_initial C] (P : C) : ⊥_ C ⟶ P := colimit.desc (functor.empty C) (as_empty_cocone P) instance unique_to_terminal [has_terminal C] (P : C) : unique (P ⟶ ⊤_ C) := { default := terminal.from P, uniq := λ m, by { apply limit.hom_ext, rintro ⟨⟩ } } instance unique_from_initial [has_initial C] (P : C) : unique (⊥_ C ⟶ P) := { default := initial.to P, uniq := λ m, by { apply colimit.hom_ext, rintro ⟨⟩ } } @[simp] lemma terminal.comp_from [has_terminal C] {P Q : C} (f : P ⟶ Q) : f ≫ terminal.from Q = terminal.from P := by tidy @[simp] lemma initial.to_comp [has_initial C] {P Q : C} (f : P ⟶ Q) : initial.to P ≫ f = initial.to Q := by tidy /-- A terminal object is terminal. -/ def terminal_is_terminal [has_terminal C] : is_terminal (⊤_ C) := { lift := λ s, terminal.from _ } /-- An initial object is initial. -/ def initial_is_initial [has_initial C] : is_initial (⊥_ C) := { desc := λ s, initial.to _ } /-- Any morphism from a terminal object is split mono. -/ instance terminal.split_mono_from {Y : C} [has_terminal C] (f : ⊤_ C ⟶ Y) : split_mono f := is_terminal.split_mono_from terminal_is_terminal _ /-- Any morphism to an initial object is split epi. -/ instance initial.split_epi_to {Y : C} [has_initial C] (f : Y ⟶ ⊥_ C) : split_epi f := is_initial.split_epi_to initial_is_initial _ /-- An initial object is terminal in the opposite category. -/ def terminal_op_of_initial {X : C} (t : is_initial X) : is_terminal (opposite.op X) := { lift := λ s, (t.to s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- An initial object in the opposite category is terminal in the original category. -/ def terminal_unop_of_initial {X : Cᵒᵖ} (t : is_initial X) : is_terminal X.unop := { lift := λ s, (t.to (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } /-- A terminal object is initial in the opposite category. -/ def initial_op_of_terminal {X : C} (t : is_terminal X) : is_initial (opposite.op X) := { desc := λ s, (t.from s.X.unop).op, uniq' := λ s m w, quiver.hom.unop_inj (t.hom_ext _ _) } /-- A terminal object in the opposite category is initial in the original category. -/ def initial_unop_of_terminal {X : Cᵒᵖ} (t : is_terminal X) : is_initial X.unop := { desc := λ s, (t.from (opposite.op s.X)).unop, uniq' := λ s m w, quiver.hom.op_inj (t.hom_ext _ _) } /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cone for `J`. In `limit_of_diagram_initial` we show it is a limit cone. -/ @[simps] def cone_of_diagram_initial {J : Type v} [small_category J] {X : J} (tX : is_initial X) (F : J ⥤ C) : cone F := { X := F.obj X, π := { app := λ j, F.map (tX.to j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.id_comp, tX.hom_ext (tX.to j ≫ k) (tX.to j')], end } } /-- From a functor `F : J ⥤ C`, given an initial object of `J`, show the cone `cone_of_diagram_initial` is a limit. -/ def limit_of_diagram_initial {J : Type v} [small_category J] {X : J} (tX : is_initial X) (F : J ⥤ C) : is_limit (cone_of_diagram_initial tX F) := { lift := λ s, s.π.app X, uniq' := λ s m w, begin rw [← w X, cone_of_diagram_initial_π_app, tX.hom_ext (tX.to X) (𝟙 _)], dsimp, simp -- See note [dsimp, simp] end} -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object then the image of it is isomorphic to the limit of `F`. -/ @[reducible] def limit_of_initial {J : Type v} [small_category J] (F : J ⥤ C) [has_initial J] [has_limit F] : limit F ≅ F.obj (⊥_ J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (limit_of_diagram_initial initial_is_initial F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cocone for `J`. In `colimit_of_diagram_terminal` we show it is a colimit cocone. -/ @[simps] def cocone_of_diagram_terminal {J : Type v} [small_category J] {X : J} (tX : is_terminal X) (F : J ⥤ C) : cocone F := { X := F.obj X, ι := { app := λ j, F.map (tX.from j), naturality' := λ j j' k, begin dsimp, rw [← F.map_comp, category.comp_id, tX.hom_ext (k ≫ tX.from j') (tX.from j)], end } } /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, show the cocone `cocone_of_diagram_terminal` is a colimit. -/ def colimit_of_diagram_terminal {J : Type v} [small_category J] {X : J} (tX : is_terminal X) (F : J ⥤ C) : is_colimit (cocone_of_diagram_terminal tX F) := { desc := λ s, s.ι.app X, uniq' := λ s m w, by { rw [← w X, cocone_of_diagram_terminal_ι_app, tX.hom_ext (tX.from X) (𝟙 _)], simp } } -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object then the image of it is isomorphic to the colimit of `F`. -/ @[reducible] def colimit_of_terminal {J : Type v} [small_category J] (F : J ⥤ C) [has_terminal J] [has_colimit F] : colimit F ≅ F.obj (⊤_ J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_terminal terminal_is_terminal F) end section comparison variables {C} {D : Type u₂} [category.{v} D] (G : C ⥤ D) /-- The comparison morphism from the image of a terminal object to the terminal object in the target category. -/ -- TODO: Show this is an isomorphism if and only if `G` preserves terminal objects. def terminal_comparison [has_terminal C] [has_terminal D] : G.obj (⊤_ C) ⟶ ⊤_ D := terminal.from _ /-- The comparison morphism from the initial object in the target category to the image of the initial object. -/ -- TODO: Show this is an isomorphism if and only if `G` preserves initial objects. def initial_comparison [has_initial C] [has_initial D] : ⊥_ D ⟶ G.obj (⊥_ C) := initial.to _ end comparison variables {C} {J : Type v} [small_category J] /-- If `j` is initial in the index category, then the map `limit.π F j` is an isomorphism. -/ lemma is_iso_π_of_is_initial {j : J} (I : is_initial j) (F : J ⥤ C) [has_limit F] : is_iso (limit.π F j) := ⟨⟨limit.lift _ (cone_of_diagram_initial I F), ⟨by { ext, simp }, by simp⟩⟩⟩ instance is_iso_π_initial [has_initial J] (F : J ⥤ C) [has_limit F] : is_iso (limit.π F (⊥_ J)) := is_iso_π_of_is_initial (initial_is_initial) F /-- If `j` is terminal in the index category, then the map `colimit.ι F j` is an isomorphism. -/ lemma is_iso_ι_of_is_terminal {j : J} (I : is_terminal j) (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F j) := ⟨⟨colimit.desc _ (cocone_of_diagram_terminal I F), ⟨by simp, by { ext, simp }⟩⟩⟩ instance is_iso_ι_terminal [has_terminal J] (F : J ⥤ C) [has_colimit F] : is_iso (colimit.ι F (⊤_ J)) := is_iso_ι_of_is_terminal (terminal_is_terminal) F end category_theory.limits
30c02f7d2bb15fb53f4fbbeada6302f8e96d1eb0
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/assoc_flat.lean
7ec04dcdfaef4053035fd90a01d965cf3678c64d
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
2,275
lean
open tactic expr meta definition is_op_app (op : expr) (e : expr) : option (expr × expr) := match e with | (app (app fn a1) a2) := if op = fn then some (a1, a2) else none | e := none end meta definition flat_with : expr → expr → expr → expr → tactic (expr × expr) | op assoc e rhs := match (is_op_app op e) with | (some (a1, a2)) := do -- H₁ is a proof for a2 + rhs = rhs₁ (rhs₁, H₁) ← flat_with op assoc a2 rhs, -- H₂ is a proof for a1 + rhs₁ = rhs₂ (new_app, H₂) ← flat_with op assoc a1 rhs₁, -- We need to generate a proof that (a1 + a2) + rhs = a1 + (a2 + rhs) -- H₃ is a proof for (a1 + a2) + rhs = a1 + (a2 + rhs) H₃ ← return $ assoc a1 a2 rhs, -- H₃ is a proof for a1 + (a2 + rhs) = a1 + rhs1 H₄ ← to_expr ``(congr_arg %%(app op a1) %%H₁), H₅ ← to_expr ``(eq.trans %%H₃ %%H₄), H ← to_expr ``(eq.trans %%H₅ %%H₂), return (new_app, H) | none := do new_app ← return $ op e rhs, H ← to_expr ``(eq.refl %%new_app), return (new_app, H) end meta definition flat : expr → expr → expr → tactic (expr × expr) | op assoc e := match (is_op_app op e) with | (some (a1, a2)) := do -- H₁ is a proof that a2 = new_a2 (new_a2, H₁) ← flat op assoc a2, -- H₂ is a proof that a1 + new_a2 = new_app (new_app, H₂) ← flat_with op assoc a1 new_a2, -- We need a proof that (a1 + a2) = new_app -- H₃ is a proof for a1 + a2 = a1 + new_a2 H₃ : expr ← to_expr ``(congr_arg %%(app op a1) %%H₁), H ← to_expr ``(eq.trans %%H₃ %%H₂), return (new_app, H) | none := do pr ← to_expr ``(eq.refl %%e), return (e, pr) end local infix `+` := nat.add set_option trace.app_builder true set_option pp.all true example (a b c d e f g : nat) : ((a + b) + c) + ((d + e) + (f + g)) = a + (b + (c + (d + (e + (f + g))))) := by do assoc : expr ← mk_const `nat.add_assoc, op : expr ← mk_const `nat.add, tgt ← target, match is_eq tgt with | (some (lhs, rhs)) := do r ← flat op assoc lhs, exact r.2 | none := failed end
57d84a4553cd00d6a51269da83028008634cab79
367134ba5a65885e863bdc4507601606690974c1
/src/topology/uniform_space/absolute_value.lean
5084786a25fd8c7980e76bb49134ad385740d830
[ "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
2,880
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import data.real.cau_seq import topology.uniform_space.basic /-! # Uniform structure induced by an absolute value We build a uniform space structure on a commutative ring `R` equipped with an absolute value into a linear ordered field `𝕜`. Of course in the case `R` is `ℚ`, `ℝ` or `ℂ` and `𝕜 = ℝ`, we get the same thing as the metric space construction, and the general construction follows exactly the same path. ## Implementation details Note that we import `data.real.cau_seq` because this is where absolute values are defined, but the current file does not depend on real numbers. TODO: extract absolute values from that `data.real` folder. ## References * [N. Bourbaki, *Topologie générale*][bourbaki1966] ## Tags absolute value, uniform spaces -/ open set function filter uniform_space open_locale filter namespace is_absolute_value variables {𝕜 : Type*} [linear_ordered_field 𝕜] variables {R : Type*} [comm_ring R] (abv : R → 𝕜) [is_absolute_value abv] /-- The uniformity coming from an absolute value. -/ def uniform_space_core : uniform_space.core R := { uniformity := (⨅ ε>0, 𝓟 {p:R×R | abv (p.2 - p.1) < ε}), refl := le_infi $ assume ε, le_infi $ assume ε_pos, principal_mono.2 (λ ⟨x, y⟩ h, by simpa [show x = y, from h, abv_zero abv]), symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ λ ⟨x, y⟩ h, have h : abv (y - x) < ε, by simpa [-sub_eq_add_neg] using h, by rwa abv_sub abv at h, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos h zero_lt_two) (subset.refl _)) $ have ∀ (a b c : R), abv (c-a) < ε / 2 → abv (b-c) < ε / 2 → abv (b-a) < ε, from assume a b c hac hcb, calc abv (b - a) ≤ _ : abv_sub_le abv b c a ... = abv (c - a) + abv (b - c) : add_comm _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel] } /-- The uniform structure coming from an absolute value. -/ def uniform_space : uniform_space R := uniform_space.of_core (uniform_space_core abv) theorem mem_uniformity {s : set (R×R)} : s ∈ (uniform_space_core abv).uniformity ↔ (∃ε>0, ∀{a b:R}, abv (b - a) < ε → (a, b) ∈ s) := begin suffices : s ∈ (⨅ ε: {ε : 𝕜 // ε > 0}, 𝓟 {p:R×R | abv (p.2 - p.1) < ε.val}) ↔ _, { rw infi_subtype at this, exact this }, rw mem_infi, { simp [subset_def] }, { exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩, }, end end is_absolute_value
aa650786329daf357720c75f29ba4d42f5f49f90
e9dbaaae490bc072444e3021634bf73664003760
/src/Arith/CRing.lean
af6675c73c6a58aa6efa812364c3a9e359105193
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,806
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Mario Carneiro Proving equalities in commutative rings, building on: 1. https://github.com/leanprover-community/mathlib/blob/master/src/tactic/ring2.lean 2. Grégoire, B. and Mahboubi, A., 2005, August. Proving equalities in a commutative ring done right in Coq. -/ import Init.Data.Nat import Init.Data.Int import Init.Data.Array import Init.Control.EState import Geo.Util namespace Arith universe u class CRing (α : Type u) extends HasOfNat α, HasAdd α, HasMul α, HasSub α, HasNeg α, HasPow α Nat := (add0 : ∀ (x : α), x + 0 = x) (addC : ∀ (x y : α), x + y = y + x) (addA : ∀ (x y z : α), (x + y) + z = x + (y + z)) (mul0 : ∀ (x : α), x * 0 = 0) (mul1 : ∀ (x : α), x * 1 = x) (mulC : ∀ (x y : α), x * y = y * x) (mulA : ∀ (x y z : α), (x * y) * z = x * (y * z)) (distribL : ∀ (x y z : α), x * (y + z) = x * y + x * z) (negMul : ∀ (x y : α), - (x * y) = (- x) * y) (negAdd : ∀ (x y : α), - (x + y) = (- x) + (- y)) (subDef : ∀ (x y : α), x - y = x + (- y)) (pow0 : ∀ (x : α), x^0 = 1) (powS : ∀ (x : α) (n : Nat), x^(n + 1) = x * x^n) inductive CRExpr : Type | atom : Nat → CRExpr | nat : Nat → CRExpr | add : CRExpr → CRExpr → CRExpr | mul : CRExpr → CRExpr → CRExpr | sub : CRExpr → CRExpr → CRExpr | neg : CRExpr → CRExpr | pow : CRExpr → Nat → CRExpr namespace CRExpr def hasBeq : CRExpr → CRExpr → Bool | atom x₁, atom x₂ => x₁ == x₂ | nat n₁, nat n₂ => n₁ == n₂ | add x₁ y₁, add x₂ y₂ => hasBeq x₁ x₂ && hasBeq y₁ y₂ | mul x₁ y₁, mul x₂ y₂ => hasBeq x₁ x₂ && hasBeq y₁ y₂ | sub x₁ y₁, sub x₂ y₂ => hasBeq x₁ x₂ && hasBeq y₁ y₂ | neg x₁, neg x₂ => hasBeq x₁ x₂ | pow x₁ k₁, pow x₂ k₂ => hasBeq x₁ x₂ && k₁ == k₂ | _, _ => false instance : HasBeq CRExpr := ⟨hasBeq⟩ def hasToString : CRExpr → String | atom x => "#" ++ toString x | nat n => toString n | add e₁ e₂ => "(add " ++ hasToString e₁ ++ " " ++ hasToString e₂ ++ ")" | mul e₁ e₂ => "(mul " ++ hasToString e₁ ++ " " ++ hasToString e₂ ++ ")" | sub e₁ e₂ => "(sub " ++ hasToString e₁ ++ " " ++ hasToString e₂ ++ ")" | neg e => "(neg " ++ hasToString e ++ ")" | pow e k => "(pow " ++ hasToString e ++ " " ++ toString k ++ ")" instance : HasToString CRExpr := ⟨hasToString⟩ instance : HasRepr CRExpr := ⟨hasToString⟩ instance : HasOfNat CRExpr := ⟨nat⟩ instance : HasAdd CRExpr := ⟨add⟩ instance : HasMul CRExpr := ⟨mul⟩ instance : HasSub CRExpr := ⟨sub⟩ instance : HasPow CRExpr Nat := ⟨pow⟩ instance : HasNeg CRExpr := ⟨neg⟩ def denote {α : Type u} [CRing α] (xs : Array α) : CRExpr → α | atom x => xs.get! x | nat n => ofNat α n | add x y => denote x + denote y | mul x y => denote x * denote y | sub x y => denote x - denote y | pow x k => (denote x)^k | neg x => - (denote x) -- TODO: consistent naming def denotationsEq (e₁ e₂ : CRExpr) : Prop := ∀ {α : Type u} [CRing α] (xs : Array α), e₁.denote xs = e₂.denote xs end CRExpr abbrev Atom := Nat abbrev Power := Nat -- Horner expressions -- Note: care must be taken to maintain "canonical forms" inductive HExpr : Type | int : Int → HExpr | hornerAux : ∀ (a : HExpr) (x : Atom) (k : Power) (b : HExpr), HExpr -- a[x]^k + b namespace HExpr def hasToString : HExpr → String | int k => "!" ++ toString k | hornerAux a x k b => "(h " ++ hasToString a ++ " " ++ toString x ++ " " ++ toString k ++ " " ++ hasToString b ++ ")" instance : HasToString HExpr := ⟨hasToString⟩ instance : HasRepr HExpr := ⟨hasToString⟩ instance : HasOfNat HExpr := ⟨λ n => int n⟩ def hasBeq : HExpr → HExpr → Bool | int n₁, int n₂ => n₁ == n₂ | hornerAux a₁ x₁ k₁ b₁, hornerAux a₂ x₂ k₂ b₂ => hasBeq a₁ a₂ && x₁ == x₂ && k₁ == k₂ && hasBeq b₁ b₂ | _, _ => false instance : HasBeq HExpr := ⟨hasBeq⟩ def atom (x : Atom) : HExpr := hornerAux 1 x 1 0 -- Constructor that maintains canonical form. def horner (a : HExpr) (x : Atom) (k : Power) (b : HExpr) : HExpr := match a with | int c => if c = 0 then b else hornerAux a x k b | hornerAux a₁ x₁ k₁ b₁ => if x₁ = x ∧ b₁ == 0 then hornerAux a₁ x (k₁ + k) b else hornerAux a x k b /- -- The "correct" version, but the compiler can't find "recOn" def addConst (c₁ : Int) (e₂ : HExpr) : HExpr := if c₁ == 0 then e₂ else @HExpr.recOn (λ _ => HExpr) e₂ (λ (c₂ : Int) => int (c₁ + c₂)) (λ a₂ x₂ k₂ b₂ _ B₂ => hornerAux a₂ x₂ k₂ B₂) -/ def addConstCore (c₁ : Int) : Nat → HExpr → HExpr | 0, e₂ => panic! "addConstCore out of fuel" | fuel+1, e₂ => if c₁ == 0 then e₂ else match e₂ with | int c₂ => int (c₁ + c₂) | hornerAux a₂ x₂ k₂ b₂ => hornerAux a₂ x₂ k₂ (addConstCore fuel b₂) def addConst (c₁ : Int) (e₂ : HExpr) : HExpr := addConstCore c₁ 10000 e₂ def addAux (a₁ : HExpr) (addA₁ : HExpr → HExpr) (x₁ : Atom) : HExpr → Power → HExpr → (HExpr → HExpr) → HExpr | int c₂, k₁, b₁, ϕ => addConst c₂ (hornerAux a₁ x₁ k₁ b₁) | e₂@(hornerAux a₂ x₂ k₂ b₂), k₁, b₁, ϕ => if x₁ < x₂ then hornerAux a₁ x₁ k₁ (ϕ e₂) else if x₂ < x₁ then hornerAux a₂ x₂ k₂ (addAux b₂ k₁ b₁ ϕ) else if k₁ < k₂ then hornerAux (addA₁ $ hornerAux a₂ x₁ (k₂ - k₁) 0) x₁ k₁ (ϕ b₂) else if k₂ < k₁ then hornerAux (addAux a₂ (k₁ - k₂) 0 id) x₁ k₂ (ϕ b₂) else horner (addA₁ a₂) x₁ k₁ (ϕ b₂) def add : HExpr → HExpr → HExpr | int c₁, e₂ => addConst c₁ e₂ | hornerAux a₁ x₁ k₁ b₁, e₂ => addAux a₁ (add a₁) x₁ e₂ k₁ b₁ (add b₁) instance : HasAdd HExpr := ⟨add⟩ def neg : HExpr → HExpr | int n => int (-n) | hornerAux a x k b => hornerAux (neg a) x k (neg b) instance : HasNeg HExpr := ⟨neg⟩ /- The "correct" version. See `addConst` above for context. def mulConst (c₁ : Int) (e₂ : HExpr) : HExpr := if c₁ == 0 then 0 else if c₁ == 1 then e₂ else @HExpr.recOn (λ _ => HExpr) e₂ (λ (c₂ : Int) => int (c₁ * c₂)) (λ a₂ x₂ k₂ b₂ A₂ B₂ => hornerAux A₂ x₂ k₂ B₂) -/ def mulConstCore (c₁ : Int) : Nat → HExpr → HExpr | 0, e₂ => panic! "mulConstCore out of fuel" | fuel+1, e₂ => if c₁ == 0 then 0 else if c₁ == 1 then e₂ else match e₂ with | int c₂ => int (c₁ * c₂) | hornerAux a₂ x₂ k₂ b₂ => hornerAux (mulConstCore fuel a₂) x₂ k₂ (mulConstCore fuel b₂) def mulConst (c₁ : Int) (e₂ : HExpr) : HExpr := mulConstCore c₁ 10000 e₂ def mulAux (a₁ : HExpr) (x₁ : Atom) (k₁ : Power) (b₁ : HExpr) (mulA₁ mulB₁ : HExpr → HExpr) : HExpr → HExpr | int k₂ => mulConst k₂ (horner a₁ x₁ k₁ b₁) | e₂@(hornerAux a₂ x₂ k₂ b₂) => if x₁ < x₂ then horner (mulA₁ e₂) x₁ k₁ (mulB₁ e₂) else if x₂ < x₁ then horner (mulAux a₂) x₂ k₂ (mulAux b₂) else let t : HExpr := horner (mulAux a₂) x₁ k₂ 0; if b₂ == 0 then t else t + horner (mulA₁ b₂) x₁ k₁ (mulB₁ b₂) def mul : HExpr → HExpr → HExpr | int k₁ => mulConst k₁ | hornerAux a₁ x₁ k₁ b₁ => mulAux a₁ x₁ k₁ b₁ (mul a₁) (mul b₁) instance : HasMul HExpr := ⟨mul⟩ def pow (t : HExpr) : Nat → HExpr | 0 => 1 | 1 => t | k+1 => t * pow k instance : HasPow HExpr Nat := ⟨pow⟩ end HExpr namespace CRExpr def toHExpr : CRExpr → HExpr | atom x => HExpr.atom x | nat n => HExpr.int n | add x y => x.toHExpr + y.toHExpr | sub x y => x.toHExpr + - y.toHExpr | mul x y => x.toHExpr * y.toHExpr | neg x => - x.toHExpr | pow x k => x.toHExpr ^ k end CRExpr namespace HExpr def denote {α : Type u} [CRing α] (xs : Array α) : HExpr → α | HExpr.int n => if n ≥ 0 then ofNat α n.natAbs else - (ofNat α $ n.natAbs) | HExpr.hornerAux a x k b => a.denote * (xs.get! x)^k + b.denote -- TODO: this theorem is not true until we either restore primitive recursion -- or switch to returning an Option. axiom denoteCommutes {α : Type u} [CRing α] (xs : Array α) : ∀ (r : CRExpr), r.denote xs = r.toHExpr.denote xs end HExpr theorem CRingCorrect (r₁ r₂ : CRExpr) : r₁.toHExpr = r₂.toHExpr → CRExpr.denotationsEq r₁ r₂ := WIP end Arith
3b6a520ee03a09e338f0cb4fc6324f259b568774
46125763b4dbf50619e8846a1371029346f4c3db
/src/data/real/nnreal.lean
125f8759b39bf41506ae17098062135199970447
[ "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
20,771
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import data.real.basic order.lattice algebra.field noncomputable theory open lattice open_locale classical /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ instance : can_lift ℝ nnreal := { coe := coe, cond := λ r, r ≥ 0, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r := le_max_left r 0 lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≤ r := r.2 @[elim_cast, simp, nolint simp_nf] -- takes a crazy amount of time simplify lhs theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝ≥0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ @[simp] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp, move_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp, move_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp, move_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp, move_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma zero_div (r : ℝ≥0) : 0 / r = 0 := nnreal.eq (zero_div _) @[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := @nnreal.eq_iff r 0 instance : comm_semiring ℝ≥0 := begin refine { zero := 0, add := (+), one := 1, mul := (*), ..}; { intros; apply nnreal.eq; simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib, add_comm_monoid.zero, add_comm, add_left_comm] } end instance : is_semiring_hom (coe : ℝ≥0 → ℝ) := by refine_struct {..}; intros; refl @[move_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := is_monoid_hom.map_pow coe r n @[move_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := eq.symm $ l.sum_hom coe @[move_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := eq.symm $ l.prod_hom coe @[move_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := eq.symm $ s.sum_hom coe @[move_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := eq.symm $ s.prod_hom coe @[move_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.sum f) = s.sum (λa, (f a : ℝ)) := eq.symm $ s.sum_hom coe @[move_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.prod f) = s.prod (λa, (f a : ℝ)) := eq.symm $ s.prod_hom coe @[move_cast] lemma smul_coe (r : ℝ≥0) (n : ℕ) : ↑(add_monoid.smul n r) = add_monoid.smul n (r:ℝ) := is_add_monoid_hom.map_smul coe r n @[simp, squash_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := is_semiring_hom.map_nat_cast coe n instance : decidable_linear_order ℝ≥0 := decidable_linear_order.lift (coe : ℝ≥0 → ℝ) subtype.val_injective (by apply_instance) @[elim_cast] protected lemma coe_le {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[elim_cast] protected lemma coe_lt {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl @[elim_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl @[elim_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := subtype.ext.symm protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le.2 protected lemma of_real_mono : monotone nnreal.of_real := λ x y h, max_le_max h (le_refl 0) @[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r := nnreal.eq $ max_eq_left r.2 /-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ protected def gi : galois_insertion nnreal.of_real coe := galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono le_coe_of_real (λ _, of_real_coe) instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order } instance : canonically_ordered_monoid ℝ≥0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.lattice.order_bot, ..nnreal.decidable_linear_order } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.lattice.order_bot, .. nnreal.lattice.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.lattice.order_bot, .. nnreal.lattice.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c, mul_le_mul_of_nonneg_left := assume a b c, @mul_le_mul_of_nonneg_left ℝ _ a b c, mul_le_mul_of_nonneg_right := assume a b c, @mul_le_mul_of_nonneg_right ℝ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_lt_one := @zero_lt_one ℝ _, .. nnreal.decidable_linear_order, .. nnreal.canonically_ordered_monoid, .. nnreal.comm_semiring } instance : canonically_ordered_comm_semiring ℝ≥0 := { zero_ne_one := assume h, @zero_ne_one ℝ _ $ congr_arg subtype.val $ h, mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp, .. nnreal.linear_ordered_semiring, .. nnreal.canonically_ordered_monoid, .. nnreal.comm_semiring } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : has_Sup ℝ≥0 := ⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Sup_empty] }, rcases h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝ≥0 := ⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2) end⟩⟩ lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝ≥0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice.lattice_of_decidable_linear_order, .. nnreal.lattice.order_bot } instance : archimedean nnreal := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (add_monoid.smul n y : nnreal), by simp [*, smul_coe]⟩ ⟩ lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end lemma lt_iff_exists_rat_btwn (a b : nnreal) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end section of_real @[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma of_real_one : nnreal.of_real 1 = 1 := by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt.symm, lt_irrefl] @[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 := by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r)) lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 := of_real_eq_zero.2 @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) : nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p := by simp [nnreal.coe_le.symm, nnreal.of_real, hp] @[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} : nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt.symm, nnreal.of_real, lt_irrefl] lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans (and_iff_left h) lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p := nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := (of_real_add hr hp).symm lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p := nnreal.of_real_mono h lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p := nnreal.coe_le.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : p ≥ 0) : r ≤ nnreal.of_real p ↔ ↑r ≤ p := by rw [← nnreal.coe_le, nnreal.coe_of_real p hp] lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : r ≥ 0) : nnreal.of_real r < p ↔ r < ↑p := by rw [← nnreal.coe_lt, nnreal.coe_of_real r ha] lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt, nnreal.coe_of_real p h] }, { rw [of_real_eq_zero.2 h], split, intro, have := not_lt_of_le (zero_le r), contradiction, intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction } end end of_real section mul lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, have := max_eq_left (mul_nonneg hp hq), simpa [nnreal.of_real, hp, hq, max_eq_left] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] } end end mul section sub lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le] using h @[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe] lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r := of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt protected lemma sub_lt_self {r p : nnreal} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le, ← nnreal.coe_le, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le, nnreal.coe_le, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] @[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a := nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel] lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h, sub_sub_cancel, nnreal.of_real_coe] end sub section inv lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl @[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero @[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 := by rw [← nnreal.eq_iff, nnreal.coe_inv, nnreal.coe_zero, inv_eq_zero, ← nnreal.coe_zero, nnreal.eq_iff] @[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r := by simp [zero_lt_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := mul_pos hr (inv_pos.2 hp) @[simp] lemma inv_one : (1:ℝ≥0)⁻¹ = 1 := nnreal.eq $ inv_one @[simp] lemma div_one {r : ℝ≥0} : r / 1 = r := by rw [div_def, inv_one, mul_one] protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv' _ _ protected lemma inv_pow' {r : ℝ≥0} {n : ℕ} : (r^n)⁻¹ = (r⁻¹)^n := nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm } @[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 := nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h @[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 := by rw [mul_comm, inv_mul_cancel h] @[simp] lemma div_self {r : ℝ≥0} (h : r ≠ 0) : r / r = 1 := mul_inv_cancel h @[simp] lemma div_mul_cancel {r p : ℝ≥0} (h : p ≠ 0) : r / p * p = r := by rw [div_def, mul_assoc, inv_mul_cancel h, mul_one] @[simp] lemma mul_div_cancel {r p : ℝ≥0} (h : p ≠ 0) : r * p / p = r := by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one] @[simp] lemma mul_div_cancel' {r p : ℝ≥0} (h : r ≠ 0) : r * (p / r) = p := by rw [mul_comm, div_mul_cancel h] @[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq inv_inv' @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm] lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa [div_def] using half_lt_self zero_ne_one.symm end inv end nnreal
5a4629052dc58a294e80bf23c5573b67fb936840
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world2/level2.lean
c67f93d5266eb0e8f40fdd05ed7d221df0655a3c
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
2,226
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level1 -- hide namespace mynat -- hide /- # World 2 -- addition world ## Your theorems so far: * `add_zero (a : mynat) : a + 0 = a` * `add_succ (a b : mynat) : a + succ(b) = succ(a + b)` * `zero_add (a : mynat) : 0 + a = a` * (some stuff from tutorial world which we won't need for a while) Check out the "Theorem Statements" drop-down box on the left to see that these theorems have been added to addition world. This is a handy place to refresh your memory about exactly which theorems you have proved so far. As we go further through the game, more theorems will be added here. ## Level 2 -- `add_assoc` -- associativity of addition. It's well-known that (1 + 2) + 3 = 1 + (2 + 3) -- if we have three numbers to add up, it doesn't matter which of the additions we do first. This fact is called *associativity of addition* by mathematicians, and it is *not* obvious. For example, subtraction really is not associative: $(6 - 2) - 1$ is really not equal to $6 - (2 - 1)$. We are going to have to prove that addition, as defined the way we've defined it, is associative. See if you can prove associativity of addition. Hint: because addition was defined by recursion on the right-most variable, use induction on the right-most variable (try other variables at your peril!). Note that when Lean writes `a + b + c`, it means `(a + b) + c`. If it wants to talk about `a + (b + c)` it will put the brackets in explictly. Reminder: you are done when you see "Proof complete!" in the top right, and an empty box (no errors) in the bottom right. -/ /- Lemma On the set of natural numbers, addition is associative. In other words, for all natural numbers $a, b$ and $c$, we have $$ (a + b) + c = a + (b + c). $$ -/ lemma add_assoc (a b c : mynat) : (a + b) + c = a + (b + c) := begin [less_leaky] induction c with d hd, { -- ⊢ a + b + 0 = a + (b + 0) rw add_zero, rw add_zero, refl }, { -- ⊢ (a + b) + succ d = a + (b + succ d) rw add_succ, rw add_succ, rw add_succ, rw hd, refl, } end /- Once you have associativity (sub-boss), let's move on to commutativity (boss). -/ end mynat -- hide
d16aa7caa544e59fb6f7b48bbb8b28054b2980c5
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/e14.lean
7bf29c15bd3e7e4f22c35cd8c9bbe5671fd1e7df
[ "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
887
lean
prelude inductive nat : Type := | zero : nat | succ : nat → nat namespace nat end nat open nat inductive list (A : Type) : Type := | nil {} : list A | cons : A → list A → list A definition nil := @list.nil definition cons := @list.cons check nil check nil.{1} check @nil.{1} nat check @nil nat check cons nat.zero nil inductive vector (A : Type) : nat → Type := | vnil {} : vector A zero | vcons : forall {n : nat}, A → vector A n → vector A (succ n) namespace vector end vector open vector check vcons zero vnil constant n : nat check vcons n vnil check vector.rec definition vector_to_list {A : Type} {n : nat} (v : vector A n) : list A := vector.rec (@nil A) (fun (n : nat) (a : A) (v : vector A n) (l : list A), cons a l) v attribute vector_to_list [coercion] constant f : forall {A : Type}, list A → nat check f (cons zero nil) check f (vcons zero vnil)
34249e42daff71dd1819c314e21956ba77ed1a1d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/combinatorics/additive/pluennecke_ruzsa.lean
16eb9cd950f8d65b42650f725bd3c9a63241c53e
[ "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
11,327
lean
/- Copyright (c) 2022 Yaël Dillies, George Shakan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, George Shakan -/ import combinatorics.double_counting import data.finset.pointwise import data.rat.nnrat /-! # The Plünnecke-Ruzsa inequality This file proves Ruzsa's triangle inequality, the Plünnecke-Petridis lemma, and the Plünnecke-Ruzsa inequality. ## Main declarations * `finset.card_sub_mul_le_card_sub_mul_card_sub`: Ruzsa's triangle inequality, difference version. * `finset.card_add_mul_le_card_add_mul_card_add`: Ruzsa's triangle inequality, sum version. * `finset.pluennecke_petridis`: The Plünnecke-Petridis lemma. * `finset.card_smul_div_smul_le`: The Plünnecke-Ruzsa inequality. ## References * [Giorgis Petridis, *The Plünnecke-Ruzsa inequality: an overview*][petridis2014] * [Terrence Tao, Van Vu, *Additive Combinatorics][tao-vu] -/ open nat open_locale nnrat pointwise namespace finset variables {α : Type*} [comm_group α] [decidable_eq α] {A B C : finset α} /-- **Ruzsa's triangle inequality**. Division version. -/ @[to_additive card_sub_mul_le_card_sub_mul_card_sub "**Ruzsa's triangle inequality**. Subtraction version."] lemma card_div_mul_le_card_div_mul_card_div (A B C : finset α) : (A / C).card * B.card ≤ (A / B).card * (B / C).card := begin rw [←card_product (A / B), ←mul_one ((finset.product _ _).card)], refine card_mul_le_card_mul (λ b ac, ac.1 * ac.2 = b) (λ x hx, _) (λ x hx, card_le_one_iff.2 $ λ u v hu hv, ((mem_bipartite_below _).1 hu).2.symm.trans ((mem_bipartite_below _).1 hv).2), obtain ⟨a, c, ha, hc, rfl⟩ := mem_div.1 hx, refine card_le_card_of_inj_on (λ b, (a / b, b / c)) (λ b hb, _) (λ b₁ _ b₂ _ h, _), { rw mem_bipartite_above, exact ⟨mk_mem_product (div_mem_div ha hb) (div_mem_div hb hc), div_mul_div_cancel' _ _ _⟩ }, { exact div_right_injective (prod.ext_iff.1 h).1 } end /-- **Ruzsa's triangle inequality**. Div-mul-mul version. -/ @[to_additive card_sub_mul_le_card_add_mul_card_add "**Ruzsa's triangle inequality**. Sub-add-add version."] lemma card_div_mul_le_card_mul_mul_card_mul (A B C : finset α) : (A / C).card * B.card ≤ (A * B).card * (B * C).card := begin rw [←div_inv_eq_mul, ←card_inv B, ←card_inv (B * C), mul_inv, ←div_eq_mul_inv], exact card_div_mul_le_card_div_mul_card_div _ _ _, end /-- **Ruzsa's triangle inequality**. Mul-div-div version. -/ @[to_additive card_add_mul_le_card_sub_mul_card_add "**Ruzsa's triangle inequality**. Add-sub-sub version."] lemma card_mul_mul_le_card_div_mul_card_mul (A B C : finset α) : (A * C).card * B.card ≤ (A / B).card * (B * C).card := by { rw [←div_inv_eq_mul, ←div_inv_eq_mul B], exact card_div_mul_le_card_div_mul_card_div _ _ _ } /-- **Ruzsa's triangle inequality**. Mul-mul-div version. -/ @[to_additive card_add_mul_le_card_add_mul_card_sub "**Ruzsa's triangle inequality**. Add-add-sub version."] lemma card_mul_mul_le_card_mul_mul_card_div (A B C : finset α) : (A * C).card * B.card ≤ (A * B).card * (B / C).card := by { rw [←div_inv_eq_mul, div_eq_mul_inv B], exact card_div_mul_le_card_mul_mul_card_mul _ _ _ } @[to_additive] lemma mul_pluennecke_petridis (C : finset α) (hA : ∀ A' ⊆ A, (A * B).card * A'.card ≤ (A' * B).card * A.card) : (A * B * C).card * A.card ≤ (A * B).card * (A * C).card := begin induction C using finset.induction_on with x C hc ih, { simp }, set A' := A ∩ (A * C / {x}) with hA', set C' := insert x C with hC', have h₀ : A' * {x} = (A * {x}) ∩ (A * C), { rw [hA', inter_mul_singleton, (is_unit_singleton x).div_mul_cancel] }, have h₁ : A * B * C' = (A * B * C) ∪ (A * B * {x}) \ (A' * B * {x}), { rw [hC', insert_eq, union_comm, mul_union], refine (sup_sdiff_eq_sup _).symm, rw [mul_right_comm, mul_right_comm A, h₀], exact mul_subset_mul_right (inter_subset_right _ _) }, have h₂ : A' * B * {x} ⊆ A * B * {x} := mul_subset_mul_right (mul_subset_mul_right $ inter_subset_left _ _), have h₃ : (A * B * C').card ≤ (A * B * C).card + (A * B).card - (A' * B).card, { rw h₁, refine (card_union_le _ _).trans_eq _, rw [card_sdiff h₂, ←add_tsub_assoc_of_le (card_le_of_subset h₂), card_mul_singleton, card_mul_singleton] }, refine (mul_le_mul_right' h₃ _).trans _, rw [tsub_mul, add_mul], refine (tsub_le_tsub (add_le_add_right ih _) $ hA _ $ inter_subset_left _ _).trans_eq _, rw [←mul_add, ←mul_tsub, ←hA', insert_eq, mul_union, ←card_mul_singleton A x, ←card_mul_singleton A' x, add_comm (card _), h₀, eq_tsub_of_add_eq (card_union_add_card_inter _ _)], end /-! ### Sum triangle inequality -/ -- Auxiliary lemma for Ruzsa's triangle sum inequality, and the Plünnecke-Ruzsa inequality. @[to_additive] private lemma mul_aux (hA : A.nonempty) (hAB : A ⊆ B) (h : ∀ A' ∈ B.powerset.erase ∅, ((A * C).card : ℚ≥0) / ↑(A.card) ≤ ((A' * C).card) / ↑(A'.card)) : ∀ A' ⊆ A, (A * C).card * A'.card ≤ (A' * C).card * A.card := begin rintro A' hAA', obtain rfl | hA' := A'.eq_empty_or_nonempty, { simp }, have hA₀ : (0 : ℚ≥0) < A.card := cast_pos.2 hA.card_pos, have hA₀' : (0 : ℚ≥0) < A'.card := cast_pos.2 hA'.card_pos, exact_mod_cast (div_le_div_iff hA₀ hA₀').1 (h _ $ mem_erase_of_ne_of_mem hA'.ne_empty $ mem_powerset.2 $ hAA'.trans hAB), end /-- **Ruzsa's triangle inequality**. Multiplication version. -/ @[to_additive card_add_mul_card_le_card_add_mul_card_add "**Ruzsa's triangle inequality**. Addition version."] lemma card_mul_mul_card_le_card_mul_mul_card_mul (A B C : finset α) : (A * C).card * B.card ≤ (A * B).card * (B * C).card := begin obtain rfl | hB := B.eq_empty_or_nonempty, { simp }, have hB' : B ∈ B.powerset.erase ∅ := mem_erase_of_ne_of_mem hB.ne_empty (mem_powerset_self _), obtain ⟨U, hU, hUA⟩ := exists_min_image (B.powerset.erase ∅) (λ U, (U * A).card/U.card : _ → ℚ≥0) ⟨B, hB'⟩, rw [mem_erase, mem_powerset, ←nonempty_iff_ne_empty] at hU, refine cast_le.1 (_ : (_ : ℚ≥0) ≤ _), push_cast, refine (le_div_iff $ by exact cast_pos.2 hB.card_pos).1 _, rw [mul_div_right_comm, mul_comm _ B], refine (cast_le.2 $ card_le_card_mul_left _ hU.1).trans _, refine le_trans _ (mul_le_mul (hUA _ hB') (cast_le.2 $ card_le_of_subset $ mul_subset_mul_right hU.2) (zero_le _) $ zero_le _), rw [←mul_div_right_comm, ←mul_assoc], refine (le_div_iff $ by exact cast_pos.2 hU.1.card_pos).2 _, exact_mod_cast mul_pluennecke_petridis C (mul_aux hU.1 hU.2 hUA), end /-- **Ruzsa's triangle inequality**. Add-sub-sub version. -/ lemma card_mul_mul_le_card_div_mul_card_div (A B C : finset α) : (A * C).card * B.card ≤ (A / B).card * (B / C).card := begin rw [div_eq_mul_inv, ←card_inv B, ←card_inv (B / C), inv_div', div_inv_eq_mul], exact card_mul_mul_card_le_card_mul_mul_card_mul _ _ _, end /-- **Ruzsa's triangle inequality**. Sub-add-sub version. -/ lemma card_div_mul_le_card_mul_mul_card_div (A B C : finset α) : (A / C).card * B.card ≤ (A * B).card * (B / C).card := by { rw [div_eq_mul_inv, div_eq_mul_inv], exact card_mul_mul_card_le_card_mul_mul_card_mul _ _ _ } /-- **Ruzsa's triangle inequality**. Sub-sub-add version. -/ lemma card_div_mul_le_card_div_mul_card_mul (A B C : finset α) : (A / C).card * B.card ≤ (A / B).card * (B * C).card := by { rw [←div_inv_eq_mul, div_eq_mul_inv], exact card_mul_mul_le_card_div_mul_card_div _ _ _ } lemma card_add_nsmul_le {α : Type*} [add_comm_group α] [decidable_eq α] {A B : finset α} (hAB : ∀ A' ⊆ A, (A + B).card * A'.card ≤ (A' + B).card * A.card) (n : ℕ) : ((A + n • B).card : ℚ≥0) ≤ ((A + B).card / A.card) ^ n * A.card := begin obtain rfl | hA := A.eq_empty_or_nonempty, { simp }, induction n with n ih, { simp }, rw [succ_nsmul, ←add_assoc, pow_succ, mul_assoc, ←mul_div_right_comm, le_div_iff, ←cast_mul], swap, exact (cast_pos.2 hA.card_pos), refine (cast_le.2 $ add_pluennecke_petridis _ hAB).trans _, rw cast_mul, exact mul_le_mul_of_nonneg_left ih (zero_le _), end @[to_additive] lemma card_mul_pow_le (hAB : ∀ A' ⊆ A, (A * B).card * A'.card ≤ (A' * B).card * A.card) (n : ℕ) : ((A * B ^ n).card : ℚ≥0) ≤ ((A * B).card / A.card) ^ n * A.card := begin obtain rfl | hA := A.eq_empty_or_nonempty, { simp }, induction n with n ih, { simp }, rw [pow_succ, ←mul_assoc, pow_succ, @mul_assoc ℚ≥0, ←mul_div_right_comm, le_div_iff, ←cast_mul], swap, exact (cast_pos.2 hA.card_pos), refine (cast_le.2 $ mul_pluennecke_petridis _ hAB).trans _, rw cast_mul, exact mul_le_mul_of_nonneg_left ih (zero_le _), end /-- The **Plünnecke-Ruzsa inequality**. Multiplication version. Note that this is genuinely harder than the division version because we cannot use a double counting argument. -/ @[to_additive "The **Plünnecke-Ruzsa inequality**. Addition version. Note that this is genuinely harder than the subtraction version because we cannot use a double counting argument."] lemma card_pow_div_pow_le (hA : A.nonempty) (B : finset α) (m n : ℕ) : ((B ^ m / B ^ n).card : ℚ≥0) ≤ ((A * B).card / A.card) ^ (m + n) * A.card := begin have hA' : A ∈ A.powerset.erase ∅ := mem_erase_of_ne_of_mem hA.ne_empty (mem_powerset_self _), obtain ⟨C, hC, hCA⟩ := exists_min_image (A.powerset.erase ∅) (λ C, (C * B).card/C.card : _ → ℚ≥0) ⟨A, hA'⟩, rw [mem_erase, mem_powerset, ←nonempty_iff_ne_empty] at hC, refine (mul_le_mul_right $ cast_pos.2 hC.1.card_pos).1 _, norm_cast, refine (cast_le.2 $ card_div_mul_le_card_mul_mul_card_mul _ _ _).trans _, push_cast, rw mul_comm _ C, refine (mul_le_mul (card_mul_pow_le (mul_aux hC.1 hC.2 hCA) _) (card_mul_pow_le (mul_aux hC.1 hC.2 hCA) _) (zero_le _) $ zero_le _).trans _, rw [mul_mul_mul_comm, ←pow_add, ←mul_assoc], exact mul_le_mul_of_nonneg_right (mul_le_mul (pow_le_pow_of_le_left (zero_le _) (hCA _ hA') _) (cast_le.2 $ card_le_of_subset hC.2) (zero_le _) $ zero_le _) (zero_le _), end /-- The **Plünnecke-Ruzsa inequality**. Subtraction version. -/ @[to_additive "The **Plünnecke-Ruzsa inequality**. Subtraction version."] lemma card_pow_div_pow_le' (hA : A.nonempty) (B : finset α) (m n : ℕ) : ((B ^ m / B ^ n).card : ℚ≥0) ≤ ((A / B).card / A.card) ^ (m + n) * A.card := begin rw [←card_inv, inv_div', ←inv_pow, ←inv_pow, div_eq_mul_inv A], exact card_pow_div_pow_le hA _ _ _, end /-- Special case of the **Plünnecke-Ruzsa inequality**. Multiplication version. -/ @[to_additive "Special case of the **Plünnecke-Ruzsa inequality**. Addition version."] lemma card_pow_le (hA : A.nonempty) (B : finset α) (n : ℕ) : ((B ^ n).card : ℚ≥0) ≤ ((A * B).card / A.card) ^ n * A.card := by simpa only [pow_zero, div_one] using card_pow_div_pow_le hA _ _ 0 /-- Special case of the **Plünnecke-Ruzsa inequality**. Division version. -/ @[to_additive "Special case of the **Plünnecke-Ruzsa inequality**. Subtraction version."] lemma card_pow_le' (hA : A.nonempty) (B : finset α) (n : ℕ) : ((B ^ n).card : ℚ≥0) ≤ ((A / B).card / A.card) ^ n * A.card := by simpa only [pow_zero, div_one] using card_pow_div_pow_le' hA _ _ 0 end finset
a8aaaaa918db19974ff8b2babd9ebe7f69f8f90c
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world4/level1.lean
df2e5ff5abbf7697c778b75f46288c1f19953b41
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
1,567
lean
import game.world3.level9 -- hide import mynat.pow -- new import namespace mynat -- hide /- Axiom : pow_zero (a : mynat) : a ^ 0 = 1 -/ /- Axiom : pow_succ (a b : mynat) : a ^ succ(b) = a ^ b * a -/ /- # Power World A new world with seven levels. And a new import! This import gives you the power to make powers of your natural numbers. It is defined by recursion, just like addition and multiplication. Here are the two new axioms: * `pow_zero (a : mynat) : a ^ 0 = 1` * `pow_succ (a b : mynat) : a ^ succ(b) = a ^ b * a` The power function has various relations to addition and multiplication. If you have gone through levels 1--6 of addition world and levels 1--9 of multiplication world, you should have no trouble with this world: The usual tactics `induction`, `rw` and `refl` should see you through. You might want to fiddle with the drop-down menus on the left so you can see which theorems of Power World you have proved at any given time. Addition and multiplication -- we have a solid API for them now, i.e. if you need something about addition or multiplication, it's probably already in the library we have built. Collectibles are indication that we are proving the right things. The levels in this world were designed by Sian Carey, a UROP student at Imperial College London, funded by a Mary Lister McCammon Fellowship, in the summer of 2019. Thanks Sian! ## Level 1: `zero_pow_zero` -/ /- Lemma $0 ^ 0 = 1$. -/ lemma zero_pow_zero : (0 : mynat) ^ (0 : mynat) = 1 := begin [nat_num_game] rw pow_zero, refl, end end mynat -- hide
a4f055e634af3157cc23498cb781180c1ceed814
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/Reformat.lean
53f43103989a2b07744395622c600b2d46ec0701
[ "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
994
lean
/-! Parse and reformat file -/ import Lean.PrettyPrinter open Lean open Lean.Elab open Lean.Elab.Term open Std.Format open Std unsafe def main (args : List String) : IO Unit := do let (debug, f) : Bool × String := match args with | [f, "-d"] => (true, f) | [f] => (false, f) | _ => panic! "usage: file [-d]" let env ← mkEmptyEnvironment let stx ← Lean.Parser.testParseFile env args.head! let (f, _) ← (tryFinally (PrettyPrinter.ppModule stx) printTraces).toIO { options := Options.empty.setBool `trace.PrettyPrinter.format debug } { env := env } IO.print f let stx' ← Lean.Parser.testParseModule env args.head! (toString f) if stx' != stx then let stx := stx.getArg 1 let stx' := stx'.getArg 1 stx.getArgs.size.forM fun i => do if stx.getArg i != stx'.getArg i then throw $ IO.userError s!"reparsing failed:\n{stx.getArg i}\n{stx'.getArg i}" -- abbreviated Prelude.lean, which can be parsed without elaboration #eval main ["Reformat/Input.lean"]
e494c951e01b3a245f7fac87f1e5b695704af3bb
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/holor.lean
9e23effb51f64d62d26fb4bd9e02a2218c01d26a
[ "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
14,152
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import algebra.module.pi import algebra.big_operators.basic /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ universes u open list open_locale big_operators /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimensions `ds` -/ def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds} namespace holor_index variables {ds₁ ds₂ ds₃ : list ℕ} def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩ def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂ | ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩ lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm) lemma take_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left]) lemma drop_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds:list ℕ) := holor_index ds → α namespace holor variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ} instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩ instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩ instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩ instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩ instance [add_semigroup α] : add_semigroup (holor α ds) := by pi_instance instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by pi_instance instance [add_monoid α] : add_monoid (holor α ds) := by pi_instance instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by pi_instance instance [add_group α] : add_group (holor α ds) := by pi_instance instance [add_comm_group α] : add_comm_group (holor α ds) := by pi_instance /- scalar product -/ instance [has_mul α] : has_scalar α (holor α ds) := ⟨λ a x, λ t, a * x t⟩ instance [semiring α] : semimodule α (holor α ds) := pi.semimodule _ _ _ /-- The tensor product of two holors. -/ def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := λ t, x (t.take) * y (t.drop) local infix ` ⊗ ` : 70 := mul lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm) lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left := funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext (λt, right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))) @[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) : (0 : holor α ds₁) ⊗ x = 0 := funext (λ t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) : x ⊗ (0 :holor α ds₂) = 0 := funext (λ t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) : x ⊗ y = x ⟨[], forall₂.nil⟩ • y := by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := (λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩) /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := λ ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) : Π (t : holor_index (d :: ds)), (∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t | ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨(i :: is), hforall₂⟩ hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis, have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forall₂_cons.1 hiisdds).1, have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 := funext $ λ t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)]) lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) : slice (0 : holor α (d :: ds)) i hid = 0 := rfl lemma slice_sum [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : ∑ x in s, slice (f x) i hid = slice (∑ x in s, f x) i hid := begin letI := classical.dec_eq β, refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) : ∑ i in (finset.range d).attach, unit_vec d i ⊗ slice x i (nat.succ_le_of_lt (finset.mem_range.1 i.prop)) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i $ finset.mem_range.2 hid), { simp }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩), have hbi' : i ≠ b, { simpa only [ne.def, subtype.ext_iff, subtype.coe_mk] using hbi.symm }, simp [hbi'] }, { assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop | nil (x : holor α []) : cprank_max1 x | cons {d} {ds} (x : holor α [d]) (y : holor α ds) : cprank_max1 y → cprank_max1 (x ⊗ y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop | zero {ds} : cprank_max 0 (0 : holor α ds) | succ n {ds} (x : holor α ds) (y : holor α ds) : cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid α] [add_monoid α]: ∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds}, cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hx₂ hy } end lemma cprank_max_mul [ring α] : ∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x y₂ hy₂ } end lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (∑ x in s, f x) := by letI := classical.dec_eq β; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x ∉ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (∑ x in s, f x), { apply ih, assume (x : β) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Π (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)), from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)), from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [ring α] (x : holor α ds) : nat := @nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod := λ ds (x : holor α ds), by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
da5ba7e1c008c81ac5424274158ff63a630de7d6
572fb32b6f5b7c2bf26921ffa2abea054cce881a
/src/week_2/Part_B_subgroups.lean
c9c03b88292f4eb1192cbaaf20e63f0ff2e6ed1a
[ "Apache-2.0" ]
permissive
kgeorgiy/lean-formalising-mathematics
2deb30756d5a54bee1cfa64873e86f641c59c7dc
73429a8ded68f641c896b6ba9342450d4d3ae50f
refs/heads/master
1,683,029,640,682
1,621,403,041,000
1,621,403,041,000
367,790,347
0
0
null
null
null
null
UTF-8
Lean
false
false
18,460
lean
/- Change the below line to import week_2.kb_solutions.Part_A_groups_solutions (once the solutions are posted) if you want to get rid of the warning -/ import week_2.Part_A_groups /-! ## Subgroups We define the structure `subgroup G`, whose terms are subgroups of `G`. A subgroup of `G` is implemented as a subset of `G` closed under `1`, `*` and `⁻¹`. -/ namespace xena /-- A subgroup of a group G is a subset containing 1 and closed under multiplication and inverse. -/ structure subgroup (G : Type) [group G] := (carrier : set G) (one_mem' : (1 : G) ∈ carrier) (mul_mem' {x y} : x ∈ carrier → y ∈ carrier → x * y ∈ carrier) (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /- At this point, here's what we have. A term `H` of type `subgroup G`, written `H : subgroup G`, is a *quadruple*. To give a term `H : subgroup G` is to give the following four things: 1) `H.carrier` (a subset of `G`), 2) `H.one_mem'` (a proof that `1 ∈ H.carrier`), 3) `H.mul_mem'` (a proof that `H` is closed under multiplication) 4) `H.inv_mem'` (a proof that `H` is closed under inverses). Note in particular that Lean, being super-pedantic, *distinguishes* between the subgroup `H` and the subset `H.carrier`. One is a subgroup, one is a subset. When we get going we will start by setting up some infrastructure so that this difference will be hard to notice. Note also that if `x` is in the subgroup `H` of `H` then the _type_ of `x` is still `G`, and `x ∈ carrier` is a Proposition. Note also that `x : carrier` doesn't make sense (`carrier` is a term, not a type, rather counterintuitively). -/ namespace subgroup open xena.group -- let G be a group and let H, J, and K be subgroups variables {G : Type} [group G] (H J K : subgroup G) /- This `h ∈ H.carrier` notation kind of stinks. I don't want to write `H.carrier` everywhere, because I want to be able to identify the subgroup `H` with its underlying subset `H.carrier`. Note that these things are not _equal_, firstly because `H` contains the proof that `H.carrier` is a subgroup, and secondly because these terms have different types! `H` has type `subgroup G` and `H.carrier` has type `set G`. Let's start by sorting this out. -/ -- If `x : G` and `H : subgroup G` then let's define the notation -- `x ∈ H` to mean `x ∈ H.carrier` instance : has_mem G (subgroup G) := ⟨λ m H, m ∈ H.carrier⟩ -- Let's also define a "coercion", a.k.a. an "invisible map" -- from subgroups of `G` to subsets of `G`, sending `H` to `H.carrier`. -- The map is not completely invisible -- it's a little ↑. So -- if you see `↑H` in the future, it means the subset `H.carrier` by definition. instance : has_coe (subgroup G) (set G) := ⟨λ H, H.carrier⟩ -- `λ` is just computer science notation for ↦ (mapsto); so -- `λ H, H.carrier` is the function `H ↦ H.carrier`. -- Let's check we have this working, and also tell the simplifier that we -- would rather talk about `g ∈ H` than any other way of saying it. /-- `g` is in the underlying subset of `H` iff `g ∈ H`. -/ @[simp] lemma mem_carrier {g : G} : g ∈ H.carrier ↔ g ∈ H := by refl /-- `g` is in `H` considered as a subset of `G`, iff `g` is in `H` considered as subgroup of `G`. -/ @[simp] lemma mem_coe {g : G} : g ∈ (↑H : set G) ↔ g ∈ H := by refl -- Now let's define theorems without the `'`s in, which use this -- more natural notation /-- A subgroup contains the group's 1. -/ theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := by apply H.mul_mem' /-- A subgroup is closed under inverse -/ theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := by apply H.inv_mem' /- So here are the three theorems which you need to remember about subgroups. Say `H : subgroup G`. Then: `H.one_mem : (1 : G) ∈ H` `H.mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H` `H.inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H` These now look like the way a mathematician would write things. Now let's start to prove basic theorems about subgroups (or, as a the computer scientists would say, make a basic _interface_ or _API_ for subgroups), using this sensible notation. Here's an example; let's prove `x ∈ H ↔ x⁻¹ ∈ H`. Let's put the more complicated expression on the left hand side of the `↔` though, because then we can make it a `simp` lemma. -/ -- Remember that `xena.group.inv_inv x` is the statement that `x⁻¹⁻¹ = x` @[simp] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := begin split, { intro h, rw ← inv_inv x, apply H.inv_mem, exact h, }, { --intro h, apply H.inv_mem, --exact h, } end -- We could prove a bunch more theorems here. Let's just do one more. -- Let's show that if x and xy are in H then so is y. theorem mem_of_mem_mul_mem {x y : G} (hx : x ∈ H) (hxy : x * y ∈ H) : y ∈ H := begin rw ← inv_mem_iff at hx, convert H.mul_mem hx hxy, simp, -- rw [← one_mul y, ← mul_left_inv x, mul_assoc x⁻¹ x y], -- exact H.mul_mem hx hxy, end /- Subgroups are extensional objects (like most things in mathematics): two subgroups are equal if they have the same underlying subset, and also if they have the same underlying elements. Let's prove variants of this triviality now. The first one is rather un-mathematical: it takes a subgroup apart into its pieces. I'll see if you can do the other two! -/ /-- Two subgroups are equal if the underlying subsets are equal. -/ theorem ext' {H K : subgroup G} (h : H.carrier = K.carrier) : H = K := begin -- first take H and K apart cases H, -- H now broken up into its underlying 3-tuple. cases K, -- and now it must be obvious, so let's see if the simplifier can do it. simp * at *, -- it can! end -- here's a variant. You can prove it using `ext'`. /-- Two subgroups are equal if and only if the underlying subsets are equal. -/ theorem ext'_iff {H K : subgroup G} : H.carrier = K.carrier ↔ H = K := begin split, { exact ext', }, { rintro rfl, refl, } end -- to do this next one, first apply the `ext'` theorem we just proved, -- and then use the `ext` tactic (which works on sets) /-- Two subgroups are equal if they have the same elements. -/ @[ext] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := begin apply ext', ext, apply h, end /- We tagged that theorem with `ext`, so now the `ext` tactic works on subgroups too: if you ever have a goal of proving that two subgroups are equal, you can use the `ext` tactic to reduce to showing that they have the same elements. -/ /- ## The lattice structure on subgroups Subgroups of a group form what is known as a *lattice*. This is a partially ordered set with a sensible notion of max and min. We partially order subgroups by saying `H ≤ K` if `H.carrier ⊆ K.carrier`. Subgroups even have a good notion of an infinite Sup and Inf (the Inf of a bunch of subgroups is just their intersection; their Sup is the subgroup generated by their union). This combinatorial structure (a partially ordered set with good finite and infinite notions of Sup and Inf) is called a "complete lattice", and Lean has this structure inbuilt into it. We will construct a complete lattice structure on `subgroup G`. We start by defining a relation ≤ on the type of subgroups of a group. We say H ≤ K iff H.carrier ⊆ K.carrier . -/ /-- If `H` and `K` are subgroups of `G`, we write `H ≤ K` to mean `H.carrier ⊆ K.carrier` -/ instance : has_le (subgroup G) := ⟨λ H K, H.carrier ⊆ K.carrier⟩ -- useful to restate the definition so we can `rw` it lemma le_def : H ≤ K ↔ H.carrier ⊆ K.carrier := by refl -- another useful variant lemma le_iff : H ≤ K ↔ ∀ g, g ∈ H → g ∈ K := by refl -- Now let's check the axioms for a partial order. -- These are not hard, they just reduce immediately to the -- fact that ⊆ is a partial order @[refl] lemma le_refl : H ≤ H := begin rw le_def, -- Lean knows ⊆ is reflexive so the sneaky `refl` which Lean tries after `rw` -- has closed the goal! end lemma le_antisymm : H ≤ K → K ≤ H → H = K := begin rw [le_def, le_def, ← ext'_iff], -- now this is antisymmetry of ⊆, which Lean knows exact set.subset.antisymm, end @[trans] lemma le_trans : H ≤ J → J ≤ K → H ≤ K := begin rw [le_def, le_def, le_def], -- now this is transitivity of ⊆, which Lean knows exact set.subset.trans, end -- We've made `subgroup G` into a partial order! instance : partial_order (subgroup G) := { le := (≤), le_refl := le_refl, le_antisymm := le_antisymm, le_trans := le_trans } /- ### intersections Let's prove that the intersection of two subgroups is a subgroup. In Lean this is a definition: given two subgroups, we define a new subgroup whose underlying subset is the intersection of the subsets, and then prove the axioms. -/ /-- The intersection of two subgroups is also a subgroup -/ def inf (H K : subgroup G) : subgroup G := { carrier := H.carrier ∩ K.carrier, -- the carrier is the intersection one_mem' := ⟨H.one_mem', K.one_mem'⟩, mul_mem' := λ _ _ ⟨xH, xK⟩ ⟨yH, yK⟩, ⟨H.mul_mem' xH yH, K.mul_mem' xK yK⟩, inv_mem' := λ _ ⟨xH, xK⟩, ⟨H.inv_mem' xH, K.inv_mem' xK⟩ } -- Notation for `inf` in computer science circles is ⊓ . instance : has_inf (subgroup G) := ⟨inf⟩ /-- The underlying set of the inf of two subgroups is just their intersection -/ lemma inf_def (H K : subgroup G) : (H ⊓ K : set G) = (H : set G) ∩ K := by refl /- ## Subgroup generated by a subset. To do the sup of two subgroups is harder, because we don't just take the union, we need to then look at the subgroup generated by this union (e.g. the union of the x and y axes in ℝ² is not a subgroup). So we need to have a machine to spit out the subgroup of `G` generated by a subset `S : set G`. There are two completely different ways to do this. The first is a "top-down" approach. We could define the subgroup generated by `S` to be the intersection of all the subgroups of `G` that contain `S`. The second is a "bottom-up" approach. We could define the subgroup generated by `S` "by induction" (or more precisely by recursion), saying that `S` is in the subgroup, 1 is in the subgroup, the product of two things in the subgroup is in the subgroup, the inverse of something in the subgroup is in the subgroup, and that's it. Both methods come out rather nicely in Lean. Let's do the first one. We are going to be using a bunch of theorems about "bounded intersections", a.k.a. `set.bInter`. We will soon get tired of writing `set.blah` so let's `open set` so that we can skip it. -/ open set /- Here is the API for `set.bInter` (or `bInter`, as we can now call it): Notation: `⋂` (type with `\I`) If `X : set (subgroup G)`, i.e. if `X` is a set of subgroups of `G`, then `⋂ K ∈ X, (K : set G)` means "take the intersection of the underlying subsets". -- mem_bInter_iff says you're in the intersection iff you're in -- all the things you're intersecting. Very useful for rewriting. `mem_bInter_iff : (g ∈ ⋂ (K ∈ S), f K) ↔ (∀ K, K ∈ s → g ∈ f K)` -- mem_bInter is just the one way implication. Very useful for `apply`ing. `mem_bInter : (∀ K, K ∈ s → g ∈ f K) → (g ∈ ⋂ (K ∈ S), f K)` -/ /- We will consider the closure of a set as the intersect of all subgroups containing the set -/ /-- The Inf of a set of subgroups of G is their intersection. -/ def Inf (X : set (subgroup G)) : subgroup G := { carrier := ⋂ K ∈ X, (K : set G), -- carrier is the intersection of the underlying sets one_mem' := mem_bInter (λ x _, one_mem' x), mul_mem' := begin intros _ _ xI yI, rw mem_bInter_iff at *, exact λ K KX, K.mul_mem (xI K KX) (yI K KX), end, inv_mem' := begin intros _ xI, rw mem_bInter_iff at *, exact λ K KX, K.inv_mem (xI K KX), end, } /-- The *closure* of a subset `S` of `G` is the `Inf` of the subgroups of `G` which contain `S`. -/ def closure (S : set G) : subgroup G := Inf {H : subgroup G | S ⊆ H} -- we can restate mem_bInter_iff using our new "closure" language: lemma mem_closure_iff {S : set G} {x : G} : x ∈ closure S ↔ ∀ H : subgroup G, S ⊆ H → x ∈ H := mem_bInter_iff /- There is an underlying abstraction here, which you may not know about. A "closure operator" in mathematics https://en.wikipedia.org/wiki/Closure_operator is something mapping subsets of a set X to subsets of X, and satisfying three axioms: 1) `subset_closure : S ⊆ closure S` 2) `closure_mono : (S ⊆ T) → (closure S ⊆ closure T)` 3) `closure_closure : closure (closure S) = closure S` It works for closure in topological spaces, and it works here too. It also works for algebraic closures of fields, and there are several other places in mathematics where it shows up. This idea, of "abstracting" and axiomatising a phenomenon which shows up in more than one place, is really key in Lean. Let's prove these three lemmas in the case where `X = G` and `closure S` is the subgroup generated by `S`. Here are some things you might find helpful. Remember `mem_coe : g ∈ ↑H ↔ g ∈ H` `mem_carrier : g ∈ H.carrier ↔ g ∈ H` There's `mem_closure_iff : x ∈ closure S ↔ ∀ (H : subgroup G), S ⊆ ↑H → x ∈ H` (`closure S` is a subgroup so you might need to use `mem_coe` or `mem_carrier` first) For subsets there's `subset.trans : X ⊆ Y → Y ⊆ Z → X ⊆ Z` You might find `le_antisymm : H ≤ K → K ≤ H → H = K` from above useful -/ /- Reminder: X ⊆ Y means `∀ g, g ∈ X → g ∈ Y` and it's definitional, so you can just start this with `intro g`. -/ lemma subset_closure (S : set G) : S ⊆ ↑(closure S) := begin intros g gS, rw [mem_coe, mem_closure_iff], exact λ H SH, SH gS, end -- It's useful to know `subset.trans : X ⊆ Y → Y ⊆ Z → X ⊆ Z` lemma closure_mono {S T : set G} (hST : S ⊆ T) : closure S ≤ closure T := begin intros x xS, rw [mem_carrier, mem_closure_iff] at *, exact λ H TH, xS H (subset.trans hST TH), end -- not one of the axioms, but sometimes handy lemma closure_le (S : set G) (H : subgroup G) : closure S ≤ H ↔ S ⊆ ↑H := begin split, { exact λ hSH, subset.trans (subset_closure S) hSH, }, { intros hSH _ hgCS, rw [mem_carrier, mem_closure_iff] at hgCS, exact hgCS H hSH, } end -- You can start this one by applying `le_antisymm`, lemma closure_closure (S : set G) : closure S = closure (closure S) := begin apply le_antisymm, { apply subset_closure, }, { rw closure_le, exact λ _ hg, hg, } end example {α : Type} { A : set α} : A ⊆ A := rfl.subset -- This shows that every subgroup is the closure of something, namely its -- underlying subset. lemma closure_self {H : subgroup G} : closure ↑H = H := begin apply le_antisymm, { rw le_iff, intros g, rw mem_closure_iff, refine λ h, h H rfl.subset, }, { exact subset_closure H, } end /- Recall the second proposed construction of the subgroup closure of a subset `S`; it is the smallest subgroup `H` of `G` such that `S ⊆ H` and which contains `1` and is closed under `*` and `⁻¹`. This inductive constuction (which we did not make) comes with a so-called "recursor": if we have a true/false statement `p g` attached to each element `g` of G with the following properties: 1) `p s` is true for all `s ∈ S`, 2) `p 1` is true, 3) If `p x` and `p y` then `p (x * y)`, 4) If `p x` then `p x⁻¹` Then `p` is true on all of `closure S`. If we had made an inductive definition of `closure S` then this would have been true by definition! We used another definition, so we will have to prove it ourselves. -/ /-- An induction principle for closures. -/ lemma closure_induction {p : G → Prop} {S : set G} (HS : ∀ x ∈ S, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : -- conclusion after colon ∀ x, x ∈ closure S → p x := begin -- the subset of G where `p` is true is a subgroup. Let's call it H let H : subgroup G := { carrier := p, one_mem' := H1, mul_mem' := Hmul, inv_mem' := Hinv }, -- The goal is just that closure S ≤ H, by definition. change closure S ≤ H, -- Our hypothesis HS is just that S ⊆ ↑H, by definition change S ⊆ ↑H at HS, -- I think you can take it from here! rwa closure_le, end /- Finally we prove that the `closure` and `coe` maps form a `galois_insertion`. This is another abstraction, it generalises `galois_connection`, which is something that shows up all over the place (algebraic geometry, Galois theory etc). See https://en.wikipedia.org/wiki/Galois_connection A partial order can be considered as a category, with Hom(A,B) having one element if A ≤ B and no elements otherwise. A Galois connection between two partial orders is just a pair of adjoint functors between the categories. Adjointness in our case is `S ⊆ ↑H ↔ closure S ≤ H`. The reason it's an insertion and not just a connection is that if you start with a subgroup, take the underlying subset, and then look at the subgroup generated by that set, you get back to where you started. So it's like one of the adjoint functors being a forgetful functor. -/ def gi : galois_insertion (closure : set G → subgroup G) (coe : subgroup G → set G) := { choice := λ S _, closure S, gc := closure_le, le_l_u := λ H, subset_closure (H : set G), choice_eq := λ _ _, rfl } /- One use of this abstraction is that now we can pull back the complete lattice structure on `set G` to get a complete lattice structure on `subgroup G`. -/ instance : complete_lattice (subgroup G) := {.. galois_insertion.lift_complete_lattice gi} /- We just proved loads of lemmas about Infs and Sups of subgroups automatically, and have access to a ton more because the `complete_lattice` structure in Lean has a big API. See for example https://leanprover-community.github.io/mathlib_docs/order/complete_lattice.html#complete_lattice All those theorems are now true for subgroups. None are particularly hard to prove, but the point is that we don't now have to prove any of them ourselves. -/ end subgroup end xena /- Further work: `bot` and `top` (would have to explain the API for `singleton` and `univ`) -/
510316b7b197312161eee2cc5556cfdef10192c5
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/metric_space/baire.lean
5fbff5386f6034b7b8f5b0c37e3919482d2742fc
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
15,239
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Baire theorem: in a complete metric space, a countable intersection of dense open subsets is dense. The good concept underlying the theorem is that of a Gδ set, i.e., a countable intersection of open sets. Then Baire theorem can also be formulated as the fact that a countable intersection of dense Gδ sets is a dense Gδ set. We prove Baire theorem, giving several different formulations that can be handy. We also prove the important consequence that, if the space is covered by a countable union of closed sets, then the union of their interiors is dense. The names of the theorems do not contain the string "Baire", but are instead built from the form of the statement. "Baire" is however in the docstring of all the theorems, to facilitate grep searches. -/ import topology.metric_space.basic analysis.specific_limits noncomputable theory local attribute [instance] classical.prop_decidable open filter lattice encodable set variables {α : Type*} {β : Type*} {γ : Type*} section is_Gδ variable [topological_space α] /-- A Gδ set is a countable intersection of open sets. -/ def is_Gδ (s : set α) : Prop := ∃T : set (set α), (∀t ∈ T, is_open t) ∧ countable T ∧ s = (⋂₀ T) /-- An open set is a Gδ set. -/ lemma is_open.is_Gδ {s : set α} (h : is_open s) : is_Gδ s := ⟨{s}, by simp [h], countable_singleton _, (set.sInter_singleton _).symm⟩ lemma is_Gδ_bInter_of_open {ι : Type*} {I : set ι} (hI : countable I) {f : ι → set α} (hf : ∀i ∈ I, is_open (f i)) : is_Gδ (⋂i∈I, f i) := ⟨f '' I, by rwa ball_image_iff, countable_image _ hI, by rw sInter_image⟩ lemma is_Gδ_Inter_of_open {ι : Type*} [encodable ι] {f : ι → set α} (hf : ∀i, is_open (f i)) : is_Gδ (⋂i, f i) := ⟨range f, by rwa forall_range_iff, countable_range _, by rw sInter_range⟩ /-- A countable intersection of Gδ sets is a Gδ set. -/ lemma is_Gδ_sInter {S : set (set α)} (h : ∀s∈S, is_Gδ s) (hS : countable S) : is_Gδ (⋂₀ S) := begin have : ∀s : set α, ∃T : set (set α), s ∈ S → ((∀t ∈ T, is_open t) ∧ countable T ∧ s = (⋂₀ T)), { assume s, by_cases hs : s ∈ S, { simp [hs], exact h s hs }, { simp [hs] }}, choose T hT using this, refine ⟨⋃s∈S, T s, λt ht, _, _, _⟩, { simp only [exists_prop, set.mem_Union] at ht, rcases ht with ⟨s, hs, tTs⟩, exact (hT s hs).1 t tTs }, { exact countable_bUnion hS (λs hs, (hT s hs).2.1) }, { exact (sInter_bUnion (λs hs, (hT s hs).2.2)).symm } end /-- The union of two Gδ sets is a Gδ set. -/ lemma is_Gδ.union {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∪ t) := begin rcases hs with ⟨S, Sopen, Scount, sS⟩, rcases ht with ⟨T, Topen, Tcount, tT⟩, rw [sS, tT, sInter_union_sInter], apply is_Gδ_bInter_of_open (countable_prod Scount Tcount), rintros ⟨a, b⟩ hab, simp only [set.prod_mk_mem_set_prod_eq] at hab, have aopen : is_open a := Sopen a hab.1, have bopen : is_open b := Topen b hab.2, simp [aopen, bopen, is_open_union] end end is_Gδ section Baire_theorem open metric variables [metric_space α] [complete_space α] /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here when the source space is ℕ (and subsumed below by `dense_Inter_of_open` working with any encodable source space). -/ theorem dense_Inter_of_open_nat {f : ℕ → set α} (ho : ∀n, is_open (f n)) (hd : ∀n, closure (f n) = univ) : closure (⋂n, f n) = univ := begin let B : ℕ → ℝ := λn, ((1/2)^n : ℝ), have Bpos : ∀n, 0 < B n := λn, begin apply pow_pos, by norm_num end, /- Translate the density assumption into two functions `center` and `radius` associating to any n, x, δ, δpos a center and a positive radius such that `closed_ball center radius` is included both in `f n` and in `closed_ball x δ`. We can also require `radius ≤ (1/2)^(n+1), to ensure we get a Cauchy sequence later. -/ have : ∀n x δ, ∃y r, δ > 0 → (r > 0 ∧ r ≤ B (n+1) ∧ closed_ball y r ⊆ (closed_ball x δ) ∩ f n), { assume n x δ, by_cases δpos : δ > 0, { have : x ∈ closure (f n) := by simpa only [(hd n).symm] using mem_univ x, rcases mem_closure_iff'.1 this (δ/2) (half_pos δpos) with ⟨y, ys, xy⟩, rw dist_comm at xy, rcases is_open_iff.1 (ho n) y ys with ⟨r, rpos, hr⟩, refine ⟨y, min (min (δ/2) (r/2)) (B (n+1)), λ_, ⟨_, _, λz hz, ⟨_, _⟩⟩⟩, show 0 < min (min (δ / 2) (r/2)) (B (n+1)), from lt_min (lt_min (half_pos δpos) (half_pos rpos)) (Bpos (n+1)), show min (min (δ / 2) (r/2)) (B (n+1)) ≤ B (n+1), from min_le_right _ _, show z ∈ closed_ball x δ, from calc dist z x ≤ dist z y + dist y x : dist_triangle _ _ _ ... ≤ (min (min (δ / 2) (r/2)) (B (n+1))) + (δ/2) : add_le_add hz (le_of_lt xy) ... ≤ δ/2 + δ/2 : add_le_add (le_trans (min_le_left _ _) (min_le_left _ _)) (le_refl _) ... = δ : add_halves _, show z ∈ f n, from hr (calc dist z y ≤ min (min (δ / 2) (r/2)) (B (n+1)) : hz ... ≤ r/2 : le_trans (min_le_left _ _) (min_le_right _ _) ... < r : half_lt_self rpos) }, { use [x, 0] }}, choose center radius H using this, refine subset.antisymm (subset_univ _) (λx hx, _), refine metric.mem_closure_iff'.2 (λε εpos, _), /- ε is positive. We have to find a point in the ball of radius ε around x belonging to all `f n`. For this, we construct inductively a sequence `F n = (c n, r n)` such that the closed ball `closed_ball (c n) (r n)` is included in the previous ball and in `f n`, and such that `r n` is small enough to ensure that `c n` is a Cauchy sequence. Then `c n` converges to a limit which belongs to all the `f n`. -/ let F : ℕ → (α × ℝ) := λn, nat.rec_on n (prod.mk x (min (ε/2) 1)) (λn p, prod.mk (center n p.1 p.2) (radius n p.1 p.2)), let c : ℕ → α := λn, (F n).1, let r : ℕ → ℝ := λn, (F n).2, have rpos : ∀n, r n > 0, { assume n, induction n with n hn, exact lt_min (half_pos εpos) (zero_lt_one), exact (H n (c n) (r n) hn).1 }, have rB : ∀n, r n ≤ B n, { assume n, induction n with n hn, exact min_le_right _ _, exact (H n (c n) (r n) (rpos n)).2.1 }, have incl : ∀n, closed_ball (c (n+1)) (r (n+1)) ⊆ (closed_ball (c n) (r n)) ∩ (f n) := λn, (H n (c n) (r n) (rpos n)).2.2, have cdist : ∀n, dist (c n) (c (n+1)) ≤ B n, { assume n, rw dist_comm, have A : c (n+1) ∈ closed_ball (c (n+1)) (r (n+1)) := mem_closed_ball_self (le_of_lt (rpos (n+1))), have I := calc closed_ball (c (n+1)) (r (n+1)) ⊆ closed_ball (c n) (r n) : subset.trans (incl n) (inter_subset_left _ _) ... ⊆ closed_ball (c n) (B n) : closed_ball_subset_closed_ball (rB n), exact I A }, have : cauchy_seq c, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _), rw one_mul, exact cdist n }, -- as the sequence `c n` is Cauchy in a complete space, it converges to a limit `y`. rcases cauchy_seq_tendsto_of_complete this with ⟨y, ylim⟩, -- this point `y` will be the desired point. We will check that it belongs to all -- `f n` and to `ball x ε`. use y, simp only [exists_prop, set.mem_Inter], have I : ∀n, ∀m ≥ n, closed_ball (c m) (r m) ⊆ closed_ball (c n) (r n), { assume n, refine nat.le_induction _ (λm hnm h, _), { exact subset.refl _ }, { exact subset.trans (incl m) (subset.trans (inter_subset_left _ _) h) }}, have yball : ∀n, y ∈ closed_ball (c n) (r n), { assume n, refine mem_of_closed_of_tendsto (by simp) ylim is_closed_ball _, simp only [filter.mem_at_top_sets, nonempty_of_inhabited, set.mem_preimage_eq], exact ⟨n, λm hm, I n m hm (mem_closed_ball_self (le_of_lt (rpos m)))⟩ }, split, show ∀n, y ∈ f n, { assume n, have : closed_ball (c (n+1)) (r (n+1)) ⊆ f n := subset.trans (incl n) (inter_subset_right _ _), exact this (yball (n+1)) }, show dist x y < ε, from calc dist x y = dist y x : dist_comm _ _ ... ≤ r 0 : yball 0 ... < ε : lt_of_le_of_lt (min_le_left _ _) (half_lt_self εpos) end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_open {S : set (set α)} (ho : ∀s∈S, is_open s) (hS : countable S) (hd : ∀s∈S, closure s = univ) : closure (⋂₀S) = univ := begin by_cases h : S = ∅, { simp [h] }, { rcases exists_surjective_of_countable h hS with ⟨f, hf⟩, have F : ∀n, f n ∈ S := λn, by rw hf; exact mem_range_self _, rw [hf, sInter_range], exact dense_Inter_of_open_nat (λn, ho _ (F n)) (λn, hd _ (F n)) } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_open {S : set β} {f : β → set α} (ho : ∀s∈S, is_open (f s)) (hS : countable S) (hd : ∀s∈S, closure (f s) = univ) : closure (⋂s∈S, f s) = univ := begin rw ← sInter_image, apply dense_sInter_of_open, { rwa ball_image_iff }, { exact countable_image _ hS }, { rwa ball_image_iff } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_open [encodable β] {f : β → set α} (ho : ∀s, is_open (f s)) (hd : ∀s, closure (f s) = univ) : closure (⋂s, f s) = univ := begin rw ← sInter_range, apply dense_sInter_of_open, { rwa forall_range_iff }, { exact countable_range _ }, { rwa forall_range_iff } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_Gδ {S : set (set α)} (ho : ∀s∈S, is_Gδ s) (hS : countable S) (hd : ∀s∈S, closure s = univ) : closure (⋂₀S) = univ := begin -- the result follows from the result for a countable intersection of dense open sets, -- by rewriting each set as a countable intersection of open sets, which are of course dense. have : ∀s : set α, ∃T : set (set α), s ∈ S → ((∀t ∈ T, is_open t) ∧ countable T ∧ s = (⋂₀ T)), { assume s, by_cases hs : s ∈ S, { simp [hs], exact ho s hs }, { simp [hs] }}, choose T hT using this, have : ⋂₀ S = ⋂₀ (⋃s∈S, T s) := (sInter_bUnion (λs hs, (hT s hs).2.2)).symm, rw this, refine dense_sInter_of_open (λt ht, _) (countable_bUnion hS (λs hs, (hT s hs).2.1)) (λt ht, _), show is_open t, { simp only [exists_prop, set.mem_Union] at ht, rcases ht with ⟨s, hs, tTs⟩, exact (hT s hs).1 t tTs }, show closure t = univ, { simp only [exists_prop, set.mem_Union] at ht, rcases ht with ⟨s, hs, tTs⟩, apply subset.antisymm (subset_univ _), rw ← (hd s hs), apply closure_mono, have := sInter_subset_of_mem tTs, rwa ← (hT s hs).2.2 at this } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_Gδ {S : set β} {f : β → set α} (ho : ∀s∈S, is_Gδ (f s)) (hS : countable S) (hd : ∀s∈S, closure (f s) = univ) : closure (⋂s∈S, f s) = univ := begin rw ← sInter_image, apply dense_sInter_of_Gδ, { rwa ball_image_iff }, { exact countable_image _ hS }, { rwa ball_image_iff } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_Gδ [encodable β] {f : β → set α} (ho : ∀s, is_Gδ (f s)) (hd : ∀s, closure (f s) = univ) : closure (⋂s, f s) = univ := begin rw ← sInter_range, apply dense_sInter_of_Gδ, { rwa forall_range_iff }, { exact countable_range _ }, { rwa forall_range_iff } end /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bUnion_interior_of_closed {S : set β} {f : β → set α} (hc : ∀s∈S, is_closed (f s)) (hS : countable S) (hU : (⋃s∈S, f s) = univ) : closure (⋃s∈S, interior (f s)) = univ := begin let g := λs, - (frontier (f s)), have clos_g : closure (⋂s∈S, g s) = univ, { refine dense_bInter_of_open (λs hs, _) hS (λs hs, _), show is_open (g s), from is_open_compl_iff.2 is_closed_frontier, show closure (g s) = univ, { apply subset.antisymm (subset_univ _), simp [g, interior_frontier (hc s hs)] }}, have : (⋂s∈S, g s) ⊆ (⋃s∈S, interior (f s)), { assume x hx, have : x ∈ ⋃s∈S, f s, { have := mem_univ x, rwa ← hU at this }, rcases mem_bUnion_iff.1 this with ⟨s, hs, xs⟩, have : x ∈ g s := mem_bInter_iff.1 hx s hs, have : x ∈ interior (f s), { have : x ∈ f s \ (frontier (f s)) := mem_inter xs this, simpa [frontier, xs, closure_eq_of_is_closed (hc s hs)] using this }, exact mem_bUnion_iff.2 ⟨s, ⟨hs, this⟩⟩ }, have := closure_mono this, rw clos_g at this, exact subset.antisymm (subset_univ _) this end /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with ⋃₀. -/ theorem dense_sUnion_interior_of_closed {S : set (set α)} (hc : ∀s∈S, is_closed s) (hS : countable S) (hU : (⋃₀ S) = univ) : closure (⋃s∈S, interior s) = univ := by rw sUnion_eq_bUnion at hU; exact dense_bUnion_interior_of_closed hc hS hU /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Union_interior_of_closed [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : closure (⋃s, interior (f s)) = univ := begin rw ← bUnion_univ, apply dense_bUnion_interior_of_closed, { simp [hc] }, { apply countable_encodable }, { rwa ← bUnion_univ at hU } end /-- One of the most useful consequences of Baire theorem: if a countable union of closed sets covers the space, then one of the sets has nonempty interior. -/ theorem nonempty_interior_of_Union_of_closed [n : nonempty α] [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : ∃s x ε, ε > 0 ∧ ball x ε ⊆ f s := begin have : ∃s, interior (f s) ≠ ∅, { by_contradiction h, simp only [not_exists_not, ne.def] at h, have := calc ∅ = closure (⋃s, interior (f s)) : by simp [h] ... = univ : dense_Union_interior_of_closed hc hU, exact nonempty_iff_univ_ne_empty.1 n this.symm }, rcases this with ⟨s, hs⟩, rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hx⟩, rcases mem_nhds_iff.1 (mem_interior_iff_mem_nhds.1 hx) with ⟨ε, εpos, hε⟩, exact ⟨s, x, ε, εpos, hε⟩, end end Baire_theorem
c66d3e734f76ff9b4492e4eacd53e0ee913ec943
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/decClassical.lean
fa3aa9780c8138d22c145b025b29c811f00a98ac
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
302
lean
open Classical theorem ex : if (fun x => x + 1) = (fun x => x + 2) then False else True := by have (fun x => x + 1) ≠ (fun x => x + 2) by intro h have 1 = 2 from congrFun h 0 contradiction rw ifNeg this exact True.intro def tst (x : Nat) : Bool := if 1 < 2 then true else false
cff8740ad91ec25e018cf7f00713ef9e55cb8adb
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/ring_theory/dedekind_domain.lean
c0f2d6b3b4d6fcb45e6b8c83a1a100ff1edd370a
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
42,324
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.discrete_valuation_ring import ring_theory.fractional_ideal import ring_theory.ideal.over import ring_theory.integrally_closed import ring_theory.polynomial.rational_root import ring_theory.trace import algebra.associated /-! # Dedekind domains This file defines the notion of a Dedekind domain (or Dedekind ring), giving three equivalent definitions (TODO: and shows that they are equivalent). ## Main definitions - `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is Noetherian, integrally closed in its field of fractions and has Krull dimension at most one. `is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions. - `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that is Noetherian, and the localization at every nonzero prime ideal is a DVR. - `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain where every nonzero fractional ideal is invertible. - `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of fractions. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [integral_domain A] [field K] open_locale non_zero_divisors /-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/ def ring.dimension_le_one : Prop := ∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal open ideal ring namespace ring lemma dimension_le_one.principal_ideal_ring [is_principal_ideal_ring A] : dimension_le_one A := λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero } lemma dimension_le_one.is_integral_closure (B : Type*) [integral_domain B] [nontrivial R] [algebra R A] [algebra R B] [algebra B A] [is_scalar_tower R B A] [is_integral_closure B R A] (h : dimension_le_one R) : dimension_le_one B := λ p ne_bot prime, by exactI is_integral_closure.is_maximal_of_is_maximal_comap A p (h _ (is_integral_closure.comap_ne_bot A ne_bot) infer_instance) lemma dimension_le_one.integral_closure [nontrivial R] [algebra R A] (h : dimension_le_one R) : dimension_le_one (integral_closure R A) := h.is_integral_closure R A (integral_closure R A) end ring /-- A Dedekind domain is an integral domain that is Noetherian, integrally closed, and has Krull dimension at most one. This is definition 3.2 of [Neukirch1992]. The integral closure condition is independent of the choice of field of fractions: use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`. This is the default implementation, but there are equivalent definitions, `is_dedekind_domain_dvr` and `is_dedekind_domain_inv`. TODO: Prove that these are actually equivalent definitions. -/ class is_dedekind_domain : Prop := (is_noetherian_ring : is_noetherian_ring A) (dimension_le_one : dimension_le_one A) (is_integrally_closed : is_integrally_closed A) -- See library note [lower instance priority] attribute [instance, priority 100] is_dedekind_domain.is_noetherian_ring is_dedekind_domain.is_integrally_closed /-- An integral domain is a Dedekind domain iff and only if it is Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field. In particular, this definition does not depend on the choice of this fraction field. -/ lemma is_dedekind_domain_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] : is_dedekind_domain A ↔ is_noetherian_ring A ∧ dimension_le_one A ∧ (∀ {x : K}, is_integral A x → ∃ y, algebra_map A K y = x) := ⟨λ ⟨hr, hd, hi⟩, ⟨hr, hd, λ x, (is_integrally_closed_iff K).mp hi⟩, λ ⟨hr, hd, hi⟩, ⟨hr, hd, (is_integrally_closed_iff K).mpr @hi⟩⟩ @[priority 100] -- See library note [lower instance priority] instance is_principal_ideal_ring.is_dedekind_domain [is_principal_ideal_ring A] : is_dedekind_domain A := ⟨principal_ideal_ring.is_noetherian_ring, ring.dimension_le_one.principal_ideal_ring A, unique_factorization_monoid.is_integrally_closed⟩ /-- A Dedekind domain is an integral domain that is Noetherian, and the localization at every nonzero prime is a discrete valuation ring. This is equivalent to `is_dedekind_domain`. TODO: prove the equivalence. -/ structure is_dedekind_domain_dvr : Prop := (is_noetherian_ring : is_noetherian_ring A) (is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime → discrete_valuation_ring (localization.at_prime P)) section inverse variables {R₁ : Type*} [integral_domain R₁] [algebra R₁ K] [is_fraction_ring R₁ K] variables {I J : fractional_ideal R₁⁰ K} noncomputable instance : has_inv (fractional_ideal R₁⁰ K) := ⟨λ I, 1 / I⟩ lemma inv_eq : I⁻¹ = 1 / I := rfl lemma inv_zero' : (0 : fractional_ideal R₁⁰ K)⁻¹ = 0 := fractional_ideal.div_zero lemma inv_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : J⁻¹ = ⟨(1 : fractional_ideal R₁⁰ K) / J, fractional_ideal.fractional_div_of_nonzero h⟩ := fractional_ideal.div_nonzero _ lemma coe_inv_of_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : (↑J⁻¹ : submodule R₁ K) = is_localization.coe_submodule K ⊤ / J := by { rwa inv_nonzero _, refl, assumption } variables {K} lemma mem_inv_iff (hI : I ≠ 0) {x : K} : x ∈ I⁻¹ ↔ ∀ y ∈ I, x * y ∈ (1 : fractional_ideal R₁⁰ K) := fractional_ideal.mem_div_iff_of_nonzero hI lemma inv_anti_mono (hI : I ≠ 0) (hJ : J ≠ 0) (hIJ : I ≤ J) : J⁻¹ ≤ I⁻¹ := λ x, by { simp only [mem_inv_iff hI, mem_inv_iff hJ], exact λ h y hy, h y (hIJ hy) } lemma le_self_mul_inv {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) : I ≤ I * I⁻¹ := fractional_ideal.le_self_mul_one_div hI variables (K) lemma coe_ideal_le_self_mul_inv (I : ideal R₁) : (I : fractional_ideal R₁⁰ K) ≤ I * I⁻¹ := le_self_mul_inv fractional_ideal.coe_ideal_le_one /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := fractional_ideal.ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply fractional_ideal.mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (fractional_ideal.mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply fractional_ideal.mul_left_mono I, apply (fractional_ideal.le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact fractional_ideal.mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa ← right_inverse_eq K I J hJ⟩ lemma mul_inv_cancel_iff_is_unit {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ is_unit I := (mul_inv_cancel_iff K).trans is_unit_iff_exists_inv.symm variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K'] @[simp] lemma map_inv (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I⁻¹).map (h : K →ₐ[R₁] K') = (I.map h)⁻¹ := by rw [inv_eq, fractional_ideal.map_div, fractional_ideal.map_one, inv_eq] open submodule submodule.is_principal @[simp] lemma span_singleton_inv (x : K) : (fractional_ideal.span_singleton R₁⁰ x)⁻¹ = fractional_ideal.span_singleton _ (x⁻¹) := fractional_ideal.one_div_span_singleton x lemma mul_generator_self_inv (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw fractional_ideal.eq_span_singleton_of_principal I }, rw [fractional_ideal.span_singleton_mul_span_singleton, mul_inv_cancel, fractional_ideal.span_singleton_one], intro generator_I_eq_zero, apply h, rw [fractional_ideal.eq_span_singleton_of_principal I, generator_I_eq_zero, fractional_ideal.span_singleton_zero] end lemma invertible_of_principal (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * I⁻¹ = 1 := (fractional_ideal.mul_div_self_cancel_iff).mpr ⟨fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹, mul_generator_self_inv _ I h⟩ lemma invertible_iff_generator_nonzero (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] : I * I⁻¹ = 1 ↔ generator (I : submodule R₁ K) ≠ 0 := begin split, { intros hI hg, apply fractional_ideal.ne_zero_of_mul_eq_one _ _ hI, rw [fractional_ideal.eq_span_singleton_of_principal I, hg, fractional_ideal.span_singleton_zero] }, { intro hg, apply invertible_of_principal, rw [fractional_ideal.eq_span_singleton_of_principal I], intro hI, have := fractional_ideal.mem_span_singleton_self _ (generator (I : submodule R₁ K)), rw [hI, fractional_ideal.mem_zero_iff] at this, contradiction } end lemma is_principal_inv (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : submodule.is_principal (I⁻¹).1 := begin rw [fractional_ideal.val_eq_coe, fractional_ideal.is_principal_iff], use (generator (I : submodule R₁ K))⁻¹, have hI : I * fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹) = 1, apply mul_generator_self_inv _ I h, exact (right_inverse_eq _ I (fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹)) hI).symm end @[simp] lemma fractional_ideal.one_inv : (1⁻¹ : fractional_ideal R₁⁰ K) = 1 := fractional_ideal.div_one /-- A Dedekind domain is an integral domain such that every fractional ideal has an inverse. This is equivalent to `is_dedekind_domain`. In particular we provide a `fractional_ideal.comm_group_with_zero` instance, assuming `is_dedekind_domain A`, which implies `is_dedekind_domain_inv`. For **integral** ideals, `is_dedekind_domain`(`_inv`) implies only `ideal.comm_cancel_monoid_with_zero`. -/ def is_dedekind_domain_inv : Prop := ∀ I ≠ (⊥ : fractional_ideal A⁰ (fraction_ring A)), I * I⁻¹ = 1 open fractional_ideal variables {R A K} lemma is_dedekind_domain_inv_iff [algebra A K] [is_fraction_ring A K] : is_dedekind_domain_inv A ↔ (∀ I ≠ (⊥ : fractional_ideal A⁰ K), I * I⁻¹ = 1) := begin set h : fraction_ring A ≃ₐ[A] K := fraction_ring.alg_equiv A K, split; rintros hi I hI, { have := hi (fractional_ideal.map h.symm.to_alg_hom I) (fractional_ideal.map_ne_zero h.symm.to_alg_hom hI), convert congr_arg (fractional_ideal.map h.to_alg_hom) this; simp only [alg_equiv.to_alg_hom_eq_coe, map_symm_map, map_one, fractional_ideal.map_mul, fractional_ideal.map_div, inv_eq] }, { have := hi (fractional_ideal.map h.to_alg_hom I) (fractional_ideal.map_ne_zero h.to_alg_hom hI), convert congr_arg (fractional_ideal.map h.symm.to_alg_hom) this; simp only [alg_equiv.to_alg_hom_eq_coe, map_map_symm, map_one, fractional_ideal.map_mul, fractional_ideal.map_div, inv_eq] }, end lemma fractional_ideal.adjoin_integral_eq_one_of_is_unit [algebra A K] [is_fraction_ring A K] (x : K) (hx : is_integral A x) (hI : is_unit (adjoin_integral A⁰ x hx)) : adjoin_integral A⁰ x hx = 1 := begin set I := adjoin_integral A⁰ x hx, have mul_self : I * I = I, { apply fractional_ideal.coe_to_submodule_injective, simp }, convert congr_arg (* I⁻¹) mul_self; simp only [(mul_inv_cancel_iff_is_unit K).mpr hI, mul_assoc, mul_one], end namespace is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] (h : is_dedekind_domain_inv A) include h lemma mul_inv_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I * I⁻¹ = 1 := is_dedekind_domain_inv_iff.mp h I hI lemma inv_mul_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I⁻¹ * I = 1 := (mul_comm _ _).trans (h.mul_inv_eq_one hI) protected lemma is_unit {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : is_unit I := is_unit_of_mul_eq_one _ _ (h.mul_inv_eq_one hI) lemma is_noetherian_ring : is_noetherian_ring A := begin refine is_noetherian_ring_iff.mpr ⟨λ (I : ideal A), _⟩, by_cases hI : I = ⊥, { rw hI, apply submodule.fg_bot }, have hI : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, exact I.fg_of_is_unit (is_fraction_ring.injective A (fraction_ring A)) (h.is_unit hI) end lemma integrally_closed : is_integrally_closed A := begin -- It suffices to show that for integral `x`, -- `A[x]` (which is a fractional ideal) is in fact equal to `A`. refine ⟨λ x hx, _⟩, rw [← set.mem_range, ← algebra.mem_bot, ← subalgebra.mem_to_submodule, algebra.to_submodule_bot, ← coe_span_singleton A⁰ (1 : fraction_ring A), fractional_ideal.span_singleton_one, ← fractional_ideal.adjoin_integral_eq_one_of_is_unit x hx (h.is_unit _)], { exact mem_adjoin_integral_self A⁰ x hx }, { exact λ h, one_ne_zero (eq_zero_iff.mp h 1 (subalgebra.one_mem _)) }, end lemma dimension_le_one : dimension_le_one A := begin -- We're going to show that `P` is maximal because any (maximal) ideal `M` -- that is strictly larger would be `⊤`. rintros P P_ne hP, refine ideal.is_maximal_def.mpr ⟨hP.ne_top, λ M hM, _⟩, -- We may assume `P` and `M` (as fractional ideals) are nonzero. have P'_ne : (P : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr P_ne, have M'_ne : (M : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr (lt_of_le_of_lt bot_le hM).ne', -- In particular, we'll show `M⁻¹ * P ≤ P` suffices : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ P, { rw [eq_top_iff, ← coe_ideal_le_coe_ideal (fraction_ring A), fractional_ideal.coe_ideal_top], calc (1 : fractional_ideal A⁰ (fraction_ring A)) = _ * _ * _ : _ ... ≤ _ * _ : mul_right_mono (P⁻¹ * M : fractional_ideal A⁰ (fraction_ring A)) this ... = M : _, { rw [mul_assoc, ← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul, h.inv_mul_eq_one M'_ne] }, { rw [← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul] }, { apply_instance } }, -- Suppose we have `x ∈ M⁻¹ * P`, then in fact `x = algebra_map _ _ y` for some `y`. intros x hx, have le_one : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ 1, { rw [← h.inv_mul_eq_one M'_ne], exact fractional_ideal.mul_left_mono _ ((coe_ideal_le_coe_ideal (fraction_ring A)).mpr hM.le) }, obtain ⟨y, hy, rfl⟩ := (mem_coe_ideal _).mp (le_one hx), -- Since `M` is strictly greater than `P`, let `z ∈ M \ P`. obtain ⟨z, hzM, hzp⟩ := set_like.exists_of_lt hM, -- We have `z * y ∈ M * (M⁻¹ * P) = P`. have zy_mem := fractional_ideal.mul_mem_mul (mem_coe_ideal_of_mem A⁰ hzM) hx, rw [← ring_hom.map_mul, ← mul_assoc, h.mul_inv_eq_one M'_ne, one_mul] at zy_mem, obtain ⟨zy, hzy, zy_eq⟩ := (mem_coe_ideal A⁰).mp zy_mem, rw is_fraction_ring.injective A (fraction_ring A) zy_eq at hzy, -- But `P` is a prime ideal, so `z ∉ P` implies `y ∈ P`, as desired. exact mem_coe_ideal_of_mem A⁰ (or.resolve_left (hP.mem_or_mem hzy) hzp) end /-- Showing one side of the equivalence between the definitions `is_dedekind_domain_inv` and `is_dedekind_domain` of Dedekind domains. -/ theorem is_dedekind_domain : is_dedekind_domain A := ⟨h.is_noetherian_ring, h.dimension_le_one, h.integrally_closed⟩ end is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] /-- Specialization of `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` to Dedekind domains: Let `I : ideal A` be a nonzero ideal, where `A` is a Dedekind domain that is not a field. Then `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` states we can find a product of prime ideals that is contained within `I`. This lemma extends that result by making the product minimal: let `M` be a maximal ideal that contains `I`, then the product including `M` is contained within `I` and the product excluding `M` is not contained within `I`. -/ lemma exists_multiset_prod_cons_le_and_prod_not_le [is_dedekind_domain A] (hNF : ¬ is_field A) {I M : ideal A} (hI0 : I ≠ ⊥) (hIM : I ≤ M) [hM : M.is_maximal] : ∃ (Z : multiset (prime_spectrum A)), (M ::ₘ (Z.map prime_spectrum.as_ideal)).prod ≤ I ∧ ¬ (multiset.prod (Z.map prime_spectrum.as_ideal) ≤ I) := begin -- Let `Z` be a minimal set of prime ideals such that their product is contained in `J`. obtain ⟨Z₀, hZ₀⟩ := exists_prime_spectrum_prod_le_and_ne_bot_of_domain hNF hI0, obtain ⟨Z, ⟨hZI, hprodZ⟩, h_eraseZ⟩ := multiset.well_founded_lt.has_min (λ Z, (Z.map prime_spectrum.as_ideal).prod ≤ I ∧ (Z.map prime_spectrum.as_ideal).prod ≠ ⊥) ⟨Z₀, hZ₀⟩, have hZM : multiset.prod (Z.map prime_spectrum.as_ideal) ≤ M := le_trans hZI hIM, have hZ0 : Z ≠ 0, { rintro rfl, simpa [hM.ne_top] using hZM }, obtain ⟨_, hPZ', hPM⟩ := (hM.is_prime.multiset_prod_le (mt multiset.map_eq_zero.mp hZ0)).mp hZM, -- Then in fact there is a `P ∈ Z` with `P ≤ M`. obtain ⟨P, hPZ, rfl⟩ := multiset.mem_map.mp hPZ', letI := classical.dec_eq (ideal A), have := multiset.map_erase prime_spectrum.as_ideal subtype.coe_injective P Z, obtain ⟨hP0, hZP0⟩ : P.as_ideal ≠ ⊥ ∧ ((Z.erase P).map prime_spectrum.as_ideal).prod ≠ ⊥, { rwa [ne.def, ← multiset.cons_erase hPZ', multiset.prod_cons, ideal.mul_eq_bot, not_or_distrib, ← this] at hprodZ }, -- By maximality of `P` and `M`, we have that `P ≤ M` implies `P = M`. have hPM' := (is_dedekind_domain.dimension_le_one _ hP0 P.is_prime).eq_of_le hM.ne_top hPM, tactic.unfreeze_local_instances, subst hPM', -- By minimality of `Z`, erasing `P` from `Z` is exactly what we need. refine ⟨Z.erase P, _, _⟩, { convert hZI, rw [this, multiset.cons_erase hPZ'] }, { refine λ h, h_eraseZ (Z.erase P) ⟨h, _⟩ (multiset.erase_lt.mpr hPZ), exact hZP0 } end namespace fractional_ideal lemma exists_not_mem_one_of_ne_bot [is_dedekind_domain A] (hNF : ¬ is_field A) {I : ideal A} (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) : ∃ x : K, x ∈ (I⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K) := begin -- WLOG, let `I` be maximal. suffices : ∀ {M : ideal A} (hM : M.is_maximal), ∃ x : K, x ∈ (M⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K), { obtain ⟨M, hM, hIM⟩ : ∃ (M : ideal A), is_maximal M ∧ I ≤ M := ideal.exists_le_maximal I hI1, resetI, have hM0 := (M.bot_lt_of_maximal hNF).ne', obtain ⟨x, hxM, hx1⟩ := this hM, refine ⟨x, inv_anti_mono _ _ ((coe_ideal_le_coe_ideal _).mpr hIM) hxM, hx1⟩; apply fractional_ideal.coe_ideal_ne_zero; assumption }, -- Let `a` be a nonzero element of `M` and `J` the ideal generated by `a`. intros M hM, resetI, obtain ⟨⟨a, haM⟩, ha0⟩ := submodule.nonzero_mem_of_bot_lt (M.bot_lt_of_maximal hNF), replace ha0 : a ≠ 0 := subtype.coe_injective.ne ha0, let J : ideal A := ideal.span {a}, have hJ0 : J ≠ ⊥ := mt ideal.span_singleton_eq_bot.mp ha0, have hJM : J ≤ M := ideal.span_le.mpr (set.singleton_subset_iff.mpr haM), have hM0 : ⊥ < M := M.bot_lt_of_maximal hNF, -- Then we can find a product of prime (hence maximal) ideals contained in `J`, -- such that removing element `M` from the product is not contained in `J`. obtain ⟨Z, hle, hnle⟩ := exists_multiset_prod_cons_le_and_prod_not_le hNF hJ0 hJM, -- Choose an element `b` of the product that is not in `J`. obtain ⟨b, hbZ, hbJ⟩ := set_like.not_le_iff_exists.mp hnle, have hnz_fa : algebra_map A K a ≠ 0 := mt ((ring_hom.injective_iff _).mp (is_fraction_ring.injective A K) a) ha0, have hb0 : algebra_map A K b ≠ 0 := mt ((ring_hom.injective_iff _).mp (is_fraction_ring.injective A K) b) (λ h, hbJ $ h.symm ▸ J.zero_mem), -- Then `b a⁻¹ : K` is in `M⁻¹` but not in `1`. refine ⟨algebra_map A K b * (algebra_map A K a)⁻¹, (mem_inv_iff _).mpr _, _⟩, { exact (fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl _)).mpr hM0.ne' }, { rintro y₀ hy₀, obtain ⟨y, h_Iy, rfl⟩ := (fractional_ideal.mem_coe_ideal _).mp hy₀, rw [mul_comm, ← mul_assoc, ← ring_hom.map_mul], have h_yb : y * b ∈ J, { apply hle, rw multiset.prod_cons, exact submodule.smul_mem_smul h_Iy hbZ }, rw ideal.mem_span_singleton' at h_yb, rcases h_yb with ⟨c, hc⟩, rw [← hc, ring_hom.map_mul, mul_assoc, mul_inv_cancel hnz_fa, mul_one], apply fractional_ideal.coe_mem_one }, { refine mt (fractional_ideal.mem_one_iff _).mp _, rintros ⟨x', h₂_abs⟩, rw [← div_eq_mul_inv, eq_div_iff_mul_eq hnz_fa, ← ring_hom.map_mul] at h₂_abs, have := ideal.mem_span_singleton'.mpr ⟨x', is_fraction_ring.injective A K h₂_abs⟩, contradiction }, end lemma one_mem_inv_coe_ideal {I : ideal A} (hI : I ≠ ⊥) : (1 : K) ∈ (I : fractional_ideal A⁰ K)⁻¹ := begin rw mem_inv_iff (fractional_ideal.coe_ideal_ne_zero hI), intros y hy, rw one_mul, exact coe_ideal_le_one hy, assumption end lemma mul_inv_cancel_of_le_one [h : is_dedekind_domain A] {I : ideal A} (hI0 : I ≠ ⊥) (hI : ((I * I⁻¹)⁻¹ : fractional_ideal A⁰ K) ≤ 1) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- Handle a few trivial cases. by_cases hI1 : I = ⊤, { rw [hI1, coe_ideal_top, one_mul, fractional_ideal.one_inv] }, by_cases hNF : is_field A, { letI := hNF.to_field A, rcases hI1 (I.eq_bot_or_top.resolve_left hI0) }, -- We'll show a contradiction with `exists_not_mem_one_of_ne_bot`: -- `J⁻¹ = (I * I⁻¹)⁻¹` cannot have an element `x ∉ 1`, so it must equal `1`. by_contradiction h_abs, obtain ⟨J, hJ⟩ : ∃ (J : ideal A), (J : fractional_ideal A⁰ K) = I * I⁻¹ := le_one_iff_exists_coe_ideal.mp mul_one_div_le_one, by_cases hJ0 : J = ⊥, { subst hJ0, apply hI0, rw [eq_bot_iff, ← coe_ideal_le_coe_ideal K, hJ], exact coe_ideal_le_self_mul_inv K I, apply_instance }, have hJ1 : J ≠ ⊤, { rintro rfl, rw [← hJ, coe_ideal_top] at h_abs, exact h_abs rfl }, obtain ⟨x, hx, hx1⟩ : ∃ (x : K), x ∈ (J : fractional_ideal A⁰ K)⁻¹ ∧ x ∉ (1 : fractional_ideal A⁰ K) := exists_not_mem_one_of_ne_bot hNF hJ0 hJ1, rw hJ at hx, exact hx1 (hI hx) end /-- Nonzero integral ideals in a Dedekind domain are invertible. We will use this to show that nonzero fractional ideals are invertible, and finally conclude that fractional ideals in a Dedekind domain form a group with zero. -/ lemma coe_ideal_mul_inv [h : is_dedekind_domain A] (I : ideal A) (hI0 : I ≠ ⊥) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- We'll show `1 ≤ J⁻¹ = (I * I⁻¹)⁻¹ ≤ 1`. apply mul_inv_cancel_of_le_one hI0, by_cases hJ0 : (I * I⁻¹ : fractional_ideal A⁰ K) = 0, { rw [hJ0, inv_zero'], exact fractional_ideal.zero_le _ }, intros x hx, -- In particular, we'll show all `x ∈ J⁻¹` are integral. suffices : x ∈ integral_closure A K, { rwa [is_integrally_closed.integral_closure_eq_bot, algebra.mem_bot, set.mem_range, ← fractional_ideal.mem_one_iff] at this; assumption }, -- For that, we'll find a subalgebra that is f.g. as a module and contains `x`. -- `A` is a noetherian ring, so we just need to find a subalgebra between `{x}` and `I⁻¹`. rw mem_integral_closure_iff_mem_fg, have x_mul_mem : ∀ b ∈ (I⁻¹ : fractional_ideal A⁰ K), x * b ∈ (I⁻¹ : fractional_ideal A⁰ K), { intros b hb, rw mem_inv_iff at ⊢ hx, swap, { exact fractional_ideal.coe_ideal_ne_zero hI0 }, swap, { exact hJ0 }, simp only [mul_assoc, mul_comm b] at ⊢ hx, intros y hy, exact hx _ (fractional_ideal.mul_mem_mul hy hb) }, -- It turns out the subalgebra consisting of all `p(x)` for `p : polynomial A` works. refine ⟨alg_hom.range (polynomial.aeval x : polynomial A →ₐ[A] K), is_noetherian_submodule.mp (fractional_ideal.is_noetherian I⁻¹) _ (λ y hy, _), ⟨polynomial.X, polynomial.aeval_X x⟩⟩, obtain ⟨p, rfl⟩ := (alg_hom.mem_range _).mp hy, rw polynomial.aeval_eq_sum_range, refine submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ _), clear hi, induction i with i ih, { rw pow_zero, exact one_mem_inv_coe_ideal hI0 }, { show x ^ i.succ ∈ (I⁻¹ : fractional_ideal A⁰ K), rw pow_succ, exact x_mul_mem _ ih }, end /-- Nonzero fractional ideals in a Dedekind domain are units. This is also available as `_root_.mul_inv_cancel`, using the `comm_group_with_zero` instance defined below. -/ protected theorem mul_inv_cancel [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hne : I ≠ 0) : I * I⁻¹ = 1 := begin obtain ⟨a, J, ha, hJ⟩ : ∃ (a : A) (aI : ideal A), a ≠ 0 ∧ I = span_singleton A⁰ (algebra_map _ _ a)⁻¹ * aI := exists_eq_span_singleton_mul I, suffices h₂ : I * (span_singleton A⁰ (algebra_map _ _ a) * J⁻¹) = 1, { rw mul_inv_cancel_iff, exact ⟨span_singleton A⁰ (algebra_map _ _ a) * J⁻¹, h₂⟩ }, subst hJ, rw [mul_assoc, mul_left_comm (J : fractional_ideal A⁰ K), coe_ideal_mul_inv, mul_one, fractional_ideal.span_singleton_mul_span_singleton, inv_mul_cancel, fractional_ideal.span_singleton_one], { exact mt ((algebra_map A K).injective_iff.mp (is_fraction_ring.injective A K) _) ha }, { exact fractional_ideal.coe_ideal_ne_zero_iff.mp (right_ne_zero_of_mul hne) } end end fractional_ideal /-- `is_dedekind_domain` and `is_dedekind_domain_inv` are equivalent ways to express that an integral domain is a Dedekind domain. -/ theorem is_dedekind_domain_iff_is_dedekind_domain_inv : is_dedekind_domain A ↔ is_dedekind_domain_inv A := ⟨λ h I hI, by exactI fractional_ideal.mul_inv_cancel hI, λ h, h.is_dedekind_domain⟩ end inverse section is_dedekind_domain variables {R A} [is_dedekind_domain A] [algebra A K] [is_fraction_ring A K] open fractional_ideal noncomputable instance fractional_ideal.comm_group_with_zero : comm_group_with_zero (fractional_ideal A⁰ K) := { inv := λ I, I⁻¹, inv_zero := inv_zero' _, exists_pair_ne := ⟨0, 1, (coe_to_fractional_ideal_injective (le_refl _)).ne (by simpa using @zero_ne_one (ideal A) _ _)⟩, mul_inv_cancel := λ I, fractional_ideal.mul_inv_cancel, .. fractional_ideal.comm_semiring } noncomputable instance ideal.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero (ideal A) := function.injective.comm_cancel_monoid_with_zero (coe_ideal_hom A⁰ (fraction_ring A)) coe_ideal_injective (ring_hom.map_zero _) (ring_hom.map_one _) (ring_hom.map_mul _) /-- For ideals in a Dedekind domain, to divide is to contain. -/ lemma ideal.dvd_iff_le {I J : ideal A} : (I ∣ J) ↔ J ≤ I := ⟨ideal.le_of_dvd, λ h, begin by_cases hI : I = ⊥, { have hJ : J = ⊥, { rwa [hI, ← eq_bot_iff] at h }, rw [hI, hJ] }, have hI' : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, have : (I : fractional_ideal A⁰ (fraction_ring A))⁻¹ * J ≤ 1 := le_trans (fractional_ideal.mul_left_mono (↑I)⁻¹ ((coe_ideal_le_coe_ideal _).mpr h)) (le_of_eq (inv_mul_cancel hI')), obtain ⟨H, hH⟩ := fractional_ideal.le_one_iff_exists_coe_ideal.mp this, use H, refine coe_to_fractional_ideal_injective (le_refl (non_zero_divisors A)) (show (J : fractional_ideal A⁰ (fraction_ring A)) = _, from _), rw [fractional_ideal.coe_ideal_mul, hH, ← mul_assoc, mul_inv_cancel hI', one_mul] end⟩ lemma ideal.dvd_not_unit_iff_lt {I J : ideal A} : dvd_not_unit I J ↔ J < I := ⟨λ ⟨hI, H, hunit, hmul⟩, lt_of_le_of_ne (ideal.dvd_iff_le.mp ⟨H, hmul⟩) (mt (λ h, have H = 1, from mul_left_cancel' hI (by rw [← hmul, h, mul_one]), show is_unit H, from this.symm ▸ is_unit_one) hunit), λ h, dvd_not_unit_of_dvd_of_not_dvd (ideal.dvd_iff_le.mpr (le_of_lt h)) (mt ideal.dvd_iff_le.mp (not_le_of_lt h))⟩ instance : wf_dvd_monoid (ideal A) := { well_founded_dvd_not_unit := have well_founded ((>) : ideal A → ideal A → Prop) := is_noetherian_iff_well_founded.mp (is_noetherian_ring_iff.mp is_dedekind_domain.is_noetherian_ring), by { convert this, ext, rw ideal.dvd_not_unit_iff_lt } } instance ideal.unique_factorization_monoid : unique_factorization_monoid (ideal A) := { irreducible_iff_prime := λ P, ⟨λ hirr, ⟨hirr.ne_zero, hirr.not_unit, λ I J, begin have : P.is_maximal, { use mt ideal.is_unit_iff.mpr hirr.not_unit, intros J hJ, obtain ⟨J_ne, H, hunit, P_eq⟩ := ideal.dvd_not_unit_iff_lt.mpr hJ, exact ideal.is_unit_iff.mp ((hirr.is_unit_or_is_unit P_eq).resolve_right hunit) }, simp only [ideal.dvd_iff_le, has_le.le, preorder.le, partial_order.le], contrapose!, rintros ⟨⟨x, x_mem, x_not_mem⟩, ⟨y, y_mem, y_not_mem⟩⟩, exact ⟨x * y, ideal.mul_mem_mul x_mem y_mem, mt this.is_prime.mem_or_mem (not_or x_not_mem y_not_mem)⟩, end⟩, prime.irreducible⟩, .. ideal.wf_dvd_monoid } noncomputable instance ideal.normalization_monoid : normalization_monoid (ideal A) := normalization_monoid_of_unique_units @[simp] lemma ideal.dvd_span_singleton {I : ideal A} {x : A} : I ∣ ideal.span {x} ↔ x ∈ I := ideal.dvd_iff_le.trans (ideal.span_le.trans set.singleton_subset_iff) lemma ideal.is_prime_of_prime {P : ideal A} (h : prime P) : is_prime P := begin refine ⟨_, λ x y hxy, _⟩, { unfreezingI { rintro rfl }, rw ← ideal.one_eq_top at h, exact h.not_unit is_unit_one }, { simp only [← ideal.dvd_span_singleton, ← ideal.span_singleton_mul_span_singleton] at ⊢ hxy, exact h.dvd_or_dvd hxy } end theorem ideal.prime_of_is_prime {P : ideal A} (hP : P ≠ ⊥) (h : is_prime P) : prime P := begin refine ⟨hP, mt ideal.is_unit_iff.mp h.ne_top, λ I J hIJ, _⟩, simpa only [ideal.dvd_iff_le] using (h.mul_le.mp (ideal.le_of_dvd hIJ)), end /-- In a Dedekind domain, the (nonzero) prime elements of the monoid with zero `ideal A` are exactly the prime ideals. -/ theorem ideal.prime_iff_is_prime {P : ideal A} (hP : P ≠ ⊥) : prime P ↔ is_prime P := ⟨ideal.is_prime_of_prime, ideal.prime_of_is_prime hP⟩ end is_dedekind_domain section is_integral_closure /-! ### `is_integral_closure` section We show that an integral closure of a Dedekind domain in a finite separable field extension is again a Dedekind domain. This implies the ring of integers of a number field is a Dedekind domain. -/ open algebra open_locale big_operators variables {A K} [algebra A K] [is_fraction_ring A K] variables {L : Type*} [field L] (C : Type*) [integral_domain C] variables [algebra K L] [finite_dimensional K L] [algebra A L] [is_scalar_tower A K L] variables [algebra C L] [is_integral_closure C A L] [algebra A C] [is_scalar_tower A C L] lemma is_integral_closure.range_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : ((algebra.linear_map C L).restrict_scalars A).range ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin let db := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, rintros _ ⟨x, rfl⟩, simp only [linear_map.coe_restrict_scalars_eq_coe, algebra.linear_map_apply], have hx : is_integral A (algebra_map C L x) := (is_integral_closure.is_integral A L x).algebra_map, suffices : ∃ (c : ι → A), algebra_map C L x = ∑ i, c i • db i, { obtain ⟨c, x_eq⟩ := this, rw x_eq, refine submodule.sum_mem _ (λ i _, submodule.smul_mem _ _ (submodule.subset_span _)), rw set.mem_range, exact ⟨i, rfl⟩ }, suffices : ∃ (c : ι → K), ((∀ i, is_integral A (c i)) ∧ algebra_map C L x = ∑ i, c i • db i), { obtain ⟨c, hc, hx⟩ := this, have hc' : ∀ i, is_localization.is_integer A (c i) := λ i, is_integrally_closed.is_integral_iff.mp (hc i), use λ i, classical.some (hc' i), refine hx.trans (finset.sum_congr rfl (λ i _, _)), conv_lhs { rw [← classical.some_spec (hc' i)] }, rw [← is_scalar_tower.algebra_map_smul K (classical.some (hc' i)) (db i)] }, refine ⟨λ i, db.repr (algebra_map C L x) i, (λ i, _), (db.sum_repr _).symm⟩, rw bilin_form.dual_basis_repr_apply, exact is_integral_trace (is_integral_mul hx (hb_int i)) end lemma integral_closure_le_span_dual_basis [is_separable K L] {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L) (hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] : (integral_closure A L).to_submodule ≤ submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) := begin refine le_trans _ (is_integral_closure.range_le_span_dual_basis (integral_closure A L) b hb_int), intros x hx, exact ⟨⟨x, hx⟩, rfl⟩ end variables (A) (K) include K /-- Send a set of `x`'es in a finite extension `L` of the fraction field of `R` to `(y : R) • x ∈ integral_closure R L`. -/ lemma exists_integral_multiples (s : finset L) : ∃ (y ≠ (0 : A)), ∀ x ∈ s, is_integral A (y • x) := begin haveI := classical.dec_eq L, refine s.induction _ _, { use [1, one_ne_zero], rintros x ⟨⟩ }, { rintros x s hx ⟨y, hy, hs⟩, obtain ⟨x', y', hy', hx'⟩ := exists_integral_multiple ((is_fraction_ring.is_algebraic_iff A K).mpr (algebra.is_algebraic_of_finite x)) ((algebra_map A L).injective_iff.mp _), refine ⟨y * y', mul_ne_zero hy hy', λ x'' hx'', _⟩, rcases finset.mem_insert.mp hx'' with (rfl | hx''), { rw [mul_smul, algebra.smul_def, algebra.smul_def, mul_comm _ x'', hx'], exact is_integral_mul is_integral_algebra_map x'.2 }, { rw [mul_comm, mul_smul, algebra.smul_def], exact is_integral_mul is_integral_algebra_map (hs _ hx'') }, { rw is_scalar_tower.algebra_map_eq A K L, apply (algebra_map K L).injective.comp, exact is_fraction_ring.injective _ _ } } end variables (L) /-- If `L` is a finite extension of `K = Frac(A)`, then `L` has a basis over `A` consisting of integral elements. -/ lemma finite_dimensional.exists_is_basis_integral : ∃ (s : finset L) (b : basis s K L), (∀ x, is_integral A (b x)) := begin letI := classical.dec_eq L, let s' := is_noetherian.finset_basis_index K L, let bs' := is_noetherian.finset_basis K L, obtain ⟨y, hy, his'⟩ := exists_integral_multiples A K (finset.univ.image bs'), have hy' : algebra_map A L y ≠ 0, { refine mt ((algebra_map A L).injective_iff.mp _ _) hy, rw is_scalar_tower.algebra_map_eq A K L, exact (algebra_map K L).injective.comp (is_fraction_ring.injective A K) }, refine ⟨s', bs'.map { to_fun := λ x, algebra_map A L y * x, inv_fun := λ x, (algebra_map A L y)⁻¹ * x, left_inv := _, right_inv := _, .. algebra.lmul _ _ (algebra_map A L y) }, _⟩, { intros x, simp only [inv_mul_cancel_left' hy'] }, { intros x, simp only [mul_inv_cancel_left' hy'] }, { rintros ⟨x', hx'⟩, simp only [algebra.smul_def, finset.mem_image, exists_prop, finset.mem_univ, true_and] at his', simp only [basis.map_apply, linear_equiv.coe_mk], exact his' _ ⟨_, rfl⟩ } end variables (A K L) [is_separable K L] include L /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure `C` of `A` in `L` is Noetherian. -/ lemma is_integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring C := begin haveI := classical.dec_eq L, obtain ⟨s, b, hb_int⟩ := finite_dimensional.exists_is_basis_integral A K L, rw is_noetherian_ring_iff, let b' := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b, letI := is_noetherian_span_of_finite A (set.finite_range b'), let f : C →ₗ[A] submodule.span A (set.range b') := (submodule.of_le (is_integral_closure.range_le_span_dual_basis C b hb_int)).comp ((algebra.linear_map C L).restrict_scalars A).range_restrict, refine is_noetherian_of_tower A (is_noetherian_of_injective f _), rw [linear_map.ker_comp, submodule.ker_of_le, submodule.comap_bot, linear_map.ker_cod_restrict], exact linear_map.ker_eq_bot_of_injective (is_integral_closure.algebra_map_injective C A L) end variables {A K} /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is integrally closed and Noetherian, the integral closure of `A` in `L` is Noetherian. -/ lemma integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] : is_noetherian_ring (integral_closure A L) := is_integral_closure.is_noetherian_ring A K L (integral_closure A L) variables (A K) /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure `C` of `A` in `L` is a Dedekind domain. Can't be an instance since `A`, `K` or `L` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A` and `C := integral_closure A L`. -/ lemma is_integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain C := begin haveI : is_fraction_ring C L := is_integral_closure.is_fraction_ring_of_finite_extension A K L C, exact ⟨is_integral_closure.is_noetherian_ring A K L C, h.dimension_le_one.is_integral_closure _ L _, (is_integrally_closed_iff L).mpr (λ x hx, ⟨is_integral_closure.mk' C x (is_integral_trans (is_integral_closure.is_integral_algebra A L) _ hx), is_integral_closure.algebra_map_mk' _ _ _⟩)⟩ end /- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. Can't be an instance since `K` can't be inferred. See also the instance `integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`. -/ lemma integral_closure.is_dedekind_domain [h : is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := is_integral_closure.is_dedekind_domain A K L (integral_closure A L) omit K variables [algebra (fraction_ring A) L] [is_scalar_tower A (fraction_ring A) L] variables [finite_dimensional (fraction_ring A) L] [is_separable (fraction_ring A) L] /- If `L` is a finite separable extension of `Frac(A)`, where `A` is a Dedekind domain, the integral closure of `A` in `L` is a Dedekind domain. See also the lemma `integral_closure.is_dedekind_domain` where you can choose the field of fractions yourself. -/ instance integral_closure.is_dedekind_domain_fraction_ring [is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) := integral_closure.is_dedekind_domain A (fraction_ring A) L end is_integral_closure section is_dedekind_domain variables {T : Type*} [integral_domain T] [is_dedekind_domain T] (I J : ideal T) open_locale classical open multiset unique_factorization_monoid ideal lemma prod_factors_eq_self {I : ideal T} (hI : I ≠ ⊥) : (factors I).prod = I := associated_iff_eq.1 (factors_prod hI) lemma factors_prod_factors_eq_factors {α : multiset (ideal T)} (h : ∀ p ∈ α, prime p) : factors α.prod = α := by { simp_rw [← multiset.rel_eq, ← associated_eq_eq], exact prime_factors_unique (prime_of_factor) h (factors_prod (α.prod_ne_zero_of_prime h)) } lemma count_le_of_ideal_ge {I J : ideal T} (h : I ≤ J) (hI : I ≠ ⊥) (K : ideal T) : count K (factors J) ≤ count K (factors I) := le_iff_count.1 ((dvd_iff_factors_le_factors (ne_bot_of_le_ne_bot hI h) hI).1 (dvd_iff_le.2 h)) _ lemma sup_eq_prod_inf_factors (hI : I ≠ ⊥) (hJ : J ≠ ⊥) : I ⊔ J = (factors I ∩ factors J).prod := begin have H : factors (factors I ∩ factors J).prod = factors I ∩ factors J, { apply factors_prod_factors_eq_factors, intros p hp, rw mem_inter at hp, exact prime_of_factor p hp.left }, have := (multiset.prod_ne_zero_of_prime (factors I ∩ factors J) (λ _ h, prime_of_factor _ (multiset.mem_inter.1 h).1)), apply le_antisymm, { rw [sup_le_iff, ← dvd_iff_le, ← dvd_iff_le], split, { rw [dvd_iff_factors_le_factors this hI, H], exact inf_le_left }, { rw [dvd_iff_factors_le_factors this hJ, H], exact inf_le_right } }, { rw [← dvd_iff_le, dvd_iff_factors_le_factors, factors_prod_factors_eq_factors, le_iff_count], { intro a, rw multiset.count_inter, exact le_min (count_le_of_ideal_ge le_sup_left hI a) (count_le_of_ideal_ge le_sup_right hJ a) }, { intros p hp, rw mem_inter at hp, exact prime_of_factor p hp.left }, { exact ne_bot_of_le_ne_bot hI le_sup_left }, { exact this } }, end end is_dedekind_domain
c81dd106cb78eb9d14dfc2e90f34d75f96d0ebff
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/setoid/basic.lean
329a64a77dd3875025b6776a26907a9903a235ec
[ "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
16,333
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen -/ import order.galois_connection /-! # Equivalence relations This file defines the complete lattice of equivalence relations on a type, results about the inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism theorems for quotients of arbitrary types. ## Implementation notes The function `rel` and lemmas ending in ' make it easier to talk about different equivalence relations on the same type. The complete lattice instance for equivalence relations could have been defined by lifting the Galois insertion of equivalence relations on α into binary relations on α, and then using `complete_lattice.copy` to define a complete lattice instance with more appropriate definitional equalities (a similar example is `filter.complete_lattice` in `order/filter/basic.lean`). This does not save space, however, and is less clear. Partitions are not defined as a separate structure here; users are encouraged to reason about them using the existing `setoid` and its infrastructure. ## Tags setoid, equivalence, iseqv, relation, equivalence relation -/ variables {α : Type*} {β : Type*} /-- A version of `setoid.r` that takes the equivalence relation as an explicit argument. -/ def setoid.rel (r : setoid α) : α → α → Prop := @setoid.r _ r /-- A version of `quotient.eq'` compatible with `setoid.rel`, to make rewriting possible. -/ lemma quotient.eq_rel {r : setoid α} {x y} : ⟦x⟧ = ⟦y⟧ ↔ r.rel x y := quotient.eq' namespace setoid @[ext] lemma ext' {r s : setoid α} (H : ∀ a b, r.rel a b ↔ s.rel a b) : r = s := ext H lemma ext_iff {r s : setoid α} : r = s ↔ ∀ a b, r.rel a b ↔ s.rel a b := ⟨λ h a b, h ▸ iff.rfl, ext'⟩ /-- Two equivalence relations are equal iff their underlying binary operations are equal. -/ theorem eq_iff_rel_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.rel = r₂.rel := ⟨λ h, h ▸ rfl, λ h, setoid.ext' $ λ x y, h ▸ iff.rfl⟩ /-- Defining `≤` for equivalence relations. -/ instance : has_le (setoid α) := ⟨λ r s, ∀ ⦃x y⦄, r.rel x y → s.rel x y⟩ theorem le_def {r s : setoid α} : r ≤ s ↔ ∀ {x y}, r.rel x y → s.rel x y := iff.rfl @[refl] lemma refl' (r : setoid α) (x) : r.rel x x := r.2.1 x @[symm] lemma symm' (r : setoid α) : ∀ {x y}, r.rel x y → r.rel y x := λ _ _ h, r.2.2.1 h @[trans] lemma trans' (r : setoid α) : ∀ {x y z}, r.rel x y → r.rel y z → r.rel x z := λ _ _ _ hx, r.2.2.2 hx /-- The kernel of a function is an equivalence relation. -/ def ker (f : α → β) : setoid α := ⟨λ x y, f x = f y, ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h, h.trans⟩⟩ /-- The kernel of the quotient map induced by an equivalence relation r equals r. -/ @[simp] lemma ker_mk_eq (r : setoid α) : ker (@quotient.mk _ r) = r := ext' $ λ x y, quotient.eq lemma ker_def {f : α → β} {x y : α} : (ker f).rel x y ↔ f x = f y := iff.rfl /-- Given types `α`, `β`, the product of two equivalence relations `r` on `α` and `s` on `β`: `(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁` by `r` and `x₂` is related to `y₂` by `s`. -/ protected def prod (r : setoid α) (s : setoid β) : setoid (α × β) := { r := λ x y, r.rel x.1 y.1 ∧ s.rel x.2 y.2, iseqv := ⟨λ x, ⟨r.refl' x.1, s.refl' x.2⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩ } /-- The infimum of two equivalence relations. -/ instance : has_inf (setoid α) := ⟨λ r s, ⟨λ x y, r.rel x y ∧ s.rel x y, ⟨λ x, ⟨r.refl' x, s.refl' x⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩ /-- The infimum of 2 equivalence relations r and s is the same relation as the infimum of the underlying binary operations. -/ lemma inf_def {r s : setoid α} : (r ⊓ s).rel = r.rel ⊓ s.rel := rfl theorem inf_iff_and {r s : setoid α} {x y} : (r ⊓ s).rel x y ↔ r.rel x y ∧ s.rel x y := iff.rfl /-- The infimum of a set of equivalence relations. -/ instance : has_Inf (setoid α) := ⟨λ S, ⟨λ x y, ∀ r ∈ S, rel r x y, ⟨λ x r hr, r.refl' x, λ _ _ h r hr, r.symm' $ h r hr, λ _ _ _ h1 h2 r hr, r.trans' (h1 r hr) $ h2 r hr⟩⟩⟩ /-- The underlying binary operation of the infimum of a set of equivalence relations is the infimum of the set's image under the map to the underlying binary operation. -/ theorem Inf_def {s : set (setoid α)} : (Inf s).rel = Inf (rel '' s) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } instance : partial_order (setoid α) := { le := (≤), lt := λ r s, r ≤ s ∧ ¬s ≤ r, le_refl := λ _ _ _, id, le_trans := λ _ _ _ hr hs _ _ h, hs $ hr h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ r s h1 h2, setoid.ext' $ λ x y, ⟨λ h, h1 h, λ h, h2 h⟩ } /-- The complete lattice of equivalence relations on a type, with bottom element `=` and top element the trivial equivalence relation. -/ instance complete_lattice : complete_lattice (setoid α) := { inf := has_inf.inf, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ h1 h2 _ _ h, ⟨h1 h, h2 h⟩, top := ⟨λ _ _, true, ⟨λ _, trivial, λ _ _ h, h, λ _ _ _ h1 h2, h1⟩⟩, le_top := λ _ _ _ _, trivial, bot := ⟨(=), ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩⟩, bot_le := λ r x y h, h ▸ r.2.1 x, .. complete_lattice_of_Inf (setoid α) $ assume s, ⟨λ r hr x y h, h _ hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The inductively defined equivalence closure of a binary relation r is the infimum of the set of all equivalence relations containing r. -/ theorem eqv_gen_eq (r : α → α → Prop) : eqv_gen.setoid r = Inf {s : setoid α | ∀ ⦃x y⦄, r x y → s.rel x y} := le_antisymm (λ _ _ H, eqv_gen.rec (λ _ _ h _ hs, hs h) (refl' _) (λ _ _ _, symm' _) (λ _ _ _ _ _, trans' _) H) (Inf_le $ λ _ _ h, eqv_gen.rel _ _ h) /-- The supremum of two equivalence relations r and s is the equivalence closure of the binary relation `x is related to y by r or s`. -/ lemma sup_eq_eqv_gen (r s : setoid α) : r ⊔ s = eqv_gen.setoid (λ x y, r.rel x y ∨ s.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of 2 equivalence relations r and s is the equivalence closure of the supremum of the underlying binary operations. -/ lemma sup_def {r s : setoid α} : r ⊔ s = eqv_gen.setoid (r.rel ⊔ s.rel) := by rw sup_eq_eqv_gen; refl /-- The supremum of a set S of equivalence relations is the equivalence closure of the binary relation `there exists r ∈ S relating x and y`. -/ lemma Sup_eq_eqv_gen (S : set (setoid α)) : Sup S = eqv_gen.setoid (λ x y, ∃ r : setoid α, r ∈ S ∧ r.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [upper_bounds, le_def, and_imp, exists_imp_distrib], ext, exact ⟨λ H x y r hr, H hr, λ H r hr x y, H r hr⟩ end /-- The supremum of a set of equivalence relations is the equivalence closure of the supremum of the set's image under the map to the underlying binary operation. -/ lemma Sup_def {s : set (setoid α)} : Sup s = eqv_gen.setoid (Sup (rel '' s)) := begin rw [Sup_eq_eqv_gen, Sup_image], congr' with x y, simp only [supr_apply, supr_Prop_eq, exists_prop] end /-- The equivalence closure of an equivalence relation r is r. -/ @[simp] lemma eqv_gen_of_setoid (r : setoid α) : eqv_gen.setoid r.r = r := le_antisymm (by rw eqv_gen_eq; exact Inf_le (λ _ _, id)) eqv_gen.rel /-- Equivalence closure is idempotent. -/ @[simp] lemma eqv_gen_idem (r : α → α → Prop) : eqv_gen.setoid (eqv_gen.setoid r).rel = eqv_gen.setoid r := eqv_gen_of_setoid _ /-- The equivalence closure of a binary relation r is contained in any equivalence relation containing r. -/ theorem eqv_gen_le {r : α → α → Prop} {s : setoid α} (h : ∀ x y, r x y → s.rel x y) : eqv_gen.setoid r ≤ s := by rw eqv_gen_eq; exact Inf_le h /-- Equivalence closure of binary relations is monotonic. -/ theorem eqv_gen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) : eqv_gen.setoid r ≤ eqv_gen.setoid s := eqv_gen_le $ λ _ _ hr, eqv_gen.rel _ _ $ h _ _ hr /-- There is a Galois insertion of equivalence relations on α into binary relations on α, with equivalence closure the lower adjoint. -/ def gi : @galois_insertion (α → α → Prop) (setoid α) _ _ eqv_gen.setoid rel := { choice := λ r h, eqv_gen.setoid r, gc := λ r s, ⟨λ H _ _ h, H $ eqv_gen.rel _ _ h, λ H, eqv_gen_of_setoid s ▸ eqv_gen_mono H⟩, le_l_u := λ x, (eqv_gen_of_setoid x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } open function /-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice of equivalence relations on α. -/ theorem injective_iff_ker_bot (f : α → β) : injective f ↔ ker f = ⊥ := (@eq_bot_iff (setoid α) _ (ker f)).symm /-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/ lemma ker_iff_mem_preimage {f : α → β} {x y} : (ker f).rel x y ↔ x ∈ f ⁻¹' {f y} := iff.rfl /-- Equivalence between functions `α → β` such that `r x y → f x = f y` and functions `quotient r → β`. -/ def lift_equiv (r : setoid α) : {f : α → β // r ≤ ker f} ≃ (quotient r → β) := { to_fun := λ f, quotient.lift (f : α → β) f.2, inv_fun := λ f, ⟨f ∘ quotient.mk, λ x y h, by simp [ker_def, quotient.sound h]⟩, left_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ x, rfl, right_inv := λ f, funext $ λ x, quotient.induction_on' x $ λ x, rfl } /-- The uniqueness part of the universal property for quotients of an arbitrary type. -/ theorem lift_unique {r : setoid α} {f : α → β} (H : r ≤ ker f) (g : quotient r → β) (Hg : f = g ∘ quotient.mk) : quotient.lift f H = g := begin ext ⟨x⟩, erw [quotient.lift_beta f H, Hg], refl end /-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is injective. -/ lemma ker_lift_injective (f : α → β) : injective (@quotient.lift _ _ (ker f) f (λ _ _ h, h)) := λ x y, quotient.induction_on₂' x y $ λ a b h, quotient.sound' h /-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose induced map from the quotient of α to β is injective. -/ lemma ker_eq_lift_of_injective {r : setoid α} (f : α → β) (H : ∀ x y, r.rel x y → f x = f y) (h : injective (quotient.lift f H)) : ker f = r := le_antisymm (λ x y hk, quotient.exact $ h $ show quotient.lift f H ⟦x⟧ = quotient.lift f H ⟦y⟧, from hk) H variables (r : setoid α) (f : α → β) /-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f bijects with f's image. -/ noncomputable def quotient_ker_equiv_range : quotient (ker f) ≃ set.range f := equiv.of_bijective (@quotient.lift _ (set.range f) (ker f) (λ x, ⟨f x, set.mem_range_self x⟩) $ λ _ _ h, subtype.ext_val h) ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨@quotient.mk _ (ker f) z, by rw quotient.lift_beta; exact subtype.ext_iff_val.2 hz⟩⟩ /-- The quotient of α by the kernel of a surjective function f bijects with f's codomain. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : surjective f) : quotient (ker f) ≃ β := (quotient_ker_equiv_range f).trans $ equiv.subtype_univ_equiv hf variables {r f} /-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `r`.' -/ def map (r : setoid α) (f : α → β) : setoid β := eqv_gen.setoid $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b /-- Given a surjective function f whose kernel is contained in an equivalence relation r, the equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to the elements of f⁻¹(y) by r. -/ def map_of_surjective (r) (f : α → β) (h : ker f ≤ r) (hf : surjective f) : setoid β := ⟨λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b, ⟨λ x, let ⟨y, hy⟩ := hf x in ⟨y, y, hy, hy, r.refl' y⟩, λ _ _ ⟨x, y, hx, hy, h⟩, ⟨y, x, hy, hx, r.symm' h⟩, λ _ _ _ ⟨x, y, hx, hy, h₁⟩ ⟨y', z, hy', hz, h₂⟩, ⟨x, z, hx, hz, r.trans' h₁ $ r.trans' (h $ by rwa ←hy' at hy) h₂⟩⟩⟩ /-- A special case of the equivalence closure of an equivalence relation r equalling r. -/ lemma map_of_surjective_eq_map (h : ker f ≤ r) (hf : surjective f) : map r f = map_of_surjective r f h hf := by rw ←eqv_gen_of_setoid (map_of_surjective r f h hf); refl /-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'. -/ def comap (f : α → β) (r : setoid β) : setoid α := ⟨λ x y, r.rel (f x) (f y), ⟨λ _, r.refl' _, λ _ _ h, r.symm' h, λ _ _ _ h1, r.trans' h1⟩⟩ /-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/ lemma comap_eq {f : α → β} {r : setoid β} : comap f r = ker (@quotient.mk _ r ∘ f) := ext $ λ x y, show _ ↔ ⟦_⟧ = ⟦_⟧, by rw quotient.eq; refl /-- The second isomorphism theorem for sets. -/ noncomputable def comap_quotient_equiv (f : α → β) (r : setoid β) : quotient (comap f r) ≃ set.range (@quotient.mk _ r ∘ f) := (quotient.congr_right $ ext_iff.1 comap_eq).trans $ quotient_ker_equiv_range $ quotient.mk ∘ f variables (r f) /-- The third isomorphism theorem for sets. -/ def quotient_quotient_equiv_quotient (s : setoid α) (h : r ≤ s) : quotient (ker (quot.map_right h)) ≃ quotient s := { to_fun := λ x, quotient.lift_on' x (λ w, quotient.lift_on' w (@quotient.mk _ s) $ λ x y H, quotient.sound $ h H) $ λ x y, quotient.induction_on₂' x y $ λ w z H, show @quot.mk _ _ _ = @quot.mk _ _ _, from H, inv_fun := λ x, quotient.lift_on' x (λ w, @quotient.mk _ (ker $ quot.map_right h) $ @quotient.mk _ r w) $ λ x y H, quotient.sound' $ show @quot.mk _ _ _ = @quot.mk _ _ _, from quotient.sound H, left_inv := λ x, quotient.induction_on' x $ λ y, quotient.induction_on' y $ λ w, by show ⟦_⟧ = _; refl, right_inv := λ x, quotient.induction_on' x $ λ y, by show ⟦_⟧ = _; refl } variables {r f} open quotient /-- Given an equivalence relation r on α, the order-preserving bijection between the set of equivalence relations containing r and the equivalence relations on the quotient of α by r. -/ def correspondence (r : setoid α) : {s // r ≤ s} ≃o setoid (quotient r) := { to_fun := λ s, map_of_surjective s.1 quotient.mk ((ker_mk_eq r).symm ▸ s.2) exists_rep, inv_fun := λ s, ⟨comap quotient.mk s, λ x y h, show s.rel ⟦x⟧ ⟦y⟧, by rw eq_rel.2 h⟩, left_inv := λ s, subtype.ext_iff_val.2 $ ext' $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in s.1.trans' (s.1.symm' $ s.2 $ eq_rel.1 hx) $ s.1.trans' H $ s.2 $ eq_rel.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ s, let Hm : ker quotient.mk ≤ comap quotient.mk s := λ x y h, show s.rel ⟦x⟧ ⟦y⟧, by rw (@eq_rel _ r x y).2 ((ker_mk_eq r) ▸ h) in ext' $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, quotient.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h x y hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h x y hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨x, y, 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 setoid
0f19055e795aa68c0cbda64e67238f861113580f
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/binary.lean
9678399c05303d84929da4a3155f766331e4b96f
[ "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
3,709
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad General properties of binary operations. -/ open function namespace binary section variable {A : Type} variables (op₁ : A → A → A) (inv : A → A) (one : A) local notation a * b := op₁ a b local notation a ⁻¹ := inv a attribute [reducible] definition commutative := ∀a b, a * b = b * a attribute [reducible] definition associative := ∀a b c, (a * b) * c = a * (b * c) attribute [reducible] definition left_identity := ∀a, one * a = a attribute [reducible] definition right_identity := ∀a, a * one = a attribute [reducible] definition left_inverse := ∀a, a⁻¹ * a = one attribute [reducible] definition right_inverse := ∀a, a * a⁻¹ = one attribute [reducible] definition left_cancelative := ∀a b c, a * b = a * c → b = c attribute [reducible] definition right_cancelative := ∀a b c, a * b = c * b → a = c attribute [reducible] definition inv_op_cancel_left := ∀a b, a⁻¹ * (a * b) = b attribute [reducible] definition op_inv_cancel_left := ∀a b, a * (a⁻¹ * b) = b attribute [reducible] definition inv_op_cancel_right := ∀a b, a * b⁻¹ * b = a attribute [reducible] definition op_inv_cancel_right := ∀a b, a * b * b⁻¹ = a variable (op₂ : A → A → A) local notation a + b := op₂ a b attribute [reducible] definition left_distributive := ∀a b c, a * (b + c) = a * b + a * c attribute [reducible] definition right_distributive := ∀a b c, (a + b) * c = a * c + b * c attribute [reducible] definition right_commutative {B : Type} (f : B → A → B) := ∀ b a₁ a₂, f (f b a₁) a₂ = f (f b a₂) a₁ attribute [reducible] definition left_commutative {B : Type} (f : A → B → B) := ∀ a₁ a₂ b, f a₁ (f a₂ b) = f a₂ (f a₁ b) end section variable {A : Type} variable {f : A → A → A} variable H_comm : commutative f variable H_assoc : associative f local infixl `*` := f include H_comm theorem left_comm : left_commutative f := take a b c, calc a*(b*c) = (a*b)*c : eq.symm (H_assoc _ _ _) ... = (b*a)*c : sorry -- by rewrite (H_comm a b) ... = b*(a*c) : H_assoc _ _ _ theorem right_comm : right_commutative f := take a b c, calc (a*b)*c = a*(b*c) : H_assoc _ _ _ ... = a*(c*b) : sorry -- by rewrite (H_comm b c) ... = (a*c)*b : eq.symm (H_assoc _ _ _) theorem comm4 (a b c d : A) : a*b*(c*d) = a*c*(b*d) := calc a*b*(c*d) = a*b*c*d : eq.symm (H_assoc _ _ _) ... = a*c*b*d : sorry -- by rewrite (right_comm H_comm H_assoc a b c) ... = a*c*(b*d) : H_assoc _ _ _ end section variable {A : Type} variable {f : A → A → A} variable H_assoc : associative f local infixl `*` := f theorem assoc4helper (a b c d) : (a*b)*(c*d) = a*((b*c)*d) := calc (a*b)*(c*d) = a*(b*(c*d)) : H_assoc _ _ _ ... = a*((b*c)*d) : sorry -- by rewrite (H_assoc b c d) end attribute [reducible] definition right_commutative_comp_right {A B : Type} (f : A → A → A) (g : B → A) (rcomm : right_commutative f) : right_commutative (comp_right f g) := λ a b₁ b₂, rcomm _ _ _ attribute [reducible] definition left_commutative_compose_left {A B : Type} (f : A → A → A) (g : B → A) (lcomm : left_commutative f) : left_commutative (comp_left f g) := λ a b₁ b₂, lcomm _ _ _ end binary
4cdf06c373e2e616afd7ffbbe8f9a38a6d07d42b
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/field_theory/normal.lean
d4725a1ba58275c31dc2febf1fcaf06cbc5aa131
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,217
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import field_theory.adjoin import field_theory.tower import group_theory.solvable import ring_theory.power_basis /-! # Normal field extensions In this file we define normal field extensions and prove that for a finite extension, being normal is the same as being a splitting field (`normal.of_is_splitting_field` and `normal.exists_is_splitting_field`). ## Main Definitions - `normal F K` where `K` is a field extension of `F`. -/ noncomputable theory open_locale classical open polynomial is_scalar_tower variables (F K : Type*) [field F] [field K] [algebra F K] --TODO(Commelin): refactor normal to extend `is_algebraic`?? /-- Typeclass for normal field extension: `K` is a normal extension of `F` iff the minimal polynomial of every element `x` in `K` splits in `K`, i.e. every conjugate of `x` is in `K`. -/ class normal : Prop := (is_integral' (x : K) : is_integral F x) (splits' (x : K) : splits (algebra_map F K) (minpoly F x)) variables {F K} theorem normal.is_integral (h : normal F K) (x : K) : is_integral F x := normal.is_integral' x theorem normal.splits (h : normal F K) (x : K) : splits (algebra_map F K) (minpoly F x) := normal.splits' x theorem normal_iff : normal F K ↔ ∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := ⟨λ h x, ⟨h.is_integral x, h.splits x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩ theorem normal.out : normal F K → ∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := normal_iff.1 variables (F K) instance normal_self : normal F F := ⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact splits_X_sub_C _ }⟩ variables {K} variables (K) theorem normal.exists_is_splitting_field [h : normal F K] [finite_dimensional F K] : ∃ p : polynomial F, is_splitting_field F K p := begin obtain ⟨s, hs⟩ := finite_dimensional.exists_is_basis_finset F K, refine ⟨s.prod $ λ x, minpoly F x, splits_prod _ $ λ x hx, h.splits x, subalgebra.to_submodule_injective _⟩, rw [algebra.coe_top, eq_top_iff, ← hs.2, submodule.span_le, set.range_subset_iff], refine λ x, algebra.subset_adjoin (multiset.mem_to_finset.mpr $ (mem_roots $ mt (map_eq_zero $ algebra_map F K).1 $ finset.prod_ne_zero_iff.2 $ λ x hx, _).2 _), { exact minpoly.ne_zero (h.is_integral x) }, rw [is_root.def, eval_map, ← aeval_def, alg_hom.map_prod], exact finset.prod_eq_zero x.2 (minpoly.aeval _ _) end section normal_tower variables (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma normal.tower_top_of_normal [h : normal F E] : normal K E := normal_iff.2 $ λ x, begin cases h.out x with hx hhx, rw algebra_map_eq F K E at hhx, exact ⟨is_integral_of_is_scalar_tower x hx, polynomial.splits_of_splits_of_dvd (algebra_map K E) (polynomial.map_ne_zero (minpoly.ne_zero hx)) ((polynomial.splits_map_iff (algebra_map F K) (algebra_map K E)).mpr hhx) (minpoly.dvd_map_of_is_scalar_tower F K x)⟩, end lemma alg_hom.normal_bijective [h : normal F E] (ϕ : E →ₐ[F] K) : function.bijective ϕ := ⟨ϕ.to_ring_hom.injective, λ x, by { letI : algebra E K := ϕ.to_ring_hom.to_algebra, obtain ⟨h1, h2⟩ := h.out (algebra_map K E x), cases minpoly.mem_range_of_degree_eq_one E x (or.resolve_left h2 (minpoly.ne_zero h1) (minpoly.irreducible (is_integral_of_is_scalar_tower x ((is_integral_algebra_map_iff (algebra_map K E).injective).mp h1))) (minpoly.dvd E x ((algebra_map K E).injective (by { rw [ring_hom.map_zero, aeval_map, ←is_scalar_tower.to_alg_hom_apply F K E, ←alg_hom.comp_apply, ←aeval_alg_hom], exact minpoly.aeval F (algebra_map K E x) })))) with y hy, exact ⟨y, hy.2⟩ }⟩ variables {F} {E} {E' : Type*} [field E'] [algebra F E'] lemma normal.of_alg_equiv [h : normal F E] (f : E ≃ₐ[F] E') : normal F E' := normal_iff.2 $ λ x, begin cases h.out (f.symm x) with hx hhx, have H := is_integral_alg_hom f.to_alg_hom hx, rw [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_equiv.apply_symm_apply] at H, use H, apply polynomial.splits_of_splits_of_dvd (algebra_map F E') (minpoly.ne_zero hx), { rw ← alg_hom.comp_algebra_map f.to_alg_hom, exact polynomial.splits_comp_of_splits (algebra_map F E) f.to_alg_hom.to_ring_hom hhx }, { apply minpoly.dvd _ _, rw ← add_equiv.map_eq_zero_iff f.symm.to_add_equiv, exact eq.trans (polynomial.aeval_alg_hom_apply f.symm.to_alg_hom x (minpoly F (f.symm x))).symm (minpoly.aeval _ _) }, end lemma alg_equiv.transfer_normal (f : E ≃ₐ[F] E') : normal F E ↔ normal F E' := ⟨λ h, by exactI normal.of_alg_equiv f, λ h, by exactI normal.of_alg_equiv f.symm⟩ lemma normal.of_is_splitting_field (p : polynomial F) [hFEp : is_splitting_field F E p] : normal F E := begin by_cases hp : p = 0, { haveI : is_splitting_field F F p := by { rw hp, exact ⟨splits_zero _, subsingleton.elim _ _⟩ }, exactI (alg_equiv.transfer_normal ((is_splitting_field.alg_equiv F p).trans (is_splitting_field.alg_equiv E p).symm)).mp (normal_self F) }, refine normal_iff.2 (λ x, _), haveI hFE : finite_dimensional F E := is_splitting_field.finite_dimensional E p, have Hx : is_integral F x := is_integral_of_noetherian hFE x, refine ⟨Hx, or.inr _⟩, rintros q q_irred ⟨r, hr⟩, let D := adjoin_root q, let pbED := adjoin_root.power_basis q_irred.ne_zero, haveI : finite_dimensional E D := power_basis.finite_dimensional pbED, have findimED : finite_dimensional.findim E D = q.nat_degree := power_basis.findim pbED, letI : algebra F D := ring_hom.to_algebra ((algebra_map E D).comp (algebra_map F E)), haveI : is_scalar_tower F E D := of_algebra_map_eq (λ _, rfl), haveI : finite_dimensional F D := finite_dimensional.trans F E D, suffices : nonempty (D →ₐ[F] E), { cases this with ϕ, rw [←with_bot.coe_one, degree_eq_iff_nat_degree_eq q_irred.ne_zero, ←findimED], have nat_lemma : ∀ a b c : ℕ, a * b = c → c ≤ a → 0 < c → b = 1, { intros a b c h1 h2 h3, nlinarith }, exact nat_lemma _ _ _ (finite_dimensional.findim_mul_findim F E D) (linear_map.findim_le_findim_of_injective (show function.injective ϕ.to_linear_map, from ϕ.to_ring_hom.injective)) finite_dimensional.findim_pos, }, let C := adjoin_root (minpoly F x), have Hx_irred := minpoly.irreducible Hx, letI : algebra C D := ring_hom.to_algebra (adjoin_root.lift (algebra_map F D) (adjoin_root.root q) (by rw [algebra_map_eq F E D, ←eval₂_map, hr, adjoin_root.algebra_map_eq, eval₂_mul, adjoin_root.eval₂_root, zero_mul])), letI : algebra C E := ring_hom.to_algebra (adjoin_root.lift (algebra_map F E) x (minpoly.aeval F x)), haveI : is_scalar_tower F C D := of_algebra_map_eq (λ x, adjoin_root.lift_of.symm), haveI : is_scalar_tower F C E := of_algebra_map_eq (λ x, adjoin_root.lift_of.symm), suffices : nonempty (D →ₐ[C] E), { exact nonempty.map (alg_hom.restrict_scalars F) this }, let S : set D := ((p.map (algebra_map F E)).roots.map (algebra_map E D)).to_finset, suffices : ⊤ ≤ intermediate_field.adjoin C S, { refine intermediate_field.alg_hom_mk_adjoin_splits' (top_le_iff.mp this) (λ y hy, _), rcases multiset.mem_map.mp (multiset.mem_to_finset.mp hy) with ⟨z, hz1, hz2⟩, have Hz : is_integral F z := is_integral_of_noetherian hFE z, use (show is_integral C y, from is_integral_of_noetherian (finite_dimensional.right F C D) y), apply splits_of_splits_of_dvd (algebra_map C E) (map_ne_zero (minpoly.ne_zero Hz)), { rw [splits_map_iff, ←algebra_map_eq F C E], exact splits_of_splits_of_dvd _ hp hFEp.splits (minpoly.dvd F z (eq.trans (eval₂_eq_eval_map _) ((mem_roots (map_ne_zero hp)).mp hz1))) }, { apply minpoly.dvd, rw [←hz2, aeval_def, eval₂_map, ←algebra_map_eq F C D, algebra_map_eq F E D, ←hom_eval₂, ←aeval_def, minpoly.aeval F z, ring_hom.map_zero] } }, rw [←intermediate_field.to_subalgebra_le_to_subalgebra, intermediate_field.top_to_subalgebra], apply ge_trans (intermediate_field.algebra_adjoin_le_adjoin C S), suffices : (algebra.adjoin C S).res F = (algebra.adjoin E {adjoin_root.root q}).res F, { rw [adjoin_root.adjoin_root_eq_top, subalgebra.res_top, ←@subalgebra.res_top F C] at this, exact top_le_iff.mpr (subalgebra.res_inj F this) }, dsimp only [S], rw [←finset.image_to_finset, finset.coe_image], apply eq.trans (algebra.adjoin_res_eq_adjoin_res F E C D hFEp.adjoin_roots adjoin_root.adjoin_root_eq_top), rw [set.image_singleton, ring_hom.algebra_map_to_algebra, adjoin_root.lift_root] end instance (p : polynomial F) : normal F p.splitting_field := normal.of_is_splitting_field p end normal_tower variables {F} {K} (ϕ ψ : K →ₐ[F] K) (χ ω : K ≃ₐ[F] K) section restrict variables (E : Type*) [field E] [algebra F E] [algebra E K] [is_scalar_tower F E K] /-- Restrict algebra homomorphism to image of normal subfield -/ def alg_hom.restrict_normal_aux [h : normal F E] : (to_alg_hom F E K).range →ₐ[F] (to_alg_hom F E K).range := { to_fun := λ x, ⟨ϕ x, by { suffices : (to_alg_hom F E K).range.map ϕ ≤ _, { exact this ⟨x, subtype.mem x, rfl⟩ }, rintros x ⟨y, ⟨z, -, hy⟩, hx⟩, rw [←hx, ←hy], apply minpoly.mem_range_of_degree_eq_one E, exact or.resolve_left (h.splits z) (minpoly.ne_zero (h.is_integral z)) (minpoly.irreducible $ is_integral_of_is_scalar_tower _ $ is_integral_alg_hom ϕ $ is_integral_alg_hom _ $ h.is_integral z) (minpoly.dvd E _ $ by rw [aeval_map, aeval_alg_hom, aeval_alg_hom, alg_hom.comp_apply, alg_hom.comp_apply, minpoly.aeval, alg_hom.map_zero, alg_hom.map_zero]) }⟩, map_zero' := subtype.ext ϕ.map_zero, map_one' := subtype.ext ϕ.map_one, map_add' := λ x y, subtype.ext (ϕ.map_add x y), map_mul' := λ x y, subtype.ext (ϕ.map_mul x y), commutes' := λ x, subtype.ext (ϕ.commutes x) } /-- Restrict algebra homomorphism to normal subfield -/ def alg_hom.restrict_normal [normal F E] : E →ₐ[F] E := ((alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).symm.to_alg_hom.comp (ϕ.restrict_normal_aux E)).comp (alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).to_alg_hom @[simp] lemma alg_hom.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K (ϕ.restrict_normal E x) = ϕ (algebra_map E K x) := subtype.ext_iff.mp (alg_equiv.apply_symm_apply (alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)) (ϕ.restrict_normal_aux E ⟨is_scalar_tower.to_alg_hom F E K x, ⟨x, ⟨subsemiring.mem_top x, rfl⟩⟩⟩)) lemma alg_hom.restrict_normal_comp [normal F E] : (ϕ.restrict_normal E).comp (ψ.restrict_normal E) = (ϕ.comp ψ).restrict_normal E := alg_hom.ext (λ _, (algebra_map E K).injective (by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes])) /-- Restrict algebra isomorphism to a normal subfield -/ def alg_equiv.restrict_normal [h : normal F E] : E ≃ₐ[F] E := alg_equiv.of_bijective (χ.to_alg_hom.restrict_normal E) (alg_hom.normal_bijective F E E _) @[simp] lemma alg_equiv.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K (χ.restrict_normal E x) = χ (algebra_map E K x) := χ.to_alg_hom.restrict_normal_commutes E x lemma alg_equiv.restrict_normal_trans [normal F E] : (χ.trans ω).restrict_normal E = (χ.restrict_normal E).trans (ω.restrict_normal E) := alg_equiv.ext (λ _, (algebra_map E K).injective (by simp only [alg_equiv.trans_apply, alg_equiv.restrict_normal_commutes])) /-- Restriction to an normal subfield as a group homomorphism -/ def alg_equiv.restrict_normal_hom [normal F E] : (K ≃ₐ[F] K) →* (E ≃ₐ[F] E) := monoid_hom.mk' (λ χ, χ.restrict_normal E) (λ ω χ, (χ.restrict_normal_trans ω E)) end restrict section lift variables {F} {K} (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E] /-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift an algebra homomorphism `ϕ : K →ₐ[F] K` to `ϕ.lift_normal E : E →ₐ[F] E`. -/ noncomputable def alg_hom.lift_normal [h : normal F E] : E →ₐ[F] E := @alg_hom.restrict_scalars F K E E _ _ _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra _ _ _ _ (nonempty.some (@intermediate_field.alg_hom_mk_adjoin_splits' K E E _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra ⊤ rfl (λ x hx, ⟨is_integral_of_is_scalar_tower x (h.out x).1, splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero (h.out x).1)) (by { rw [splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact (h.out x).2 }) (minpoly.dvd_map_of_is_scalar_tower F K x)⟩))) @[simp] lemma alg_hom.lift_normal_commutes [normal F E] (x : K) : ϕ.lift_normal E (algebra_map K E x) = algebra_map K E (ϕ x) := @alg_hom.commutes K E E _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra _ x @[simp] lemma alg_hom.restrict_lift_normal [normal F K] [normal F E] : (ϕ.lift_normal E).restrict_normal K = ϕ := alg_hom.ext (λ x, (algebra_map K E).injective (eq.trans (alg_hom.restrict_normal_commutes _ K x) (ϕ.lift_normal_commutes E x))) /-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift an algebra isomorphism `ϕ : K ≃ₐ[F] K` to `ϕ.lift_normal E : E ≃ₐ[F] E`. -/ noncomputable def alg_equiv.lift_normal [normal F E] : E ≃ₐ[F] E := alg_equiv.of_bijective (χ.to_alg_hom.lift_normal E) (alg_hom.normal_bijective F E E _) @[simp] lemma alg_equiv.lift_normal_commutes [normal F E] (x : K) : χ.lift_normal E (algebra_map K E x) = algebra_map K E (χ x) := χ.to_alg_hom.lift_normal_commutes E x @[simp] lemma alg_equiv.restrict_lift_normal [normal F K] [normal F E] : (χ.lift_normal E).restrict_normal K = χ := alg_equiv.ext (λ x, (algebra_map K E).injective (eq.trans (alg_equiv.restrict_normal_commutes _ K x) (χ.lift_normal_commutes E x))) lemma alg_equiv.restrict_normal_hom_surjective [normal F K] [normal F E] : function.surjective (alg_equiv.restrict_normal_hom K : (E ≃ₐ[F] E) → (K ≃ₐ[F] K)) := λ χ, ⟨χ.lift_normal E, χ.restrict_lift_normal E⟩ variables (F) (K) (E) lemma is_solvable_of_is_scalar_tower [normal F K] [h1 : is_solvable (K ≃ₐ[F] K)] [h2 : is_solvable (E ≃ₐ[K] E)] : is_solvable (E ≃ₐ[F] E) := begin let f : (E ≃ₐ[K] E) →* (E ≃ₐ[F] E) := { to_fun := λ ϕ, alg_equiv.of_alg_hom (ϕ.to_alg_hom.restrict_scalars F) (ϕ.symm.to_alg_hom.restrict_scalars F) (alg_hom.ext (λ x, ϕ.apply_symm_apply x)) (alg_hom.ext (λ x, ϕ.symm_apply_apply x)), map_one' := alg_equiv.ext (λ _, rfl), map_mul' := λ _ _, alg_equiv.ext (λ _, rfl) }, refine solvable_of_ker_le_range f (alg_equiv.restrict_normal_hom K) (λ ϕ hϕ, ⟨{commutes' := λ x, _, .. ϕ}, alg_equiv.ext (λ _, rfl)⟩), exact (eq.trans (ϕ.restrict_normal_commutes K x).symm (congr_arg _ (alg_equiv.ext_iff.mp hϕ x))), end end lift
8a675566ff453e894f604a85989f468a6787f5b4
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/ring_theory/witt_vector/frobenius.lean
2d3b0e094a505b4b936e19117fa9d2121e76248a
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,345
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.nat.multiplicity import ring_theory.witt_vector.basic import ring_theory.witt_vector.is_poly /-! ## The Frobenius operator If `R` has characteristic `p`, then there is a ring endomorphism `frobenius R p` that raises `r : R` to the power `p`. By applying `witt_vector.map` to `frobenius R p`, we obtain a ring endomorphism `𝕎 R →+* 𝕎 R`. It turns out that this endomorphism can be described by polynomials over `ℤ` that do not depend on `R` or the fact that it has characteristic `p`. In this way, we obtain a Frobenius endomorphism `witt_vector.frobenius_fun : 𝕎 R → 𝕎 R` for every commutative ring `R`. Unfortunately, the aforementioned polynomials can not be obtained using the machinery of `witt_structure_int` that was developed in `structure_polynomial.lean`. We therefore have to define the polynomials by hand, and check that they have the required property. In case `R` has characteristic `p`, we show in `frobenius_fun_eq_map_frobenius` that `witt_vector.frobenius_fun` is equal to `witt_vector.map (frobenius R p)`. ### Main definitions and results * `frobenius_poly`: the polynomials that describe the coefficients of `frobenius_fun`; * `frobenius_fun`: the Frobenius endomorphism on Witt vectors; * `frobenius_fun_is_poly`: the tautological assertion that Frobenius is a polynomial function; * `frobenius_fun_eq_map_frobenius`: the fact that in characteristic `p`, Frobenius is equal to `witt_vector.map (frobenius R p)`. TODO: Show that `witt_vector.frobenius_fun` is a ring homomorphism, and bundle it into `witt_vector.frobenius`. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ namespace witt_vector variables {p : ℕ} {R S : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S] local notation `𝕎` := witt_vector p -- type as `\bbW` local attribute [semireducible] witt_vector noncomputable theory open mv_polynomial finset open_locale big_operators variables (p) include hp /-- The rational polynomials that give the coefficients of `frobenius x`, in terms of the coefficients of `x`. These polynomials actually have integral coefficients, see `frobenius_poly` and `map_frobenius_poly`. -/ def frobenius_poly_rat (n : ℕ) : mv_polynomial ℕ ℚ := bind₁ (witt_polynomial p ℚ ∘ λ n, n + 1) (X_in_terms_of_W p ℚ n) lemma bind₁_frobenius_poly_rat_witt_polynomial (n : ℕ) : bind₁ (frobenius_poly_rat p) (witt_polynomial p ℚ n) = (witt_polynomial p ℚ (n+1)) := begin delta frobenius_poly_rat, rw [← bind₁_bind₁, bind₁_X_in_terms_of_W_witt_polynomial, bind₁_X_right], end /-- An auxilliary definition, to avoid an excessive amount of finiteness proofs for `multiplicity p n`. -/ private def pnat_multiplicity (n : ℕ+) : ℕ := (multiplicity p n).get $ multiplicity.finite_nat_iff.mpr $ ⟨ne_of_gt hp.one_lt, n.2⟩ local notation `v` := pnat_multiplicity /-- An auxilliary polynomial over the integers, that satisfies `(frobenius_poly_aux p n - X n ^ p) / p = frobenius_poly p n`. This makes it easy to show that `frobenius_poly p n` is congruent to `X n ^ p` modulo `p`. -/ noncomputable def frobenius_poly_aux : ℕ → mv_polynomial ℕ ℤ | n := X (n + 1) - ∑ i : fin n, have _ := i.is_lt, ∑ j in range (p ^ (n - i)), (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * (frobenius_poly_aux i) ^ (j + 1) * C ↑((p ^ (n - i)).choose (j + 1) / (p ^ (n - i - v p ⟨j + 1, nat.succ_pos j⟩)) * ↑p ^ (j - v p ⟨j + 1, nat.succ_pos j⟩) : ℕ) lemma frobenius_poly_aux_eq (n : ℕ) : frobenius_poly_aux p n = X (n + 1) - ∑ i in range n, ∑ j in range (p ^ (n - i)), (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * (frobenius_poly_aux p i) ^ (j + 1) * C ↑((p ^ (n - i)).choose (j + 1) / (p ^ (n - i - v p ⟨j + 1, nat.succ_pos j⟩)) * ↑p ^ (j - v p ⟨j + 1, nat.succ_pos j⟩) : ℕ) := by { rw [frobenius_poly_aux, ← fin.sum_univ_eq_sum_range] } /-- The polynomials that give the coefficients of `frobenius x`, in terms of the coefficients of `x`. -/ def frobenius_poly (n : ℕ) : mv_polynomial ℕ ℤ := X n ^ p + C ↑p * (frobenius_poly_aux p n) /- Our next goal is to prove ``` lemma map_frobenius_poly (n : ℕ) : mv_polynomial.map (int.cast_ring_hom ℚ) (frobenius_poly p n) = frobenius_poly_rat p n ``` This lemma has a rather long proof, but it mostly boils down to applying induction, and then using the following two key facts at the right point. -/ /-- A key divisibility fact for the proof of `witt_vector.map_frobenius_poly`. -/ lemma map_frobenius_poly.key₁ (n j : ℕ) (hj : j < p ^ (n)) : p ^ (n - v p ⟨j + 1, j.succ_pos⟩) ∣ (p ^ n).choose (j + 1) := begin apply multiplicity.pow_dvd_of_le_multiplicity, have aux : (multiplicity p ((p ^ n).choose (j + 1))).dom, { rw [← multiplicity.finite_iff_dom, multiplicity.finite_nat_iff], exact ⟨hp.ne_one, nat.choose_pos hj⟩, }, rw [← enat.coe_get aux, enat.coe_le_coe, nat.sub_le_left_iff_le_add, ← enat.coe_le_coe, enat.coe_add, pnat_multiplicity, enat.coe_get, enat.coe_get, add_comm], exact (nat.prime.multiplicity_choose_prime_pow hp hj j.succ_pos).ge, end /-- A key numerical identity needed for the proof of `witt_vector.map_frobenius_poly`. -/ lemma map_frobenius_poly.key₂ {n i j : ℕ} (hi : i < n) (hj : j < p ^ (n - i)) : j - (v p ⟨j + 1, j.succ_pos⟩) + n = i + j + (n - i - v p ⟨j + 1, j.succ_pos⟩) := begin generalize h : (v p ⟨j + 1, j.succ_pos⟩) = m, suffices : m ≤ n - i ∧ m ≤ j, { cases this, unfreezingI { clear_dependent p }, omega }, split, { rw [← h, ← enat.coe_le_coe, pnat_multiplicity, enat.coe_get, ← (nat.prime.multiplicity_choose_prime_pow hp hj j.succ_pos)], apply le_add_left, refl }, { obtain ⟨c, hc⟩ : p ^ m ∣ j + 1, { rw [← h], exact multiplicity.pow_multiplicity_dvd _, }, obtain ⟨c, rfl⟩ : ∃ k : ℕ, c = k + 1, { apply nat.exists_eq_succ_of_ne_zero, rintro rfl, simpa only using hc }, rw [mul_add, mul_one] at hc, apply nat.le_of_lt_succ, calc m < p ^ m : nat.lt_pow_self hp.one_lt m ... ≤ j + 1 : by { rw ← nat.sub_eq_of_eq_add hc, apply nat.sub_le } } end lemma map_frobenius_poly (n : ℕ) : mv_polynomial.map (int.cast_ring_hom ℚ) (frobenius_poly p n) = frobenius_poly_rat p n := begin rw [frobenius_poly, ring_hom.map_add, ring_hom.map_mul, ring_hom.map_pow, map_C, map_X, ring_hom.eq_int_cast, int.cast_coe_nat, frobenius_poly_rat], apply nat.strong_induction_on n, clear n, intros n IH, rw [X_in_terms_of_W_eq], simp only [alg_hom.map_sum, alg_hom.map_sub, alg_hom.map_mul, alg_hom.map_pow, bind₁_C_right], have h1 : (↑p ^ n) * (⅟ (↑p : ℚ) ^ n) = 1 := by rw [←mul_pow, mul_inv_of_self, one_pow], rw [bind₁_X_right, function.comp_app, witt_polynomial_eq_sum_C_mul_X_pow, sum_range_succ, sum_range_succ, nat.sub_self, nat.add_sub_cancel_left, pow_zero, pow_one, pow_one, sub_mul, add_mul, add_mul, mul_assoc, mul_assoc, mul_comm _ (C (⅟ ↑p ^ n)), mul_comm _ (C (⅟ ↑p ^ n)), ←mul_assoc, ←mul_assoc, ←C_mul, ←C_mul, pow_succ, mul_assoc ↑p (↑p ^ n) (⅟ ↑p ^ n), h1, mul_one, C_1, one_mul, ←add_assoc, add_comm _ (X n ^ p), add_assoc, ←add_sub, add_right_inj], rw [frobenius_poly_aux_eq, ring_hom.map_sub, map_X, mul_sub, ←add_sub, sub_eq_add_neg, add_right_inj, neg_eq_iff_neg_eq, neg_sub], simp only [ring_hom.map_sum, mul_sum, sum_mul, ←sum_sub_distrib], apply sum_congr rfl, intros i hi, rw mem_range at hi, rw [← IH i hi], clear IH, rw [add_comm (X i ^ p), add_pow, sum_range_succ', pow_zero, nat.sub_zero, nat.choose_zero_right, one_mul, nat.cast_one, mul_one, mul_add, add_mul, nat.succ_sub (le_of_lt hi), nat.succ_eq_add_one (n - i), pow_succ, pow_mul, add_sub_cancel, mul_sum, sum_mul], apply sum_congr rfl, intros j hj, rw mem_range at hj, rw [ring_hom.map_mul, ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_pow, ring_hom.map_pow, ring_hom.map_pow, ring_hom.map_pow, map_C, map_X, mul_pow], rw [mul_comm (C ↑p ^ i), mul_comm _ ((X i ^ p) ^ _), mul_comm (C ↑p ^ (j + 1)), mul_comm (C ↑p)], simp only [mul_assoc], apply congr_arg, apply congr_arg, rw [←C_eq_coe_nat], simp only [←ring_hom.map_pow, ←C_mul], rw C_inj, simp only [inv_of_eq_inv, ring_hom.eq_int_cast, inv_pow', int.cast_coe_nat, nat.cast_mul], rw [rat.coe_nat_div _ _ (map_frobenius_poly.key₁ p (n - i) j hj)], simp only [nat.cast_pow, pow_add, pow_one], suffices : ((p ^ (n - i)).choose (j + 1) * p ^ (j - v p ⟨j + 1, j.succ_pos⟩) * p * p ^ n : ℚ) = p ^ j * p * ((p ^ (n - i)).choose (j + 1) * p ^ i) * p ^ (n - i - v p ⟨j + 1, j.succ_pos⟩), { have aux : ∀ k : ℕ, (p ^ k : ℚ) ≠ 0, { intro, apply pow_ne_zero, exact_mod_cast hp.ne_zero }, simpa [aux, -one_div] with field_simps using this.symm }, rw [mul_comm _ (p : ℚ), mul_assoc, mul_assoc, ← pow_add, map_frobenius_poly.key₂ p hi hj], ring_exp end lemma frobenius_poly_zmod (n : ℕ) : mv_polynomial.map (int.cast_ring_hom (zmod p)) (frobenius_poly p n) = X n ^ p := begin rw [frobenius_poly, ring_hom.map_add, ring_hom.map_pow, ring_hom.map_mul, map_X, map_C], simp only [int.cast_coe_nat, add_zero, ring_hom.eq_int_cast, zmod.nat_cast_self, zero_mul, C_0], end @[simp] lemma bind₁_frobenius_poly_witt_polynomial (n : ℕ) : bind₁ (frobenius_poly p) (witt_polynomial p ℤ n) = (witt_polynomial p ℤ (n+1)) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_bind₁, map_frobenius_poly, bind₁_frobenius_poly_rat_witt_polynomial, map_witt_polynomial], end variables {p} /-- `frobenius_fun` is the function underlying the ring endomorphism `frobenius : 𝕎 R →+* frobenius 𝕎 R`. -/ def frobenius_fun (x : 𝕎 R) : 𝕎 R := mk p $ λ n, mv_polynomial.aeval x.coeff (frobenius_poly p n) lemma coeff_frobenius_fun (x : 𝕎 R) (n : ℕ) : coeff (frobenius_fun x) n = mv_polynomial.aeval x.coeff (frobenius_poly p n) := by rw [frobenius_fun, coeff_mk] variables (p) /-- `frobenius_fun` is tautologically a polynomial function. See also `frobenius_is_poly`. -/ @[is_poly] lemma frobenius_fun_is_poly : is_poly p (λ R _Rcr, @frobenius_fun p R _ _Rcr) := ⟨⟨frobenius_poly p, by { introsI, funext n, apply coeff_frobenius_fun }⟩⟩ variable {p} @[ghost_simps] lemma ghost_component_frobenius_fun (n : ℕ) (x : 𝕎 R) : ghost_component n (frobenius_fun x) = ghost_component (n + 1) x := by simp only [ghost_component_apply, frobenius_fun, coeff_mk, ← bind₁_frobenius_poly_witt_polynomial, aeval_bind₁] /-- If `R` has characteristic `p`, then there is a ring endomorphism that raises `r : R` to the power `p`. By applying `witt_vector.map` to this endomorphism, we obtain a ring endomorphism `frobenius R p : 𝕎 R →+* 𝕎 R`. The underlying function of this morphism is `witt_vector.frobenius_fun`. -/ def frobenius : 𝕎 R →+* 𝕎 R := { to_fun := frobenius_fun, map_zero' := begin refine is_poly.ext ((frobenius_fun_is_poly p).comp (witt_vector.zero_is_poly)) ((witt_vector.zero_is_poly).comp (frobenius_fun_is_poly p)) _ _ 0, ghost_simp end, map_one' := begin refine is_poly.ext ((frobenius_fun_is_poly p).comp (witt_vector.one_is_poly)) ((witt_vector.one_is_poly).comp (frobenius_fun_is_poly p)) _ _ 0, ghost_simp end, map_add' := by ghost_calc _ _; ghost_simp, map_mul' := by ghost_calc _ _; ghost_simp } lemma coeff_frobenius (x : 𝕎 R) (n : ℕ) : coeff (frobenius x) n = mv_polynomial.aeval x.coeff (frobenius_poly p n) := coeff_frobenius_fun _ _ @[ghost_simps] lemma ghost_component_frobenius (n : ℕ) (x : 𝕎 R) : ghost_component n (frobenius x) = ghost_component (n + 1) x := ghost_component_frobenius_fun _ _ variables (p) /-- `frobenius` is tautologically a polynomial function. -/ @[is_poly] lemma frobenius_is_poly : is_poly p (λ R _Rcr, @frobenius p R _ _Rcr) := frobenius_fun_is_poly _ section char_p variables [char_p R p] @[simp] lemma coeff_frobenius_char_p (x : 𝕎 R) (n : ℕ) : coeff (frobenius x) n = (x.coeff n) ^ p := begin rw [coeff_frobenius], -- outline of the calculation, proofs follow below calc aeval (λ k, x.coeff k) (frobenius_poly p n) = aeval (λ k, x.coeff k) (mv_polynomial.map (int.cast_ring_hom (zmod p)) (frobenius_poly p n)) : _ ... = aeval (λ k, x.coeff k) (X n ^ p : mv_polynomial ℕ (zmod p)) : _ ... = (x.coeff n) ^ p : _, { conv_rhs { rw [aeval_eq_eval₂_hom, eval₂_hom_map_hom] }, apply eval₂_hom_congr (ring_hom.ext_int _ _) rfl rfl }, { rw frobenius_poly_zmod }, { rw [alg_hom.map_pow, aeval_X] } end lemma frobenius_eq_map_frobenius : @frobenius p R _ _ = map (_root_.frobenius R p) := begin ext x n, simp only [coeff_frobenius_char_p, map_coeff, frobenius_def], end @[simp] lemma frobenius_zmodp (x : 𝕎 (zmod p)) : (frobenius x) = x := by simp only [ext_iff, coeff_frobenius_char_p, zmod.pow_card, eq_self_iff_true, forall_const] end char_p end witt_vector
85df88624f2b09656f68544528f4aeca1db9802f
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/matrix/basis.lean
262bf58bb909bb0d4a32272a50c1f725aa8a357a
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
171
lean
import linear_algebra.determinant import linear_algebra.matrix import data.complex.basic open linear_map notation `Σ` := finset.sum finset.univ universe variables u v w
1ba669f20b40149a87180df5d1309adea24a59de
94e33a31faa76775069b071adea97e86e218a8ee
/src/set_theory/cardinal/basic.lean
7be2e3c90f840c799f7ec3ccb15db06cd9f293d0
[ "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
65,265
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, Floris van Doorn -/ import data.nat.part_enat import data.set.countable import logic.small import order.conditionally_complete_lattice import order.succ_pred.basic import set_theory.cardinal.schroeder_bernstein /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. ## Main definitions * `cardinal` the type of cardinal numbers (in a given universe). * `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale `cardinal`. * There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`. * Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`. * Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α × β)`. * The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`. * Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`. * `cardinal.aleph_0` or `ℵ₀` is the cardinality of `ℕ`. This definition is universe polymorphic: `cardinal.aleph_0.{u} : cardinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`. * `order.succ c` is the successor cardinal, the smallest cardinal larger than `c`. * `cardinal.sum` is the sum of a collection of cardinals. * `cardinal.powerlt a b` or `a ^< b` is defined as the supremum of `a ^ c` for `c < b`. ## Main Statements * Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`. * König's theorem: `cardinal.sum_lt_prod` ## 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`. The operation `cardinal.lift` lifts cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/cardinal_ordinal.lean`. * There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both the base and the exponent live in the same universe. As a workaround, you can add ``` local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow ``` to a file. This notation will work even if Lean doesn't know yet that the base and the exponent live in the same universe (but no exponents in other types can be used). ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, aleph, Cantor's theorem, König's theorem, Konig's theorem -/ open function set order open_locale classical noncomputable theory universes u v w 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 localized "notation `#` := cardinal.mk" in cardinal instance can_lift_cardinal_Type : can_lift cardinal.{u} (Type u) := ⟨mk, λ c, true, λ c _, quot.induction_on c $ λ α, ⟨α, rfl⟩⟩ @[elab_as_eliminator] lemma induction_on {p : cardinal → Prop} (c : cardinal) (h : ∀ α, p (#α)) : p c := quotient.induction_on c h @[elab_as_eliminator] lemma induction_on₂ {p : cardinal → cardinal → Prop} (c₁ : cardinal) (c₂ : cardinal) (h : ∀ α β, p (#α) (#β)) : p c₁ c₂ := quotient.induction_on₂ c₁ c₂ h @[elab_as_eliminator] lemma induction_on₃ {p : cardinal → cardinal → cardinal → Prop} (c₁ : cardinal) (c₂ : cardinal) (c₃ : cardinal) (h : ∀ α β γ, p (#α) (#β) (#γ)) : p c₁ c₂ c₃ := quotient.induction_on₃ c₁ c₂ c₃ h protected lemma eq : #α = #β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (#α) := rfl @[simp] theorem mk_out (c : cardinal) : #(c.out) = c := quotient.out_eq _ /-- The representative of the cardinal of a type is equivalent ot the original type. -/ def out_mk_equiv {α : Type v} : (#α).out ≃ α := nonempty.some $ cardinal.eq.mp (by simp) lemma mk_congr (e : α ≃ β) : # α = # β := quot.sound ⟨e⟩ alias mk_congr ← _root_.equiv.cardinal_eq /-- Lift a function between `Type*`s to a function between `cardinal`s. -/ def map (f : Type u → Type v) (hf : ∀ α β, α ≃ β → f α ≃ f β) : cardinal.{u} → cardinal.{v} := quotient.map f (λ α β ⟨e⟩, ⟨hf α β e⟩) @[simp] lemma map_mk (f : Type u → Type v) (hf : ∀ α β, α ≃ β → f α ≃ f β) (α : Type u) : map f hf (#α) = #(f α) := rfl /-- Lift a binary operation `Type* → Type* → Type*` to a binary operation on `cardinal`s. -/ def map₂ (f : Type u → Type v → Type w) (hf : ∀ α β γ δ, α ≃ β → γ ≃ δ → f α γ ≃ f β δ) : cardinal.{u} → cardinal.{v} → cardinal.{w} := quotient.map₂ f $ λ α β ⟨e₁⟩ γ δ ⟨e₂⟩, ⟨hf α β γ δ e₁ e₂⟩ /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{v} → cardinal.{max v u}` -/ def lift (c : cardinal.{v}) : cardinal.{max v u} := map ulift (λ α β e, equiv.ulift.trans $ e.trans equiv.ulift.symm) c @[simp] theorem mk_ulift (α) : #(ulift.{v u} α) = lift.{v} (#α) := rfl /-- `lift.{(max u v) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much easier to understand what's happening when using this lemma. -/ @[simp] theorem lift_umax : lift.{(max u v) u} = lift.{v u} := funext $ λ a, induction_on a $ λ α, (equiv.ulift.trans equiv.ulift.symm).cardinal_eq /-- `lift.{(max v u) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much easier to understand what's happening when using this lemma. -/ @[simp] theorem lift_umax' : lift.{(max v u) u} = lift.{v u} := lift_umax /-- A cardinal lifted to a lower or equal universe equals itself. -/ @[simp] theorem lift_id' (a : cardinal.{max u v}) : lift.{u} a = a := induction_on a $ λ α, mk_congr equiv.ulift /-- A cardinal lifted to the same universe equals itself. -/ @[simp] theorem lift_id (a : cardinal) : lift.{u u} a = a := lift_id'.{u u} a /-- A cardinal lifted to the zero universe equals itself. -/ @[simp] theorem lift_uzero (a : cardinal.{u}) : lift.{0} a = a := lift_id'.{0 u} a @[simp] theorem lift_lift (a : cardinal) : lift.{w} (lift.{v} a) = lift.{max v w} a := induction_on a $ λ α, (equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm).cardinal_eq /-- We define the order on cardinal numbers by `#α ≤ #β` 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 $ α ↪ β) $ λ α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨λ ⟨e⟩, ⟨e.congr e₁ e₂⟩, λ ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ instance : partial_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₂) } } theorem le_def (α β : Type u) : #α ≤ #β ↔ nonempty (α ↪ β) := iff.rfl theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : #α ≤ #β := ⟨⟨f, hf⟩⟩ theorem _root_.function.embedding.cardinal_le {α β : Type u} (f : α ↪ β) : #α ≤ #β := ⟨f⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : #β ≤ #α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ #α ↔ ∃ p : set α, #p = c := ⟨induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, (equiv.of_injective f hf).cardinal_eq.symm⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem mk_subtype_le {α : Type u} (p : α → Prop) : #(subtype p) ≤ #α := ⟨embedding.subtype p⟩ theorem mk_set_le (s : set α) : #s ≤ #α := mk_subtype_le s 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 } theorem lift_mk_le {α : Type u} {β : Type v} : lift.{(max v w)} (#α) ≤ lift.{max u w} (#β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ /-- A variant of `cardinal.lift_mk_le` with specialized universes. Because Lean often can not realize it should use this specialization itself, we provide this statement separately so you don't have to solve the specialization problem either. -/ theorem lift_mk_le' {α : Type u} {β : Type v} : lift.{v} (#α) ≤ lift.{u} (#β) ↔ nonempty (α ↪ β) := lift_mk_le.{u v 0} theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{max v w} (#α) = lift.{max u w} (#β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ /-- A variant of `cardinal.lift_mk_eq` with specialized universes. Because Lean often can not realize it should use this specialization itself, we provide this statement separately so you don't have to solve the specialization problem either. -/ theorem lift_mk_eq' {α : Type u} {β : Type v} : lift.{v} (#α) = lift.{u} (#β) ↔ nonempty (α ≃ β) := lift_mk_eq.{u v 0} @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := induction_on₂ a b $ λ α β, by { rw ← lift_umax, exact lift_mk_le } /-- `cardinal.lift` as an `order_embedding`. -/ @[simps { fully_applied := ff }] def lift_order_embedding : cardinal.{v} ↪o cardinal.{max v u} := order_embedding.of_map_le_iff lift (λ _ _, lift_le) theorem lift_injective : injective lift.{u v} := lift_order_embedding.injective @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := lift_injective.eq_iff @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := lift_order_embedding.lt_iff_lt theorem lift_strict_mono : strict_mono lift := λ a b, lift_lt.2 theorem lift_monotone : monotone lift := lift_strict_mono.monotone instance : has_zero cardinal.{u} := ⟨#pempty⟩ instance : inhabited cardinal.{u} := ⟨0⟩ lemma mk_eq_zero (α : Type u) [is_empty α] : #α = 0 := (equiv.equiv_pempty α).cardinal_eq @[simp] theorem lift_zero : lift 0 = 0 := mk_congr (equiv.equiv_pempty _) @[simp] theorem lift_eq_zero {a : cardinal.{v}} : lift.{u} a = 0 ↔ a = 0 := lift_injective.eq_iff' lift_zero lemma mk_eq_zero_iff {α : Type u} : #α = 0 ↔ is_empty α := ⟨λ e, let ⟨h⟩ := quotient.exact e in h.is_empty, @mk_eq_zero α⟩ theorem mk_ne_zero_iff {α : Type u} : #α ≠ 0 ↔ nonempty α := (not_iff_not.2 mk_eq_zero_iff).trans not_is_empty_iff @[simp] lemma mk_ne_zero (α : Type u) [nonempty α] : #α ≠ 0 := mk_ne_zero_iff.2 ‹_› instance : has_one cardinal.{u} := ⟨#punit⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, mk_ne_zero _⟩⟩ lemma mk_eq_one (α : Type u) [unique α] : #α = 1 := (equiv.equiv_punit α).cardinal_eq theorem le_one_iff_subsingleton {α : Type u} : #α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨map₂ sum $ λ α β γ δ, equiv.sum_congr⟩ theorem add_def (α β : Type u) : #α + #β = #(α ⊕ β) := rfl instance : has_nat_cast cardinal.{u} := ⟨nat.unary_cast⟩ @[simp] lemma mk_sum (α : Type u) (β : Type v) : #(α ⊕ β) = lift.{v u} (#α) + lift.{u v} (#β) := mk_congr ((equiv.ulift).symm.sum_congr (equiv.ulift).symm) @[simp] theorem mk_option {α : Type u} : #(option α) = #α + 1 := (equiv.option_equiv_sum_punit α).cardinal_eq @[simp] lemma mk_psum (α : Type u) (β : Type v) : #(psum α β) = lift.{v} (#α) + lift.{u} (#β) := (mk_congr (equiv.psum_equiv_sum α β)).trans (mk_sum α β) @[simp] lemma mk_fintype (α : Type u) [fintype α] : #α = fintype.card α := begin refine fintype.induction_empty_option' _ _ _ α, { introsI α β h e hα, letI := fintype.of_equiv β e.symm, rwa [mk_congr e, fintype.card_congr e] at hα }, { refl }, { introsI α h hα, simp [hα], refl } end instance : has_mul cardinal.{u} := ⟨map₂ prod $ λ α β γ δ, equiv.prod_congr⟩ theorem mul_def (α β : Type u) : #α * #β = #(α × β) := rfl @[simp] lemma mk_prod (α : Type u) (β : Type v) : #(α × β) = lift.{v u} (#α) * lift.{u v} (#β) := mk_congr (equiv.ulift.symm.prod_congr (equiv.ulift).symm) private theorem mul_comm' (a b : cardinal.{u}) : a * b = b * a := induction_on₂ a b $ λ α β, mk_congr $ equiv.prod_comm α β /-- The cardinal exponential. `#α ^ #β` is the cardinal of `β → α`. -/ instance : has_pow cardinal.{u} cardinal.{u} := ⟨map₂ (λ α β, β → α) (λ α β γ δ e₁ e₂, e₂.arrow_congr e₁)⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow local infixr ` ^ℕ `:80 := @has_pow.pow cardinal ℕ monoid.has_pow theorem power_def (α β) : #α ^ #β = #(β → α) := rfl theorem mk_arrow (α : Type u) (β : Type v) : #(α → β) = lift.{u} (#β) ^ lift.{v} (#α) := mk_congr (equiv.ulift.symm.arrow_congr equiv.ulift.symm) @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := induction_on₂ a b $ λ α β, mk_congr $ equiv.ulift.trans (equiv.ulift.arrow_congr equiv.ulift).symm @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := induction_on a $ λ α, mk_congr $ equiv.pempty_arrow_equiv_punit α @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := induction_on a $ λ α, mk_congr $ equiv.punit_arrow_equiv α theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.sum_arrow_equiv_prod_arrow β γ α instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := λ a, induction_on a $ λ α, mk_congr $ equiv.empty_sum pempty α, add_zero := λ a, induction_on a $ λ α, mk_congr $ equiv.sum_empty α pempty, add_assoc := λ a b c, induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.sum_assoc α β γ, add_comm := λ a b, induction_on₂ a b $ λ α β, mk_congr $ equiv.sum_comm α β, zero_mul := λ a, induction_on a $ λ α, mk_congr $ equiv.pempty_prod α, mul_zero := λ a, induction_on a $ λ α, mk_congr $ equiv.prod_pempty α, one_mul := λ a, induction_on a $ λ α, mk_congr $ equiv.punit_prod α, mul_one := λ a, induction_on a $ λ α, mk_congr $ equiv.prod_punit α, mul_assoc := λ a b c, induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.prod_assoc α β γ, mul_comm := mul_comm', left_distrib := λ a b c, induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.prod_sum_distrib α β γ, right_distrib := λ a b c, induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.sum_prod_distrib α β γ, npow := λ n c, c ^ n, npow_zero' := @power_zero, npow_succ' := λ n c, show c ^ (n + 1) = c * c ^ n, by rw [power_add, power_one, mul_comm'] } theorem power_bit0 (a b : cardinal) : a ^ (bit0 b) = a ^ b * a ^ b := power_add theorem power_bit1 (a b : cardinal) : a ^ (bit1 b) = a ^ b * a ^ b * a := by rw [bit1, ←power_bit0, power_add, power_one] @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := induction_on a $ λ α, (equiv.arrow_punit_equiv_punit α).cardinal_eq @[simp] theorem mk_bool : #bool = 2 := by simp @[simp] theorem mk_Prop : #(Prop) = 2 := by simp @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := induction_on a $ λ α heq, mk_eq_zero_iff.2 $ is_empty_pi.2 $ let ⟨a⟩ := mk_ne_zero_iff.1 heq in ⟨a, pempty.is_empty⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := induction_on₂ a b $ λ α β h, let ⟨a⟩ := mk_ne_zero_iff.1 h in mk_ne_zero_iff.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.arrow_prod_equiv_prod_arrow α β γ theorem power_mul {a b c : cardinal} : a ^ (b * c) = (a ^ b) ^ c := by { rw [mul_comm b c], exact induction_on₃ a b c (λ α β γ, mk_congr $ equiv.curry γ β α) } @[simp] lemma pow_cast_right (a : cardinal.{u}) (n : ℕ) : (a ^ (↑n : cardinal.{u})) = a ^ℕ n := rfl @[simp] theorem lift_one : lift 1 = 1 := mk_congr $ equiv.ulift.trans equiv.punit_equiv_punit @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := induction_on₂ a b $ λ α β, mk_congr $ equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := induction_on₂ a b $ λ α β, mk_congr $ equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm @[simp] theorem lift_bit0 (a : cardinal) : lift (bit0 a) = bit0 (lift a) := lift_add a a @[simp] theorem lift_bit1 (a : cardinal) : lift (bit1 a) = bit1 (lift a) := by simp [bit1] theorem lift_two : lift.{u v} 2 = 2 := by simp @[simp] theorem mk_set {α : Type u} : #(set α) = 2 ^ #α := by simp [set, mk_arrow] /-- A variant of `cardinal.mk_set` expressed in terms of a `set` instead of a `Type`. -/ @[simp] theorem mk_powerset {α : Type u} (s : set α) : #↥(𝒫 s) = 2 ^ #↥s := (mk_congr (equiv.set.powerset s)).trans mk_set theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp section order_properties open sum protected theorem zero_le : ∀ a : cardinal, 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_is_empty⟩ private theorem add_le_add' : ∀ {a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ instance add_covariant_class : covariant_class cardinal cardinal (+) (≤) := ⟨λ a b c, add_le_add' le_rfl⟩ instance add_swap_covariant_class : covariant_class cardinal cardinal (swap (+)) (≤) := ⟨λ a b c h, add_le_add' h le_rfl⟩ instance : canonically_ordered_comm_semiring cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, add_le_add_left := λ a b, add_le_add_left, exists_add_of_le := λ a b, induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.of_injective f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨#↥(range f)ᶜ, mk_congr this.symm⟩, le_self_add := λ a b, (add_zero a).ge.trans $ add_le_add_left (cardinal.zero_le _) _, eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, induction_on₂ a b $ λ α β, by simpa only [mul_def, mk_eq_zero_iff, is_empty_prod] using id, ..cardinal.comm_semiring, ..cardinal.partial_order } @[simp] 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 power_le_power_left : ∀ {a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := mk_ne_zero_iff.1 hα in ⟨@embedding.arrow_congr_left _ _ _ ⟨a⟩ e⟩ theorem self_le_power (a : cardinal) {b : cardinal} (hb : 1 ≤ b) : a ≤ a ^ b := begin rcases eq_or_ne a 0 with rfl|ha, { exact zero_le _ }, { convert power_le_power_left ha hb, exact power_one.symm } end /-- **Cantor's theorem** -/ theorem cantor (a : cardinal.{u}) : a < 2 ^ a := begin induction a using cardinal.induction_on with α, rw [← mk_set], refine ⟨⟨⟨singleton, λ a b, singleton_eq_singleton_iff.1⟩⟩, _⟩, rintro ⟨⟨f, hf⟩⟩, exact cantor_injective f hf end instance : no_max_order cardinal.{u} := { exists_gt := λ a, ⟨_, cantor a⟩, ..cardinal.partial_order } instance : canonically_linear_ordered_add_monoid cardinal.{u} := { le_total := by { rintros ⟨α⟩ ⟨β⟩, apply embedding.total }, decidable_le := classical.dec_rel _, ..(infer_instance : canonically_ordered_add_monoid cardinal), ..cardinal.partial_order } -- short-circuit type class inference instance : distrib_lattice cardinal.{u} := by apply_instance theorem one_lt_iff_nontrivial {α : Type u} : 1 < #α ↔ nontrivial α := by rw [← not_le, le_one_iff_subsingleton, ← not_nontrivial_iff_subsingleton, not_not] theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact (power_le_power_left ha h).trans (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := induction_on₃ a b c $ λ α β γ ⟨e⟩, ⟨embedding.arrow_congr_right e⟩ end order_properties protected theorem lt_wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, begin let ι := {c : cardinal // ¬ acc (<) c}, let f : ι → cardinal := subtype.val, haveI hι : nonempty ι := ⟨⟨_, h⟩⟩, obtain ⟨⟨c : cardinal, hc : ¬acc (<) c⟩, ⟨h_1 : Π j, (f ⟨c, hc⟩).out ↪ (f j).out⟩⟩ := embedding.min_injective (λ i, (f i).out), apply hc (acc.intro _ (λ j h', classical.by_contradiction (λ hj, h'.2 _))), have : #_ ≤ #_ := ⟨h_1 ⟨j, hj⟩⟩, simpa only [f, mk_out] using this end⟩ instance : has_well_founded cardinal.{u} := ⟨(<), cardinal.lt_wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.lt_wf⟩ instance : conditionally_complete_linear_order_bot cardinal := is_well_order.conditionally_complete_linear_order_bot _ @[simp] theorem Inf_empty : Inf (∅ : set cardinal.{u}) = 0 := dif_neg not_nonempty_empty /-- Note that the successor of `c` is not the same as `c + 1` except in the case of finite `c`. -/ instance : succ_order cardinal := succ_order.of_succ_le_iff (λ c, Inf {c' | c < c'}) (λ a b, ⟨lt_of_lt_of_le $ Inf_mem $ exists_gt a, cInf_le'⟩) theorem succ_def (c : cardinal) : succ c = Inf {c' | c < c'} := rfl theorem add_one_le_succ (c : cardinal.{u}) : c + 1 ≤ succ c := begin refine (le_cInf_iff'' (exists_gt c)).2 (λ b hlt, _), rcases ⟨b, c⟩ with ⟨⟨β⟩, ⟨γ⟩⟩, cases le_of_lt hlt with f, have : ¬ surjective f := λ hn, (not_le_of_lt hlt) (mk_le_of_surjective hn), simp only [surjective, not_forall] at this, rcases this with ⟨b, hb⟩, calc #γ + 1 = #(option γ) : mk_option.symm ... ≤ #β : (f.option_elim b hb).cardinal_le end lemma succ_pos : ∀ c : cardinal, 0 < succ c := bot_lt_succ lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := (succ_pos _).ne' /-- 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 mk_sigma {ι} (f : ι → Type*) : #(Σ i, f i) = sum (λ i, #(f i)) := mk_congr $ equiv.sigma_congr_right $ λ i, out_mk_equiv.symm @[simp] theorem sum_const (ι : Type u) (a : cardinal.{v}) : sum (λ i : ι, a) = lift.{v} (#ι) * lift.{u} a := induction_on a $ λ α, mk_congr $ calc (Σ i : ι, quotient.out (#α)) ≃ ι × quotient.out (#α) : equiv.sigma_equiv_prod _ _ ... ≃ ulift ι × ulift α : equiv.ulift.symm.prod_congr (out_mk_equiv.trans equiv.ulift.symm) theorem sum_const' (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = #ι * a := by simp @[simp] theorem sum_add_distrib {ι} (f g : ι → cardinal) : sum (f + g) = sum f + sum g := by simpa only [mk_sigma, mk_sum, mk_out, lift_id] using mk_congr (equiv.sigma_sum_distrib (quotient.out ∘ f) (quotient.out ∘ g)) @[simp] theorem sum_add_distrib' {ι} (f g : ι → cardinal) : cardinal.sum (λ i, f i + g i) = sum f + sum g := sum_add_distrib f g @[simp] theorem lift_sum {ι : Type u} (f : ι → cardinal.{v}) : cardinal.lift.{w} (cardinal.sum f) = cardinal.sum (λ i, cardinal.lift.{w} (f i)) := equiv.cardinal_eq $ equiv.ulift.trans $ equiv.sigma_congr_right $ λ a, nonempty.some $ by rw [←lift_mk_eq, mk_out, mk_out, lift_lift] theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ lemma mk_le_mk_mul_of_mk_preimage_le {c : cardinal} (f : α → β) (hf : ∀ b : β, #(f ⁻¹' {b}) ≤ c) : #α ≤ #β * c := by simpa only [←mk_congr (@equiv.sigma_fiber_equiv α β f), mk_sigma, ←sum_const'] using sum_le_sum _ _ hf /-- The range of an indexed cardinal function, whose outputs live in a higher universe than the inputs, is always bounded above. -/ theorem bdd_above_range {ι : Type u} (f : ι → cardinal.{max u v}) : bdd_above (set.range f) := ⟨_, by { rintros a ⟨i, rfl⟩, exact le_sum f i }⟩ instance (a : cardinal.{u}) : small.{u} (set.Iic a) := begin rw ←mk_out a, apply @small_of_surjective (set a.out) (Iic (#a.out)) _ (λ x, ⟨#x, mk_set_le x⟩), rintro ⟨x, hx⟩, simpa using le_mk_iff_exists_set.1 hx end /-- A set of cardinals is bounded above iff it's small, i.e. it corresponds to an usual ZFC set. -/ theorem bdd_above_iff_small {s : set cardinal.{u}} : bdd_above s ↔ small.{u} s := ⟨λ ⟨a, ha⟩, @small_subset _ (Iic a) s (λ x h, ha h) _, begin rintro ⟨ι, ⟨e⟩⟩, suffices : range (λ x : ι, (e.symm x).1) = s, { rw ←this, apply bdd_above_range.{u u} }, ext x, refine ⟨_, λ hx, ⟨e ⟨x, hx⟩, _⟩⟩, { rintro ⟨a, rfl⟩, exact (e.symm a).prop }, { simp_rw [subtype.val_eq_coe, equiv.symm_apply_apply], refl } end⟩ theorem bdd_above_image (f : cardinal.{u} → cardinal.{max u v}) {s : set cardinal.{u}} (hs : bdd_above s) : bdd_above (f '' s) := by { rw bdd_above_iff_small at hs ⊢, exactI small_lift _ } theorem bdd_above_range_comp {ι : Type u} {f : ι → cardinal.{v}} (hf : bdd_above (range f)) (g : cardinal.{v} → cardinal.{max v w}) : bdd_above (range (g ∘ f)) := by { rw range_comp, exact bdd_above_image g hf } theorem supr_le_sum {ι} (f : ι → cardinal) : supr f ≤ sum f := csupr_le' $ le_sum _ theorem sum_le_supr_lift {ι : Type u} (f : ι → cardinal.{max u v}) : sum f ≤ (#ι).lift * supr f := begin rw [←(supr f).lift_id, ←lift_umax, lift_umax.{(max u v) u}, ←sum_const], exact sum_le_sum _ _ (le_csupr $ bdd_above_range.{u v} f) end theorem sum_le_supr {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ #ι * supr f := by { rw ←lift_id (#ι), exact sum_le_supr_lift f } theorem sum_nat_eq_add_sum_succ (f : ℕ → cardinal.{u}) : cardinal.sum f = f 0 + cardinal.sum (λ i, f (i + 1)) := begin refine (equiv.sigma_nat_succ (λ i, quotient.out (f i))).cardinal_eq.trans _, simp only [mk_sum, mk_out, lift_id, mk_sigma], end /-- A variant of `csupr_of_empty` but with `0` on the RHS for convenience -/ @[simp] protected theorem supr_of_empty {ι} (f : ι → cardinal) [is_empty ι] : supr f = 0 := csupr_of_empty f @[simp] lemma lift_mk_shrink (α : Type u) [small.{v} α] : cardinal.lift.{max u w} (# (shrink.{v} α)) = cardinal.lift.{max v w} (# α) := lift_mk_eq.2 ⟨(equiv_shrink α).symm⟩ @[simp] lemma lift_mk_shrink' (α : Type u) [small.{v} α] : cardinal.lift.{u} (# (shrink.{v} α)) = cardinal.lift.{v} (# α) := lift_mk_shrink.{u v 0} α @[simp] lemma lift_mk_shrink'' (α : Type (max u v)) [small.{v} α] : cardinal.lift.{u} (# (shrink.{v} α)) = # α := by rw [← lift_umax', lift_mk_shrink.{(max u v) v 0} α, ← lift_umax, lift_id] /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := #(Π i, (f i).out) @[simp] theorem mk_pi {ι : Type u} (α : ι → Type v) : #(Π i, α i) = prod (λ i, #(α i)) := mk_congr $ equiv.Pi_congr_right $ λ i, out_mk_equiv.symm @[simp] theorem prod_const (ι : Type u) (a : cardinal.{v}) : prod (λ i : ι, a) = lift.{u} a ^ lift.{v} (#ι) := induction_on a $ λ α, mk_congr $ equiv.Pi_congr equiv.ulift.symm $ λ i, out_mk_equiv.trans equiv.ulift.symm theorem prod_const' (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ #ι := induction_on a $ λ α, (mk_pi _).symm 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⟩ @[simp] theorem prod_eq_zero {ι} (f : ι → cardinal.{u}) : prod f = 0 ↔ ∃ i, f i = 0 := by { lift f to ι → Type u using λ _, trivial, simp only [mk_eq_zero_iff, ← mk_pi, is_empty_pi] } theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := by simp [prod_eq_zero] @[simp] theorem lift_prod {ι : Type u} (c : ι → cardinal.{v}) : lift.{w} (prod c) = prod (λ i, lift.{w} (c i)) := begin lift c to ι → Type v using λ _, trivial, simp only [← mk_pi, ← mk_ulift], exact mk_congr (equiv.ulift.trans $ equiv.Pi_congr_right $ λ i, equiv.ulift.symm) end @[simp] theorem lift_Inf (s : set cardinal) : lift (Inf s) = Inf (lift '' s) := begin rcases eq_empty_or_nonempty s with rfl | hs, { simp }, { exact lift_monotone.map_Inf hs } end @[simp] theorem lift_infi {ι} (f : ι → cardinal) : lift (infi f) = ⨅ i, lift (f i) := by { unfold infi, convert lift_Inf (range f), rw range_comp } theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := induction_on₂ a b $ λ α β, by rw [← lift_id (#β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨#(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 h.le 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_iff, ← lift_le, e] at h, exact h.not_lt (lt_succ _) end) (succ_le_of_lt $ lift_lt.2 $ lt_succ a) @[simp] theorem lift_umax_eq {a : cardinal.{u}} {b : cardinal.{v}} : lift.{max v w} a = lift.{max u w} b ↔ lift.{v} a = lift.{u} b := by rw [←lift_lift, ←lift_lift, lift_inj] @[simp] theorem lift_min {a b : cardinal} : lift (min a b) = min (lift a) (lift b) := lift_monotone.map_min @[simp] theorem lift_max {a b : cardinal} : lift (max a b) = max (lift a) (lift b) := lift_monotone.map_max /-- The lift of a supremum is the supremum of the lifts. -/ lemma lift_Sup {s : set cardinal} (hs : bdd_above s) : lift.{u} (Sup s) = Sup (lift.{u} '' s) := begin apply ((le_cSup_iff' (bdd_above_image _ hs)).2 (λ c hc, _)).antisymm (cSup_le' _), { by_contra h, obtain ⟨d, rfl⟩ := cardinal.lift_down (not_le.1 h).le, simp_rw lift_le at h hc, rw cSup_le_iff' hs at h, exact h (λ a ha, lift_le.1 $ hc (mem_image_of_mem _ ha)) }, { rintros i ⟨j, hj, rfl⟩, exact lift_le.2 (le_cSup hs hj) }, end /-- The lift of a supremum is the supremum of the lifts. -/ lemma lift_supr {ι : Type v} {f : ι → cardinal.{w}} (hf : bdd_above (range f)) : lift.{u} (supr f) = ⨆ i, lift.{u} (f i) := by rw [supr, supr, lift_Sup hf, ←range_comp] /-- To prove that the lift of a supremum is bounded by some cardinal `t`, it suffices to show that the lift of each cardinal is bounded by `t`. -/ lemma lift_supr_le {ι : Type v} {f : ι → cardinal.{w}} {t : cardinal} (hf : bdd_above (range f)) (w : ∀ i, lift.{u} (f i) ≤ t) : lift.{u} (supr f) ≤ t := by { rw lift_supr hf, exact csupr_le' w } @[simp] lemma lift_supr_le_iff {ι : Type v} {f : ι → cardinal.{w}} (hf : bdd_above (range f)) {t : cardinal} : lift.{u} (supr f) ≤ t ↔ ∀ i, lift.{u} (f i) ≤ t := by { rw lift_supr hf, exact csupr_le_iff' (bdd_above_range_comp hf _) } universes v' w' /-- To prove an inequality between the lifts to a common universe of two different supremums, it suffices to show that the lift of each cardinal from the smaller supremum if bounded by the lift of some cardinal from the larger supremum. -/ lemma lift_supr_le_lift_supr {ι : Type v} {ι' : Type v'} {f : ι → cardinal.{w}} {f' : ι' → cardinal.{w'}} (hf : bdd_above (range f)) (hf' : bdd_above (range f')) {g : ι → ι'} (h : ∀ i, lift.{w'} (f i) ≤ lift.{w} (f' (g i))) : lift.{w'} (supr f) ≤ lift.{w} (supr f') := begin rw [lift_supr hf, lift_supr hf'], exact csupr_mono' (bdd_above_range_comp hf' _) (λ i, ⟨_, h i⟩) end /-- A variant of `lift_supr_le_lift_supr` with universes specialized via `w = v` and `w' = v'`. This is sometimes necessary to avoid universe unification issues. -/ lemma lift_supr_le_lift_supr' {ι : Type v} {ι' : Type v'} {f : ι → cardinal.{v}} {f' : ι' → cardinal.{v'}} (hf : bdd_above (range f)) (hf' : bdd_above (range f')) (g : ι → ι') (h : ∀ i, lift.{v'} (f i) ≤ lift.{v} (f' (g i))) : lift.{v'} (supr f) ≤ lift.{v} (supr f') := lift_supr_le_lift_supr hf hf' h /-- `ℵ₀` is the smallest infinite cardinal. -/ def aleph_0 : cardinal.{u} := lift (#ℕ) localized "notation `ℵ₀` := cardinal.aleph_0" in cardinal lemma mk_nat : #ℕ = ℵ₀ := (lift_id _).symm theorem aleph_0_ne_zero : ℵ₀ ≠ 0 := mk_ne_zero _ theorem aleph_0_pos : 0 < ℵ₀ := pos_iff_ne_zero.2 aleph_0_ne_zero @[simp] theorem lift_aleph_0 : lift ℵ₀ = ℵ₀ := lift_lift _ @[simp] theorem aleph_0_le_lift {c : cardinal.{u}} : ℵ₀ ≤ lift.{v} c ↔ ℵ₀ ≤ c := by rw [←lift_aleph_0, lift_le] @[simp] theorem lift_le_aleph_0 {c : cardinal.{u}} : lift.{v} c ≤ ℵ₀ ↔ c ≤ ℵ₀ := by rw [←lift_aleph_0, lift_le] /-! ### Properties about the cast from `ℕ` -/ @[simp] theorem mk_fin (n : ℕ) : #(fin n) = n := by simp @[simp] theorem lift_nat_cast (n : ℕ) : lift.{u} (n : cardinal.{v}) = n := by induction n; simp * @[simp] lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{v} a = n ↔ a = n := lift_injective.eq_iff' (lift_nat_cast n) @[simp] lemma nat_eq_lift_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{v} a ↔ (n : cardinal) = a := by rw [←lift_nat_cast.{v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (#(fin n)) = n := by simp lemma mk_coe_finset {α : Type u} {s : finset α} : #s = ↑(finset.card s) := by simp lemma mk_finset_of_fintype [fintype α] : #(finset α) = 2 ^ℕ fintype.card α := by simp theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ #α := begin rw (_ : (s.card : cardinal) = #s), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.mk_fintype, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [pow_succ', power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := begin rw [←lift_mk_fin, ←lift_mk_fin, lift_le], exact ⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf, λ h, ⟨(fin.cast_le h).to_embedding⟩⟩ end @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, ←not_le] instance : char_zero cardinal := ⟨strict_mono.injective $ λ m n, nat_cast_lt.2⟩ theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := nat.cast_inj lemma nat_cast_injective : injective (coe : ℕ → cardinal) := nat.cast_injective @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := (add_one_le_succ _).antisymm (succ_le_of_lt $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ (0 : cardinal) = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine le_of_lt_succ (lt_of_not_ge $ λ hn, _), rw [←cardinal.nat_succ, ←lift_mk_fin n.succ] at hn, cases hn with f, refine (H $ finset.univ.map f).not_lt _, rw [finset.card_map, ←fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := begin rw [←succ_le_iff, (by norm_cast : succ (1 : cardinal) = 2)] at hb, exact (cantor a).trans_le (power_le_power_right hb) end theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [←succ_zero, succ_le_iff] 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_aleph_0 (n : ℕ) : (n : cardinal.{u}) < ℵ₀ := succ_le_iff.1 begin rw [←nat_succ, ←lift_mk_fin, aleph_0, lift_mk_le.{0 0 u}], exact ⟨⟨coe, λ a b, fin.ext⟩⟩ end @[simp] theorem one_lt_aleph_0 : 1 < ℵ₀ := by simpa using nat_lt_aleph_0 1 theorem one_le_aleph_0 : 1 ≤ ℵ₀ := one_lt_aleph_0.le theorem lt_aleph_0 {c : cardinal} : c < ℵ₀ ↔ ∃ 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 : S.finite, { lift S to finset ℕ using this, simp }, contrapose! h', haveI := infinite.to_subtype h', exact ⟨infinite.nat_embedding S⟩ end, λ ⟨n, e⟩, e.symm ▸ nat_lt_aleph_0 _⟩ theorem aleph_0_le {c : cardinal} : ℵ₀ ≤ c ↔ ∀ n : ℕ, ↑n ≤ c := ⟨λ h n, (nat_lt_aleph_0 _).le.trans h, λ h, le_of_not_lt $ λ hn, begin rcases lt_aleph_0.1 hn with ⟨n, rfl⟩, exact (nat.lt_succ_self _).not_le (nat_cast_le.1 (h (n+1))) end⟩ theorem mk_eq_nat_iff {α : Type u} {n : ℕ} : #α = n ↔ nonempty (α ≃ fin n) := by rw [← lift_mk_fin, ← lift_uzero (#α), lift_mk_eq'] theorem lt_aleph_0_iff_finite {α : Type u} : #α < ℵ₀ ↔ finite α := by simp only [lt_aleph_0, mk_eq_nat_iff, finite_iff_exists_equiv_fin] theorem lt_aleph_0_iff_fintype {α : Type u} : #α < ℵ₀ ↔ nonempty (fintype α) := lt_aleph_0_iff_finite.trans (finite_iff_nonempty_fintype _) theorem lt_aleph_0_of_finite (α : Type u) [finite α] : #α < ℵ₀ := lt_aleph_0_iff_finite.2 ‹_› theorem lt_aleph_0_iff_set_finite {α} {S : set α} : #S < ℵ₀ ↔ S.finite := lt_aleph_0_iff_finite.trans finite_coe_iff alias lt_aleph_0_iff_set_finite ↔ _ _root_.set.finite.lt_aleph_0 instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < ℵ₀, λ x hx, let ⟨n, hn⟩ := lt_aleph_0.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_aleph_0 {a b : cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a + b < ℵ₀ := match a, b, lt_aleph_0.1 ha, lt_aleph_0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_aleph_0 end lemma add_lt_aleph_0_iff {a b : cardinal} : a + b < ℵ₀ ↔ a < ℵ₀ ∧ b < ℵ₀ := ⟨λ h, ⟨(self_le_add_right _ _).trans_lt h, (self_le_add_left _ _).trans_lt h⟩, λ ⟨h1, h2⟩, add_lt_aleph_0 h1 h2⟩ lemma aleph_0_le_add_iff {a b : cardinal} : ℵ₀ ≤ a + b ↔ ℵ₀ ≤ a ∨ ℵ₀ ≤ b := by simp only [←not_lt, add_lt_aleph_0_iff, not_and_distrib] /-- See also `cardinal.nsmul_lt_aleph_0_iff_of_ne_zero` if you already have `n ≠ 0`. -/ lemma nsmul_lt_aleph_0_iff {n : ℕ} {a : cardinal} : n • a < ℵ₀ ↔ n = 0 ∨ a < ℵ₀ := begin cases n, { simpa using nat_lt_aleph_0 0 }, simp only [nat.succ_ne_zero, false_or], induction n with n ih, { simp }, rw [succ_nsmul, add_lt_aleph_0_iff, ih, and_self] end /-- See also `cardinal.nsmul_lt_aleph_0_iff` for a hypothesis-free version. -/ lemma nsmul_lt_aleph_0_iff_of_ne_zero {n : ℕ} {a : cardinal} (h : n ≠ 0) : n • a < ℵ₀ ↔ a < ℵ₀ := nsmul_lt_aleph_0_iff.trans $ or_iff_right h theorem mul_lt_aleph_0 {a b : cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a * b < ℵ₀ := match a, b, lt_aleph_0.1 ha, lt_aleph_0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_aleph_0 end lemma mul_lt_aleph_0_iff {a b : cardinal} : a * b < ℵ₀ ↔ a = 0 ∨ b = 0 ∨ a < ℵ₀ ∧ b < ℵ₀ := begin refine ⟨λ h, _, _⟩, { by_cases ha : a = 0, { exact or.inl ha }, right, by_cases hb : b = 0, { exact or.inl hb }, right, rw [←ne, ←one_le_iff_ne_zero] at ha hb, split, { rw ←mul_one a, refine (mul_le_mul' le_rfl hb).trans_lt h }, { rw ←one_mul b, refine (mul_le_mul' ha le_rfl).trans_lt h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_aleph_0, aleph_0_pos, zero_mul, mul_zero] end /-- See also `cardinal.aleph_0_le_mul_iff`. -/ lemma aleph_0_le_mul_iff {a b : cardinal} : ℵ₀ ≤ a * b ↔ a ≠ 0 ∧ b ≠ 0 ∧ (ℵ₀ ≤ a ∨ ℵ₀ ≤ b) := let h := (@mul_lt_aleph_0_iff a b).not in by rwa [not_lt, not_or_distrib, not_or_distrib, not_and_distrib, not_lt, not_lt] at h /-- See also `cardinal.aleph_0_le_mul_iff'`. -/ lemma aleph_0_le_mul_iff' {a b : cardinal.{u}} : ℵ₀ ≤ a * b ↔ a ≠ 0 ∧ ℵ₀ ≤ b ∨ ℵ₀ ≤ a ∧ b ≠ 0 := begin have : ∀ {a : cardinal.{u}}, ℵ₀ ≤ a → a ≠ 0, from λ a, ne_bot_of_le_ne_bot aleph_0_ne_zero, simp only [aleph_0_le_mul_iff, and_or_distrib_left, and_iff_right_of_imp this, @and.left_comm (a ≠ 0)], simp only [and.comm, or.comm] end lemma mul_lt_aleph_0_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < ℵ₀ ↔ a < ℵ₀ ∧ b < ℵ₀ := by simp [mul_lt_aleph_0_iff, ha, hb] theorem power_lt_aleph_0 {a b : cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a ^ b < ℵ₀ := match a, b, lt_aleph_0.1 ha, lt_aleph_0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_aleph_0 end lemma eq_one_iff_unique {α : Type*} : #α = 1 ↔ subsingleton α ∧ nonempty α := calc #α = 1 ↔ #α ≤ 1 ∧ 1 ≤ #α : le_antisymm_iff ... ↔ subsingleton α ∧ nonempty α : le_one_iff_subsingleton.and (one_le_iff_ne_zero.trans mk_ne_zero_iff) theorem infinite_iff {α : Type u} : infinite α ↔ ℵ₀ ≤ #α := by rw [← not_lt, lt_aleph_0_iff_finite, not_finite_iff_infinite] @[simp] lemma aleph_0_le_mk (α : Type u) [infinite α] : ℵ₀ ≤ #α := infinite_iff.1 ‹_› lemma encodable_iff {α : Type u} : nonempty (encodable α) ↔ #α ≤ ℵ₀ := ⟨λ ⟨h⟩, ⟨(@encodable.encode' α h).trans equiv.ulift.symm.to_embedding⟩, λ ⟨h⟩, ⟨encodable.of_inj _ (h.trans equiv.ulift.to_embedding).injective⟩⟩ @[simp] lemma mk_le_aleph_0 [encodable α] : #α ≤ ℵ₀ := encodable_iff.1 ⟨‹_›⟩ lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ #α = ℵ₀ := ⟨λ ⟨h⟩, mk_congr ((@denumerable.eqv α h).trans equiv.ulift.symm), λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ @[simp] lemma mk_denumerable (α : Type u) [denumerable α] : #α = ℵ₀ := denumerable_iff.1 ⟨‹_›⟩ @[simp] lemma mk_set_le_aleph_0 (s : set α) : #s ≤ ℵ₀ ↔ s.countable := begin rw [set.countable_iff_exists_injective], split, { rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ }, { rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩ } end @[simp] lemma mk_subtype_le_aleph_0 (p : α → Prop) : #{x // p x} ≤ ℵ₀ ↔ {x | p x}.countable := mk_set_le_aleph_0 _ @[simp] lemma aleph_0_add_aleph_0 : ℵ₀ + ℵ₀ = ℵ₀ := mk_denumerable _ lemma aleph_0_mul_aleph_0 : ℵ₀ * ℵ₀ = ℵ₀ := mk_denumerable _ @[simp] lemma add_le_aleph_0 {c₁ c₂ : cardinal} : c₁ + c₂ ≤ ℵ₀ ↔ c₁ ≤ ℵ₀ ∧ c₂ ≤ ℵ₀ := ⟨λ h, ⟨le_self_add.trans h, le_add_self.trans h⟩, λ h, aleph_0_add_aleph_0 ▸ add_le_add h.1 h.2⟩ /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to 0. -/ def to_nat : zero_hom cardinal ℕ := ⟨λ c, if h : c < aleph_0.{v} then classical.some (lt_aleph_0.1 h) else 0, begin have h : 0 < ℵ₀ := nat_lt_aleph_0 0, rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_aleph_0.1 h), nat.cast_zero], end⟩ lemma to_nat_apply_of_lt_aleph_0 {c : cardinal} (h : c < ℵ₀) : c.to_nat = classical.some (lt_aleph_0.1 h) := dif_pos h lemma to_nat_apply_of_aleph_0_le {c : cardinal} (h : ℵ₀ ≤ c) : c.to_nat = 0 := dif_neg h.not_lt lemma cast_to_nat_of_lt_aleph_0 {c : cardinal} (h : c < ℵ₀) : ↑c.to_nat = c := by rw [to_nat_apply_of_lt_aleph_0 h, ← classical.some_spec (lt_aleph_0.1 h)] lemma cast_to_nat_of_aleph_0_le {c : cardinal} (h : ℵ₀ ≤ c) : ↑c.to_nat = (0 : cardinal) := by rw [to_nat_apply_of_aleph_0_le h, nat.cast_zero] lemma to_nat_le_iff_le_of_lt_aleph_0 {c d : cardinal} (hc : c < ℵ₀) (hd : d < ℵ₀) : c.to_nat ≤ d.to_nat ↔ c ≤ d := by rw [←nat_cast_le, cast_to_nat_of_lt_aleph_0 hc, cast_to_nat_of_lt_aleph_0 hd] lemma to_nat_lt_iff_lt_of_lt_aleph_0 {c d : cardinal} (hc : c < ℵ₀) (hd : d < ℵ₀) : c.to_nat < d.to_nat ↔ c < d := by rw [←nat_cast_lt, cast_to_nat_of_lt_aleph_0 hc, cast_to_nat_of_lt_aleph_0 hd] lemma to_nat_le_of_le_of_lt_aleph_0 {c d : cardinal} (hd : d < ℵ₀) (hcd : c ≤ d) : c.to_nat ≤ d.to_nat := (to_nat_le_iff_le_of_lt_aleph_0 (hcd.trans_lt hd) hd).mpr hcd lemma to_nat_lt_of_lt_of_lt_aleph_0 {c d : cardinal} (hd : d < ℵ₀) (hcd : c < d) : c.to_nat < d.to_nat := (to_nat_lt_iff_lt_of_lt_aleph_0 (hcd.trans hd) hd).mpr hcd @[simp] lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n := begin rw [to_nat_apply_of_lt_aleph_0 (nat_lt_aleph_0 n), ← nat_cast_inj], exact (classical.some_spec (lt_aleph_0.1 (nat_lt_aleph_0 n))).symm, end /-- `to_nat` has a right-inverse: coercion. -/ lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective @[simp] lemma mk_to_nat_of_infinite [h : infinite α] : (#α).to_nat = 0 := dif_neg (infinite_iff.1 h).not_lt @[simp] theorem aleph_0_to_nat : to_nat ℵ₀ = 0 := to_nat_apply_of_aleph_0_le le_rfl lemma mk_to_nat_eq_card [fintype α] : (#α).to_nat = fintype.card α := by simp @[simp] lemma zero_to_nat : to_nat 0 = 0 := by rw [←to_nat_cast 0, nat.cast_zero] @[simp] lemma one_to_nat : to_nat 1 = 1 := by rw [←to_nat_cast 1, nat.cast_one] @[simp] lemma to_nat_eq_one {c : cardinal} : to_nat c = 1 ↔ c = 1 := ⟨λ h, (cast_to_nat_of_lt_aleph_0 (lt_of_not_ge (one_ne_zero ∘ h.symm.trans ∘ to_nat_apply_of_aleph_0_le))).symm.trans ((congr_arg coe h).trans nat.cast_one), λ h, (congr_arg to_nat h).trans one_to_nat⟩ lemma to_nat_eq_one_iff_unique {α : Type*} : (#α).to_nat = 1 ↔ subsingleton α ∧ nonempty α := to_nat_eq_one.trans eq_one_iff_unique @[simp] lemma to_nat_lift (c : cardinal.{v}) : (lift.{u v} c).to_nat = c.to_nat := begin apply nat_cast_injective, cases lt_or_ge c ℵ₀ with hc hc, { rw [cast_to_nat_of_lt_aleph_0, ←lift_nat_cast, cast_to_nat_of_lt_aleph_0 hc], rwa [←lift_aleph_0, lift_lt] }, { rw [cast_to_nat_of_aleph_0_le, ←lift_nat_cast, cast_to_nat_of_aleph_0_le hc, lift_zero], rwa [←lift_aleph_0, lift_le] }, end lemma to_nat_congr {β : Type v} (e : α ≃ β) : (#α).to_nat = (#β).to_nat := by rw [←to_nat_lift, lift_mk_eq.mpr ⟨e⟩, to_nat_lift] @[simp] lemma to_nat_mul (x y : cardinal) : (x * y).to_nat = x.to_nat * y.to_nat := begin rcases eq_or_ne x 0 with rfl | hx1, { rw [zero_mul, zero_to_nat, zero_mul] }, rcases eq_or_ne y 0 with rfl | hy1, { rw [mul_zero, zero_to_nat, mul_zero] }, cases lt_or_le x ℵ₀ with hx2 hx2, { cases lt_or_le y ℵ₀ with hy2 hy2, { lift x to ℕ using hx2, lift y to ℕ using hy2, rw [← nat.cast_mul, to_nat_cast, to_nat_cast, to_nat_cast] }, { rw [to_nat_apply_of_aleph_0_le hy2, mul_zero, to_nat_apply_of_aleph_0_le], exact aleph_0_le_mul_iff'.2 (or.inl ⟨hx1, hy2⟩) } }, { rw [to_nat_apply_of_aleph_0_le hx2, zero_mul, to_nat_apply_of_aleph_0_le], exact aleph_0_le_mul_iff'.2 (or.inr ⟨hx2, hy1⟩) }, end @[simp] lemma to_nat_add_of_lt_aleph_0 {a : cardinal.{u}} {b : cardinal.{v}} (ha : a < ℵ₀) (hb : b < ℵ₀) : ((lift.{v u} a) + (lift.{u v} b)).to_nat = a.to_nat + b.to_nat := begin apply cardinal.nat_cast_injective, replace ha : (lift.{v u} a) < ℵ₀ := by { rw ←lift_aleph_0, exact lift_lt.2 ha }, replace hb : (lift.{u v} b) < ℵ₀ := by { rw ←lift_aleph_0, exact lift_lt.2 hb }, rw [nat.cast_add, ←to_nat_lift.{v u} a, ←to_nat_lift.{u v} b, cast_to_nat_of_lt_aleph_0 ha, cast_to_nat_of_lt_aleph_0 hb, cast_to_nat_of_lt_aleph_0 (add_lt_aleph_0 ha hb)] end /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to `⊤`. -/ def to_part_enat : cardinal →+ part_enat := { to_fun := λ c, if c < ℵ₀ then c.to_nat else ⊤, map_zero' := by simp [if_pos (zero_lt_one.trans one_lt_aleph_0)], map_add' := λ x y, begin by_cases hx : x < ℵ₀, { obtain ⟨x0, rfl⟩ := lt_aleph_0.1 hx, by_cases hy : y < ℵ₀, { obtain ⟨y0, rfl⟩ := lt_aleph_0.1 hy, simp only [add_lt_aleph_0 hx hy, hx, hy, to_nat_cast, if_true], rw [← nat.cast_add, to_nat_cast, nat.cast_add] }, { rw [if_neg hy, if_neg, part_enat.add_top], contrapose! hy, apply le_add_self.trans_lt hy } }, { rw [if_neg hx, if_neg, part_enat.top_add], contrapose! hx, apply le_self_add.trans_lt hx }, end } lemma to_part_enat_apply_of_lt_aleph_0 {c : cardinal} (h : c < ℵ₀) : c.to_part_enat = c.to_nat := if_pos h lemma to_part_enat_apply_of_aleph_0_le {c : cardinal} (h : ℵ₀ ≤ c) : c.to_part_enat = ⊤ := if_neg h.not_lt @[simp] lemma to_part_enat_cast (n : ℕ) : cardinal.to_part_enat n = n := by rw [to_part_enat_apply_of_lt_aleph_0 (nat_lt_aleph_0 n), to_nat_cast] @[simp] lemma mk_to_part_enat_of_infinite [h : infinite α] : (#α).to_part_enat = ⊤ := to_part_enat_apply_of_aleph_0_le (infinite_iff.1 h) @[simp] theorem aleph_0_to_part_enat : to_part_enat ℵ₀ = ⊤ := to_part_enat_apply_of_aleph_0_le le_rfl lemma to_part_enat_surjective : surjective to_part_enat := λ x, part_enat.cases_on x ⟨ℵ₀, to_part_enat_apply_of_aleph_0_le le_rfl⟩ $ λ n, ⟨n, to_part_enat_cast n⟩ lemma mk_to_part_enat_eq_coe_card [fintype α] : (#α).to_part_enat = fintype.card α := by simp lemma mk_int : #ℤ = ℵ₀ := mk_denumerable ℤ lemma mk_pnat : #ℕ+ = ℵ₀ := mk_denumerable ℕ+ /-- **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 haveI : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ mk_ne_zero_iff.1 _⟩, rw mk_out, exact (H i).ne_bot }, 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, { intro i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, (H i).not_le _, 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 : #empty = 0 := mk_eq_zero _ @[simp] theorem mk_pempty : #pempty = 0 := mk_eq_zero _ @[simp] theorem mk_punit : #punit = 1 := mk_eq_one punit theorem mk_unit : #unit = 1 := mk_punit @[simp] theorem mk_singleton {α : Type u} (x : α) : #({x} : set α) = 1 := mk_eq_one _ @[simp] theorem mk_plift_true : #(plift true) = 1 := mk_eq_one _ @[simp] theorem mk_plift_false : #(plift false) = 0 := mk_eq_zero _ @[simp] theorem mk_vector (α : Type u) (n : ℕ) : #(vector α n) = (#α) ^ℕ n := (mk_congr (equiv.vector_equiv_fin α n)).trans $ by simp theorem mk_list_eq_sum_pow (α : Type u) : #(list α) = sum (λ n : ℕ, (#α) ^ℕ n) := calc #(list α) = #(Σ n, vector α n) : mk_congr (equiv.sigma_fiber_equiv list.length).symm ... = sum (λ n : ℕ, (#α) ^ℕ n) : by simp theorem mk_quot_le {α : Type u} {r : α → α → Prop} : #(quot r) ≤ #α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : #(quotient s) ≤ #α := mk_quot_le theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : #(subtype p) ≤ #(subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : #(∅ : set α) = 0 := mk_eq_zero _ lemma mk_emptyc_iff {α : Type u} {s : set α} : #s = 0 ↔ s = ∅ := begin split, { intro h, rw mk_eq_zero_iff at h, exact eq_empty_iff_forall_not_mem.2 (λ x hx, h.elim' ⟨x, hx⟩) }, { rintro rfl, exact mk_emptyc _ } end @[simp] theorem mk_univ {α : Type u} : #(@univ α) = #α := mk_congr (equiv.set.univ α) theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : #(f '' s) ≤ #s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{u} (#(f '' s)) ≤ lift.{v} (#s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : #(range f) ≤ #α := mk_le_of_surjective surjective_onto_range theorem mk_range_le_lift {α : Type u} {β : Type v} {f : α → β} : lift.{u} (#(range f)) ≤ lift.{v} (#α) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_range⟩ lemma mk_range_eq (f : α → β) (h : injective f) : #(range f) = #α := mk_congr ((equiv.of_injective f h).symm) lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{u} (#(range f)) = lift.{v} (#α) := lift_mk_eq'.mpr ⟨(equiv.of_injective f hf).symm⟩ lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{max u w} (# (range f)) = lift.{max v w} (# α) := lift_mk_eq.mpr ⟨(equiv.of_injective f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : #(f '' s) = #s := mk_congr ((equiv.set.image f s hf).symm) theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : #(⋃ i, f i) ≤ sum (λ i, #(f i)) := calc #(⋃ i, f i) ≤ #(Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, #(f i)) : mk_sigma _ theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : #(⋃ i, f i) = sum (λ i, #(f i)) := calc #(⋃ i, f i) = #(Σ i, f i) : mk_congr (set.Union_eq_sigma_of_disjoint h) ... = sum (λi, #(f i)) : mk_sigma _ lemma mk_Union_le {α ι : Type u} (f : ι → set α) : #(⋃ i, f i) ≤ #ι * ⨆ i, #(f i) := mk_Union_le_sum_mk.trans (sum_le_supr _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : #(⋃₀ A) ≤ #A * ⨆ s : A, #s := by { rw sUnion_eq_Union, apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : #(⋃ x ∈ s, A x) ≤ #s * ⨆ x : s, #(A x.1) := by { rw bUnion_eq_Union, apply mk_Union_le } lemma finset_card_lt_aleph_0 (s : finset α) : #(↑s : set α) < ℵ₀ := lt_aleph_0_of_finite _ theorem mk_eq_nat_iff_finset {α} {s : set α} {n : ℕ} : #s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n := begin split, { intro h, lift s to finset α using lt_aleph_0_iff_set_finite.1 (h.symm ▸ nat_lt_aleph_0 n), simpa using h }, { rintro ⟨t, rfl, rfl⟩, exact mk_coe_finset } end theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : #(S ∪ T : set α) + #(S ∩ T : set α) = #S + #T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : #(S ∪ T : set α) ≤ #S + #T := @mk_union_add_mk_inter α S T ▸ self_le_add_right (#(S ∪ T : set α)) (#(S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : #(S ∪ T : set α) = #S + #T := quot.sound ⟨equiv.set.union H⟩ theorem mk_insert {α : Type u} {s : set α} {a : α} (h : a ∉ s) : #(insert a s : set α) = #s + 1 := by { rw [← union_singleton, mk_union_of_disjoint, mk_singleton], simpa } lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := mk_congr (equiv.set.sum_compl s) lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : #s ≤ #t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀ x, p x → q x) : #{x // p x} ≤ #{x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_union_le_aleph_0 {α} {P Q : set α} : #((P ∪ Q : set α)) ≤ ℵ₀ ↔ #P ≤ ℵ₀ ∧ #Q ≤ ℵ₀ := by simp lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{u} (#(f '' s)) = lift.{v} (#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.{u} (#(f '' s)) = lift.{v} (#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) : #(f '' s) = #s := mk_congr ((equiv.set.image_of_inj_on f s h).symm) lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : #{a : α // p (e a)} = #{b : β // p b} := mk_congr (equiv.subtype_equiv_of_subtype e) lemma mk_sep (s : set α) (t : α → Prop) : #({ x ∈ s | t x } : set α) = #{ x : s | t x.1 } := mk_congr (equiv.set.sep s t) lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{v} (#(f ⁻¹' s)) ≤ lift.{u} (#s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{u} (#s) ≤ lift.{v} (#(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.{v} (#(f ⁻¹' s)) = lift.{u} (#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) : #(f ⁻¹' s) ≤ #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) : #s ≤ #(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) : #(f ⁻¹' s) = #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.{u} (#t) ≤ lift.{v} (#({ 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) : #t ≤ #({ 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 ≤ #s ↔ ∃ p : set α, p ⊆ s ∧ #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 lemma two_le_iff : (2 : cardinal) ≤ #α ↔ ∃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_iff, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ #α ↔ ∃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 lemma exists_not_mem_of_length_le {α : Type*} (l : list α) (h : ↑l.length < # α) : ∃ (z : α), z ∉ l := begin contrapose! h, calc # α = # (set.univ : set α) : mk_univ.symm ... ≤ # l.to_finset : mk_le_mk_of_subset (λ x _, list.mem_to_finset.mpr (h x)) ... = l.to_finset.card : cardinal.mk_coe_finset ... ≤ l.length : cardinal.nat_cast_le.mpr (list.to_finset_card_le l), end lemma three_le {α : Type*} (h : 3 ≤ # α) (x : α) (y : α) : ∃ (z : α), z ≠ x ∧ z ≠ y := begin have : ↑(3 : ℕ) ≤ # α, simpa using h, have : ↑(2 : ℕ) < # α, rwa [← succ_le_iff, ← cardinal.nat_succ], have := exists_not_mem_of_length_le [x, y] this, simpa [not_or_distrib] using this, end /-- The function `a ^< b`, defined as the supremum of `a ^ c` for `c < b`. -/ def powerlt (a b : cardinal.{u}) : cardinal.{u} := ⨆ c : Iio b, a ^ c infix ` ^< `:80 := powerlt lemma le_powerlt {b c : cardinal.{u}} (a) (h : c < b) : a ^ c ≤ a ^< b := begin apply @le_csupr _ _ _ (λ y : Iio b, a ^ y) _ ⟨c, h⟩, rw ←image_eq_range, exact bdd_above_image.{u u} _ bdd_above_Iio end lemma powerlt_le {a b c : cardinal.{u}} : a ^< b ≤ c ↔ ∀ x < b, a ^ x ≤ c := begin rw [powerlt, csupr_le_iff'], { simp }, { rw ←image_eq_range, exact bdd_above_image.{u u} _ bdd_above_Iio } end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := powerlt_le.2 $ λ x hx, le_powerlt a $ hx.trans_le h lemma powerlt_mono_left (a) : monotone (λ c, a ^< c) := λ b c, powerlt_le_powerlt_left lemma powerlt_succ {a b : cardinal} (h : a ≠ 0) : a ^< (succ b) = a ^ b := (powerlt_le.2 $ λ c h', power_le_power_left h $ le_of_lt_succ h').antisymm $ le_powerlt a (lt_succ b) lemma powerlt_min {a b c : cardinal} : a ^< min b c = min (a ^< b) (a ^< c) := (powerlt_mono_left a).map_min lemma powerlt_max {a b c : cardinal} : a ^< max b c = max (a ^< b) (a ^< c) := (powerlt_mono_left a).map_max lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply (powerlt_le.2 (λ c hc, zero_power_le _)).antisymm, rw ←power_zero, exact le_powerlt 0 (pos_iff_ne_zero.2 h) end @[simp] lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := begin convert cardinal.supr_of_empty _, exact subtype.is_empty_of_false (λ x, (cardinal.zero_le _).not_lt), end end cardinal
84b0b7c29ec556b9327c8bacfd0c8c1642d619ae
46125763b4dbf50619e8846a1371029346f4c3db
/src/measure_theory/measurable_space.lean
7a49dc4b5584fc677c70cb39d962c3e3643b5259
[ "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
44,027
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 Measurable spaces -- σ-algberas -/ import data.set.disjointed order.galois_connection data.set.countable /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set α form a complete lattice. Here we order σ-algebras by writing m₁ ≤ m₂ if every set which is m₁-measurable is also m₂-measurable (that is, m₁ is a subset of m₂). In particular, any collection of subsets of α generates a smallest σ-algebra which contains all of them. A function f : α → β induces a Galois connection between the lattices of σ-algebras on α and β. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose s is a collection of subsets of α such that the intersection of two members of s belongs to s whenever it is nonempty. Let m be the σ-algebra generated by s. In order to check that a predicate C holds on every member of m, it suffices to check that C holds on the members of s and that C is preserved by complementation and *disjoint* countable unions. ## Implementation notes Measurability of a function f : α → β between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, measurable function, dynkin system -/ local attribute [instance] classical.prop_decidable open set lattice encodable open_locale classical universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort x} {s t u : set α} structure measurable_space (α : Type u) := (is_measurable : set α → Prop) (is_measurable_empty : is_measurable ∅) (is_measurable_compl : ∀s, is_measurable s → is_measurable (- s)) (is_measurable_Union : ∀f:ℕ → set α, (∀i, is_measurable (f i)) → is_measurable (⋃i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable (-s) := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.compl_iff : is_measurable (-s) ↔ is_measurable s := ⟨λ h, by simpa using h.compl, is_measurable.compl⟩ lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma encodable.Union_decode2 {α} [encodable β] (f : β → set α) : (⋃ b, f b) = ⋃ (i : ℕ) (b ∈ decode2 β i), f b := ext $ by simp [mem_decode2, exists_swap] @[elab_as_eliminator] lemma encodable.Union_decode2_cases {α} [encodable β] {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 lemma is_measurable.Union [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by rw encodable.Union_decode2; exact ‹measurable_space α›.is_measurable_Union (λ n, ⋃ b ∈ decode2 β n, f b) (λ n, encodable.Union_decode2_cases is_measurable.empty h) lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋃b∈s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋃₀ s) := by rw sUnion_eq_bUnion; exact is_measurable.bUnion hs h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by by_cases p; simp [h, hf, is_measurable.empty] lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := is_measurable.compl_iff.1 $ by rw compl_Inter; exact is_measurable.Union (λ b, (h b).compl) lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋂b∈s, f b) := is_measurable.compl_iff.1 $ by rw compl_bInter; exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋂₀ s) := by rw sInter_eq_bInter; exact is_measurable.bInter hs h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := by by_cases p; simp [h, hf, is_measurable.univ] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by rw union_eq_Union; exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by rw inter_eq_compl_compl_union_compl; exact (h₁.compl.union h₂.compl).compl lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl lemma is_measurable.sub {s₁ s₂ : set α} : is_measurable s₁ → is_measurable s₂ → is_measurable (s₁ - s₂) := is_measurable.diff lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ end @[ext] lemma measurable_space.ext : ∀{m₁ m₂ : measurable_space α}, (∀s:set α, m₁.is_measurable s ↔ m₂.is_measurable s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λm₁ m₂, m₁.is_measurable ≤ m₂.is_measurable, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀u∈s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀s, generate_measurable s → generate_measurable (-s) | union : ∀f:ℕ → set α, (∀n, generate_measurable (f n)) → generate_measurable (⋃i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable := generate_measurable s, is_measurable_empty := generate_measurable.empty s, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀t∈s, m.is_measurable t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} {m : measurable_space α} : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable t} = g) : measurable_space α := { is_measurable := λs, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by rw [← hs] {occs := occurrences.pos [1] }; refl def gi_generate_from : galois_insertion (@generate_from α) (λm, {t | @is_measurable α m t}) := { gc := assume s m, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λg hg, measurable_space.mk_of_closure g $ le_antisymm hg $ generate_from_le_iff.1 $ le_refl _, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable := λs, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (assume s, s.symm ▸ @is_measurable_empty _ ⊥) (assume s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂m∈ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λm, {s | @is_measurable _ m s }) (infi m) ↔ _, by rw (@gi_generate_from α).gc.u_infi; simp; refl theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable ∪ m₂.is_measurable) s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable (⋃₀ (measurable_space.is_measurable '' ms)) s := begin change @is_measurable _ (generate_from _) _ ↔ _, dsimp [generate_from], rw (show (⨆ (b : measurable_space α) (H : b ∈ ms), set_of (is_measurable b)) = (⋃₀(is_measurable '' ms)), { ext, simp only [exists_prop, mem_Union, sUnion_image, mem_set_of_eq], refl, }) end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable (⋃i, (m i).is_measurable) s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable := λs, m.is_measurable $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by rw [preimage_Union]; exact m.is_measurable_Union _ hf } @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable := λs, ∃s', m.is_measurable s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨-s', m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃i, s' i, m.is_measurable_Union _ (λi, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥:measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} :(⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤:measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [m₁ : measurable_space α] [m₂ : measurable_space β] (f : α → β) : Prop := m₂ ≤ m₁.map f lemma measurable_id [measurable_space α] : measurable (@id α) := le_refl _ lemma measurable.preimage [measurable_space α] [measurable_space β] {f : α → β} (hf : measurable f) {s : set β} : is_measurable s → is_measurable (f ⁻¹' s) := hf _ lemma measurable.comp [measurable_space α] [measurable_space β] [measurable_space γ] {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := le_trans hg $ map_mono hf lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀t∈s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := generate_from_le h lemma measurable.if [measurable_space α] [measurable_space β] {p : α → Prop} {h : decidable_pred p} {f g : α → β} (hp : is_measurable {a | p a}) (hf : measurable f) (hg : measurable g) : measurable (λa, if p a then f a else g a) := λ s hs, show is_measurable {a | (if p a then f a else g a) ∈ s}, begin convert (hp.inter $ hf s hs).union (hp.compl.inter $ hg s hs), exact ext (λ a, by by_cases p a ; { rw mem_def, simp [h] }) end lemma measurable_const {α β} [measurable_space α] [measurable_space β] {a : α} : measurable (λb:β, a) := assume s hs, show is_measurable {b : β | a ∈ s}, from classical.by_cases (assume h : a ∈ s, by simp [h]; from is_measurable.univ) (assume h : a ∉ s, by simp [h]; from is_measurable.empty) lemma measurable_zero {α β} [measurable_space α] [has_zero α] [measurable_space β] : measurable (λb:β, (0:α)) := measurable_const end measurable_functions section constructions instance : measurable_space empty := ⊤ instance : measurable_space unit := ⊤ instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ lemma measurable_unit [measurable_space α] (f : unit → α) : measurable f := have f = (λu, f ()) := funext $ assume ⟨⟩, rfl, by rw this; exact measurable_const section nat lemma measurable_from_nat [measurable_space α] {f : ℕ → α} : measurable f := assume s hs, show is_measurable {n : ℕ | f n ∈ s}, from trivial lemma measurable_to_nat [measurable_space α] {f : α → ℕ} : (∀ k, is_measurable {x | f x = k}) → measurable f := begin assume h s hs, show is_measurable {x | f x ∈ s}, have : {x | f x ∈ s} = ⋃ (n ∈ s), {x | f x = n}, { ext, simp }, rw this, simp [is_measurable.Union, is_measurable.Union_Prop, h] end lemma measurable_find_greatest [measurable_space α] {p : ℕ → α → Prop} : ∀ {N}, (∀ k ≤ N, is_measurable {x | nat.find_greatest (λ n, p n x) N = k}) → measurable (λ x, nat.find_greatest (λ n, p n x) N) | 0 := assume h s hs, show is_measurable {x : α | (nat.find_greatest (λ n, p n x) 0) ∈ s}, begin by_cases h : 0 ∈ s, { convert is_measurable.univ, simp only [nat.find_greatest_zero, h] }, { convert is_measurable.empty, simp only [nat.find_greatest_zero, h], refl } end | (n + 1) := assume h, begin apply measurable_to_nat, assume k, by_cases hk : k ≤ n + 1, { exact h k hk }, { have := is_measurable.empty, rw ← set_of_false at this, convert this, funext, rw eq_false, assume h, rw ← h at hk, have := nat.find_greatest_le, contradiction } end end nat section subtype instance {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap subtype.val lemma measurable.subtype_val [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λa:α, (f a).val) := measurable.comp (measurable_space.comap_le_iff_le_map.mp (le_refl _)) hf lemma measurable.subtype_mk [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable (λa, (f a).val)) : measurable f := measurable_space.comap_le_iff_le_map.mpr $ by rw [measurable_space.map_comp]; exact hf lemma is_measurable_subtype_image [measurable_space α] {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, image_preimage_eq_inter_range, range_coe_subtype], exact is_measurable.inter hu hs end lemma measurable_of_measurable_union_cover [measurable_space α] [measurable_space β] {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λa:s, f a)) (hd : measurable (λa:t, f a)) : measurable f := assume u (hu : is_measurable u), show is_measurable (f ⁻¹' u), from begin rw show f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), by rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, range_coe_subtype, range_coe_subtype, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], exact is_measurable.union (is_measurable_subtype_image hs (hc _ hu)) (is_measurable_subtype_image ht (hd _ hu)) end end subtype section prod instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd lemma measurable.fst [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).1) := measurable.comp (measurable_space.comap_le_iff_le_map.mp le_sup_left) hf lemma measurable.snd [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).2) := measurable.comp (measurable_space.comap_le_iff_le_map.mp le_sup_right) hf lemma measurable.prod [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf₁ : measurable (λa, (f a).1)) (hf₂ : measurable (λa, (f a).2)) : measurable f := sup_le (by rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp]; exact hf₁) (by rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp]; exact hf₂) lemma measurable.prod_mk [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λa:α, (f a, g a)) := measurable.prod hf hg lemma is_measurable_set_prod [measurable_space α] [measurable_space β] {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (set.prod s t) := is_measurable.inter (measurable.fst measurable_id _ hs) (measurable.snd measurable_id _ ht) end prod section pi instance measurable_space.pi {α : Type u} {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (Πa, β a) := ⨆a, (m a).comap (λb, b a) lemma measurable_pi_apply {α : Type u} {β : α → Type v} [Πa, measurable_space (β a)] (a : α) : measurable (λf:Πa, β a, f a) := measurable_space.comap_le_iff_le_map.1 $ lattice.le_supr _ a lemma measurable_pi_lambda {α : Type u} {β : α → Type v} {γ : Type w} [Πa, measurable_space (β a)] [measurable_space γ] (f : γ → Πa, β a) (hf : ∀a, measurable (λc, f c a)) : measurable f := lattice.supr_le $ assume a, measurable_space.comap_le_iff_le_map.2 (hf a) end pi instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_inl : measurable (@sum.inl α β) := inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable_space.comap_le_iff_le_map.1 $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable_sum_rec {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : @measurable (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := measurable_sum hf hg lemma is_measurable_inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by rwa [preimage_image_eq]; exact (assume a b, sum.inl.inj), have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by rw [this]; exact is_measurable.empty⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by rw [← image_univ]; exact is_measurable_inl_image is_measurable.univ lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by rw [this]; exact is_measurable.empty, show is_measurable (sum.inr ⁻¹' _), by rwa [preimage_image_eq]; exact (assume a b, sum.inr.inj)⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by rw [← image_univ]; exact is_measurable_inr_image is_measurable.univ end sum instance {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) namespace measurable_equiv instance (α β) [measurable_space α] [measurable_space β] : has_coe_to_fun (measurable_equiv α β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : (e : α → β) = e.to_equiv := rfl def refl (α : Type*) [measurable_space α] : measurable_equiv α α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } def trans [measurable_space α] [measurable_space β] [measurable_space γ] (ab : measurable_equiv α β) (bc : measurable_equiv β γ) : measurable_equiv α γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } lemma trans_to_equiv {α β} [measurable_space α] [measurable_space β] [measurable_space γ] (e : measurable_equiv α β) (f : measurable_equiv β γ) : (e.trans f).to_equiv = e.to_equiv.trans f.to_equiv := rfl def symm [measurable_space α] [measurable_space β] (ab : measurable_equiv α β) : measurable_equiv β α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } lemma symm_to_equiv {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : e.symm.to_equiv = e.to_equiv.symm := rfl protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : measurable_equiv α β := { to_equiv := equiv.cast h, measurable_to_fun := by unfreezeI; subst h; subst hi; exact measurable_id, measurable_inv_fun := by unfreezeI; subst h; subst hi; exact measurable_id } protected lemma measurable {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : measurable (e : α → β) := e.measurable_to_fun protected lemma measurable_coe_iff {α β γ} [measurable_space α] [measurable_space β] [measurable_space γ] {f : β → γ} (e : measurable_equiv α β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λh, h.comp e.measurable) def prod_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α × γ) (β × δ) := { to_equiv := equiv.prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := measurable.prod_mk (ab.measurable_to_fun.comp (measurable.fst measurable_id)) (cd.measurable_to_fun.comp (measurable.snd measurable_id)), measurable_inv_fun := measurable.prod_mk (ab.measurable_inv_fun.comp (measurable.fst measurable_id)) (cd.measurable_inv_fun.comp (measurable.snd measurable_id)) } def prod_comm [measurable_space α] [measurable_space β] : measurable_equiv (α × β) (β × α) := { to_equiv := equiv.prod_comm α β, measurable_to_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id), measurable_inv_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id) } def sum_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α ⊕ γ) (β ⊕ δ) := { to_equiv := equiv.sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } def set.prod [measurable_space α] [measurable_space β] (s : set α) (t : set β) : measurable_equiv (set.prod s t) (s × t) := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable.prod_mk (measurable.subtype_mk $ measurable.fst $ measurable.subtype_val $ measurable_id) (measurable.subtype_mk $ measurable.snd $ measurable.subtype_val $ measurable_id), measurable_inv_fun := measurable.subtype_mk $ measurable.prod_mk (measurable.subtype_val $ measurable.fst $ measurable_id) (measurable.subtype_val $ measurable.snd $ measurable_id) } def set.univ (α : Type*) [measurable_space α] : measurable_equiv (univ : set α) α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable.subtype_val measurable_id, measurable_inv_fun := measurable.subtype_mk measurable_id } def set.singleton [measurable_space α] (a:α) : measurable_equiv ({a} : set α) unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable.subtype_mk $ show measurable (λu:unit, a), from measurable_const } noncomputable def set.image [measurable_space α] [measurable_space β] (f : α → β) (s : set α) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv s (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := begin have : measurable (λa:s, f a) := hfm.comp (measurable.subtype_val measurable_id), refine measurable.subtype_mk _, convert this, ext ⟨a, h⟩, refl end, measurable_inv_fun := assume t ⟨u, (hu : is_measurable u), eq⟩, begin clear_, subst eq, show is_measurable {x : f '' s | ((equiv.set.image f s hf).inv_fun x).val ∈ u}, have : ∀(a ∈ s) (h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λa ha h, (classical.some_spec h).2, rw show {x:f '' s | ((equiv.set.image f s hf).inv_fun x).val ∈ u} = subtype.val ⁻¹' (f '' u), by ext ⟨b, a, hbs, rfl⟩; simp [equiv.set.image, equiv.set.image_of_inj_on, hf, this _ hbs], exact (measurable.subtype_val measurable_id) (f '' u) (hfi u hu) end } noncomputable def set.range [measurable_space α] [measurable_space β] (f : α → β) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv α (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) def set.range_inl [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inl : set (α ⊕ β)) α := { to_fun := λab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by cases p; contradiction, this.elim end, inv_fun := λa, ⟨sum.inl a, a, rfl⟩, left_inv := assume ⟨ab, a, eq⟩, by subst eq; refl, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inl_image hs, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } def set.range_inr [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inr : set (α ⊕ β)) β := { to_fun := λab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by cases p; contradiction, this.elim end, inv_fun := λb, ⟨sum.inr b, b, rfl⟩, left_inv := assume ⟨ab, b, eq⟩, by subst eq; refl, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv ((α ⊕ β) × γ) ((α × γ) ⊕ (β × γ)) := { to_equiv := equiv.sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_set_prod is_measurable_range_inl is_measurable.univ) (is_measurable_set_prod is_measurable_range_inr is_measurable.univ) (assume ⟨ab, c⟩ s, by cases ab; simp [set.prod_eq]) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := begin refine measurable_sum _ _, { convert measurable.prod_mk (measurable_inl.comp (measurable.fst measurable_id)) (measurable.snd measurable_id), ext ⟨a, c⟩; refl }, { convert measurable.prod_mk (measurable_inr.comp (measurable.fst measurable_id)) (measurable.snd measurable_id), ext ⟨b, c⟩; refl } end } def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv (α × (β ⊕ γ)) ((α × β) ⊕ (α × γ)) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : measurable_equiv ((α ⊕ β) × (γ ⊕ δ)) (((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ))) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) end measurable_equiv namespace measurable_equiv end measurable_equiv namespace measurable_space /-- Dynkin systems The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀{a}, has a → has (-a)) (has_Union_nat : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, has (f i)) → has (⋃i, f i)) theorem Union_decode2_disjoint_on {β} [encodable β] {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 namespace dynkin_system @[ext] lemma ext : ∀{d₁ d₂ : dynkin_system α}, (∀s:set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has (-a) ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀i, d.has (f i)) : d.has (⋃i, f i) := by rw encodable.Union_decode2; exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by rw union_eq_Union; exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := d.has_compl_iff.1 begin simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λm₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable, has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀t∈s, generate_has t | empty : generate_has ∅ | compl : ∀{a}, generate_has a → generate_has (-a) | Union : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, generate_has (f i)) → generate_has (⋃i, f i) def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty s, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } instance : inhabited (dynkin_system α) := ⟨generate univ⟩ def to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λt, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have -t ∩ s = (- (t ∩ s)) \ -s, from set.ext $ assume x, by by_cases x ∈ s; simp [h], by rw [this]; from d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _), has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀t∈s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_inter {s : set (set α)} (hs : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty _) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ lemma generate_from_eq {s : set (set α)} (hs : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by rw [of_measurable_space_to_measurable_space]; from (generate_le _ $ assume t ht, is_measurable_generate_from ht)) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} {m : measurable_space α} (h_eq : m = generate_from s) (h_inter : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) (h_empty : C ∅) (h_basic : ∀t∈s, C t) (h_compl : ∀t, m.is_measurable t → C t → C (- t)) (h_union : ∀f:ℕ → set α, (∀i j, i ≠ j → f i ∩ f j ⊆ ∅) → (∀i, m.is_measurable (f i)) → (∀i, C (f i)) → C (⋃i, f i)) : ∀{t}, m.is_measurable t → C t := have eq : m.is_measurable = dynkin_system.generate_has s, by rw [h_eq, dynkin_system.generate_from_eq h_inter]; refl, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by rw [eq]; exact ht) (assume f hf ht, h_union f hf $ assume i, by rw [eq]; exact ht _) end measurable_space
795c2b4bb7675c4e2d792e85779162e662335ba7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/rearrangement.lean
f3fa11c25eb67e6375d251a5fd7889ce064a21df
[ "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
27,943
lean
/- Copyright (c) 2022 Mantas Bakšys. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mantas Bakšys -/ import algebra.big_operators.basic import algebra.order.module import data.prod.lex import group_theory.perm.support import order.monovary import tactic.abel /-! # Rearrangement inequality This file proves the rearrangement inequality and deduces the conditions for equality and strict inequality. The rearrangement inequality tells you that for two functions `f g : ι → α`, the sum `∑ i, f i * g (σ i)` is maximized over all `σ : perm ι` when `g ∘ σ` monovaries with `f` and minimized when `g ∘ σ` antivaries with `f`. The inequality also tells you that `∑ i, f i * g (σ i) = ∑ i, f i * g i` if and only if `g ∘ σ` monovaries with `f` when `g` monovaries with `f`. The above equality also holds if and only if `g ∘ σ` antivaries with `f` when `g` antivaries with `f`. From the above two statements, we deduce that the inequality is strict if and only if `g ∘ σ` does not monovary with `f` when `g` monovaries with `f`. Analogously, the inequality is strict if and only if `g ∘ σ` does not antivary with `f` when `g` antivaries with `f`. ## Implementation notes In fact, we don't need much compatibility between the addition and multiplication of `α`, so we can actually decouple them by replacing multiplication with scalar multiplication and making `f` and `g` land in different types. As a bonus, this makes the dual statement trivial. The multiplication versions are provided for convenience. The case for `monotone`/`antitone` pairs of functions over a `linear_order` is not deduced in this file because it is easily deducible from the `monovary` API. -/ open equiv equiv.perm finset function order_dual open_locale big_operators variables {ι α β : Type*} /-! ### Scalar multiplication versions -/ section smul variables [linear_ordered_ring α] [linear_ordered_add_comm_group β] [module α β] [ordered_smul α β] {s : finset ι} {σ : perm ι} {f : ι → α} {g : ι → β} /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_le_sum_smul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) ≤ ∑ i in s, f i • g i := begin classical, revert hσ σ hfg, apply finset.induction_on_max_value (λ i, to_lex (g i, f i)) s, { simp only [le_rfl, finset.sum_empty, implies_true_iff] }, intros a s has hamax hind σ hfg hσ, set τ : perm ι := σ.trans (swap a (σ a)) with hτ, have hτs : {x | τ x ≠ x} ⊆ s, { intros x hx, simp only [ne.def, set.mem_set_of_eq, equiv.coe_trans, equiv.swap_comp_apply] at hx, split_ifs at hx with h₁ h₂ h₃, { obtain rfl | hax := eq_or_ne x a, { contradiction }, { exact mem_of_mem_insert_of_ne (hσ $ λ h, hax $ h.symm.trans h₁) hax } }, { exact (hx $ σ.injective h₂.symm).elim }, { exact mem_of_mem_insert_of_ne (hσ hx) (ne_of_apply_ne _ h₂) } }, specialize hind (hfg.subset $ subset_insert _ _) hτs, simp_rw sum_insert has, refine le_trans _ (add_le_add_left hind _), obtain hσa | hσa := eq_or_ne a (σ a), { rw [hτ, ←hσa, swap_self, trans_refl] }, have h1s : σ⁻¹ a ∈ s, { rw [ne.def, ←inv_eq_iff_eq] at hσa, refine mem_of_mem_insert_of_ne (hσ $ λ h, hσa _) hσa, rwa [apply_inv_self, eq_comm] at h }, simp only [← s.sum_erase_add _ h1s, add_comm], rw [← add_assoc, ← add_assoc], simp only [hτ, swap_apply_left, function.comp_app, equiv.coe_trans, apply_inv_self], refine add_le_add (smul_add_smul_le_smul_add_smul' _ _) (sum_congr rfl $ λ x hx, _).le, { specialize hamax (σ⁻¹ a) h1s, rw prod.lex.le_iff at hamax, cases hamax, { exact hfg (mem_insert_of_mem h1s) (mem_insert_self _ _) hamax }, { exact hamax.2 } }, { specialize hamax (σ a) (mem_of_mem_insert_of_ne (hσ $ σ.injective.ne hσa.symm) hσa.symm), rw prod.lex.le_iff at hamax, cases hamax, { exact hamax.le }, { exact hamax.1.le } }, { rw [mem_erase, ne.def, eq_inv_iff_eq] at hx, rw swap_apply_of_ne_of_ne hx.1 (σ.injective.ne _), rintro rfl, exact has hx.2 } end /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_eq_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) = ∑ i in s, f i • g i ↔ monovary_on f (g ∘ σ) s := begin classical, refine ⟨not_imp_not.1 $ λ h, _, λ h, (hfg.sum_smul_comp_perm_le_sum_smul hσ).antisymm _⟩, { rw monovary_on at h, push_neg at h, obtain ⟨x, hx, y, hy, hgxy, hfxy⟩ := h, set τ : perm ι := (swap x y).trans σ, have hτs : {x | τ x ≠ x} ⊆ s, { refine (set_support_mul_subset σ $ swap x y).trans (set.union_subset hσ $ λ z hz, _), obtain ⟨_, rfl | rfl⟩ := swap_apply_ne_self_iff.1 hz; assumption }, refine ((hfg.sum_smul_comp_perm_le_sum_smul hτs).trans_lt' _).ne, obtain rfl | hxy := eq_or_ne x y, { cases lt_irrefl _ hfxy }, simp only [←s.sum_erase_add _ hx, ←(s.erase x).sum_erase_add _ (mem_erase.2 ⟨hxy.symm, hy⟩), add_assoc, equiv.coe_trans, function.comp_app, swap_apply_right, swap_apply_left], refine add_lt_add_of_le_of_lt (finset.sum_congr rfl $ λ z hz, _).le (smul_add_smul_lt_smul_add_smul hfxy hgxy), simp_rw mem_erase at hz, rw swap_apply_of_ne_of_ne hz.2.1 hz.1 }, { convert h.sum_smul_comp_perm_le_sum_smul ((set_support_inv_eq _).subset.trans hσ) using 1, simp_rw [function.comp_app, apply_inv_self] } end /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_lt_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) < ∑ i in s, f i • g i ↔ ¬ monovary_on f (g ∘ σ) s := by simp [←hfg.sum_smul_comp_perm_eq_sum_smul_iff hσ, lt_iff_le_and_ne, hfg.sum_smul_comp_perm_le_sum_smul hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_le_sum_smul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i ≤ ∑ i in s, f i • g i := begin convert hfg.sum_smul_comp_perm_le_sum_smul (show {x | σ⁻¹ x ≠ x} ⊆ s, by simp only [set_support_inv_eq, hσ]) using 1, exact σ.sum_comp' s (λ i j, f i • g j) hσ, end /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_eq_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i = ∑ i in s, f i • g i ↔ monovary_on (f ∘ σ) g s := begin have hσinv : {x | σ⁻¹ x ≠ x} ⊆ s := (set_support_inv_eq _).subset.trans hσ, refine (iff.trans _ $ hfg.sum_smul_comp_perm_eq_sum_smul_iff hσinv).trans ⟨λ h, _, λ h, _⟩, { simpa only [σ.sum_comp' s (λ i j, f i • g j) hσ] }, { convert h.comp_right σ, { rw [comp.assoc, inv_def, symm_comp_self, comp.right_id] }, { rw [σ.eq_preimage_iff_image_eq, set.image_perm hσ] } }, { convert h.comp_right σ.symm, { rw [comp.assoc, self_comp_symm, comp.right_id] }, { rw σ.symm.eq_preimage_iff_image_eq, exact set.image_perm hσinv } } end /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_lt_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i < ∑ i in s, f i • g i ↔ ¬ monovary_on (f ∘ σ) g s := by simp [←hfg.sum_comp_perm_smul_eq_sum_smul_iff hσ, lt_iff_le_and_ne, hfg.sum_comp_perm_smul_le_sum_smul hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_le_sum_smul_comp_perm (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i ≤ ∑ i in s, f i • g (σ i) := hfg.dual_right.sum_smul_comp_perm_le_sum_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_eq_sum_smul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) = ∑ i in s, f i • g i ↔ antivary_on f (g ∘ σ) s := (hfg.dual_right.sum_smul_comp_perm_eq_sum_smul_iff hσ).trans monovary_on_to_dual_right /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_lt_sum_smul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i < ∑ i in s, f i • g (σ i) ↔ ¬ antivary_on f (g ∘ σ) s := by simp [←hfg.sum_smul_eq_sum_smul_comp_perm_iff hσ, lt_iff_le_and_ne, eq_comm, hfg.sum_smul_le_sum_smul_comp_perm hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_le_sum_comp_perm_smul (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i ≤ ∑ i in s, f (σ i) • g i := hfg.dual_right.sum_comp_perm_smul_le_sum_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_eq_sum_comp_perm_smul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i = ∑ i in s, f i • g i ↔ antivary_on (f ∘ σ) g s := (hfg.dual_right.sum_comp_perm_smul_eq_sum_smul_iff hσ).trans monovary_on_to_dual_right /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_lt_sum_comp_perm_smul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i < ∑ i in s, f (σ i) • g i ↔ ¬ antivary_on (f ∘ σ) g s := by simp [←hfg.sum_smul_eq_sum_comp_perm_smul_iff hσ, eq_comm, lt_iff_le_and_ne, hfg.sum_smul_le_sum_comp_perm_smul hσ] variables [fintype ι] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_le_sum_smul (hfg : monovary f g) : ∑ i, f i • g (σ i) ≤ ∑ i, f i • g i := (hfg.monovary_on _).sum_smul_comp_perm_le_sum_smul $ λ i _, mem_univ _ /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_eq_sum_smul_iff (hfg : monovary f g) : ∑ i, f i • g (σ i) = ∑ i, f i • g i ↔ monovary f (g ∘ σ) := by simp [(hfg.monovary_on _).sum_smul_comp_perm_eq_sum_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_lt_sum_smul_iff (hfg : monovary f g) : ∑ i, f i • g (σ i) < ∑ i, f i • g i ↔ ¬ monovary f (g ∘ σ) := by simp [(hfg.monovary_on _).sum_smul_comp_perm_lt_sum_smul_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary.sum_comp_perm_smul_le_sum_smul (hfg : monovary f g) : ∑ i, f (σ i) • g i ≤ ∑ i, f i • g i := (hfg.monovary_on _).sum_comp_perm_smul_le_sum_smul $ λ i _, mem_univ _ /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_smul_eq_sum_smul_iff (hfg : monovary f g) : ∑ i, f (σ i) • g i = ∑ i, f i • g i ↔ monovary (f ∘ σ) g := by simp [(hfg.monovary_on _).sum_comp_perm_smul_eq_sum_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_smul_lt_sum_smul_iff (hfg : monovary f g) : ∑ i, f (σ i) • g i < ∑ i, f i • g i ↔ ¬ monovary (f ∘ σ) g := by simp [(hfg.monovary_on _).sum_comp_perm_smul_lt_sum_smul_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_le_sum_smul_comp_perm (hfg : antivary f g) : ∑ i, f i • g i ≤ ∑ i, f i • g (σ i) := (hfg.antivary_on _).sum_smul_le_sum_smul_comp_perm $ λ i _, mem_univ _ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_eq_sum_smul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g (σ i) = ∑ i, f i • g i ↔ antivary f (g ∘ σ) := by simp [(hfg.antivary_on _).sum_smul_eq_sum_smul_comp_perm_iff (λ i _, mem_univ _)] /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_lt_sum_smul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f i • g (σ i) ↔ ¬ antivary f (g ∘ σ) := by simp [(hfg.antivary_on _).sum_smul_lt_sum_smul_comp_perm_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_le_sum_comp_perm_smul (hfg : antivary f g) : ∑ i, f i • g i ≤ ∑ i, f (σ i) • g i := (hfg.antivary_on _).sum_smul_le_sum_comp_perm_smul $ λ i _, mem_univ _ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_eq_sum_comp_perm_smul_iff (hfg : antivary f g) : ∑ i, f (σ i) • g i = ∑ i, f i • g i ↔ antivary (f ∘ σ) g := by simp [(hfg.antivary_on _).sum_smul_eq_sum_comp_perm_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_lt_sum_comp_perm_smul_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f (σ i) • g i ↔ ¬ antivary (f ∘ σ) g := by simp [(hfg.antivary_on _).sum_smul_lt_sum_comp_perm_smul_iff (λ i _, mem_univ _)] end smul /-! ### Multiplication versions Special cases of the above when scalar multiplication is actually multiplication. -/ section mul variables [linear_ordered_ring α] {s : finset ι} {σ : perm ι} {f g : ι → α} /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_le_sum_mul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) ≤ ∑ i in s, f i * g i := hfg.sum_smul_comp_perm_le_sum_smul hσ /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_eq_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) = ∑ i in s, f i * g i ↔ monovary_on f (g ∘ σ) s := hfg.sum_smul_comp_perm_eq_sum_smul_iff hσ /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_lt_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) < ∑ i in s, f i • g i ↔ ¬ monovary_on f (g ∘ σ) s := hfg.sum_smul_comp_perm_lt_sum_smul_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_le_sum_mul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i ≤ ∑ i in s, f i * g i := hfg.sum_comp_perm_smul_le_sum_smul hσ /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_eq_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i = ∑ i in s, f i * g i ↔ monovary_on (f ∘ σ) g s := hfg.sum_comp_perm_smul_eq_sum_smul_iff hσ /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_lt_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i < ∑ i in s, f i * g i ↔ ¬ monovary_on (f ∘ σ) g s := hfg.sum_comp_perm_smul_lt_sum_smul_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_le_sum_mul_comp_perm (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i ≤ ∑ i in s, f i * g (σ i) := hfg.sum_smul_le_sum_smul_comp_perm hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_eq_sum_mul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) = ∑ i in s, f i * g i ↔ antivary_on f (g ∘ σ) s := hfg.sum_smul_eq_sum_smul_comp_perm_iff hσ /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_lt_sum_mul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i < ∑ i in s, f i * g (σ i) ↔ ¬ antivary_on f (g ∘ σ) s := hfg.sum_smul_lt_sum_smul_comp_perm_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_le_sum_comp_perm_mul (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i ≤ ∑ i in s, f (σ i) * g i := hfg.sum_smul_le_sum_comp_perm_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_eq_sum_comp_perm_mul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i = ∑ i in s, f i * g i ↔ antivary_on (f ∘ σ) g s := hfg.sum_smul_eq_sum_comp_perm_smul_iff hσ /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_lt_sum_comp_perm_mul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i < ∑ i in s, f (σ i) * g i ↔ ¬ antivary_on (f ∘ σ) g s := hfg.sum_smul_lt_sum_comp_perm_smul_iff hσ variables [fintype ι] /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_le_sum_mul (hfg : monovary f g) : ∑ i, f i * g (σ i) ≤ ∑ i, f i * g i := hfg.sum_smul_comp_perm_le_sum_smul /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_eq_sum_mul_iff (hfg : monovary f g) : ∑ i, f i * g (σ i) = ∑ i, f i * g i ↔ monovary f (g ∘ σ) := hfg.sum_smul_comp_perm_eq_sum_smul_iff /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_lt_sum_mul_iff (hfg : monovary f g) : ∑ i, f i * g (σ i) < ∑ i, f i * g i ↔ ¬ monovary f (g ∘ σ) := hfg.sum_smul_comp_perm_lt_sum_smul_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary.sum_comp_perm_mul_le_sum_mul (hfg : monovary f g) : ∑ i, f (σ i) * g i ≤ ∑ i, f i * g i := hfg.sum_comp_perm_smul_le_sum_smul /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_mul_eq_sum_mul_iff (hfg : monovary f g) : ∑ i, f (σ i) * g i = ∑ i, f i * g i ↔ monovary (f ∘ σ) g := hfg.sum_comp_perm_smul_eq_sum_smul_iff /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_mul_lt_sum_mul_iff (hfg : monovary f g) : ∑ i, f (σ i) * g i < ∑ i, f i * g i ↔ ¬ monovary (f ∘ σ) g := hfg.sum_comp_perm_smul_lt_sum_smul_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_le_sum_mul_comp_perm (hfg : antivary f g) : ∑ i, f i * g i ≤ ∑ i, f i * g (σ i) := hfg.sum_smul_le_sum_smul_comp_perm /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_eq_sum_mul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i * g (σ i) = ∑ i, f i * g i ↔ antivary f (g ∘ σ) := hfg.sum_smul_eq_sum_smul_comp_perm_iff /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_lt_sum_mul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f i • g (σ i) ↔ ¬ antivary f (g ∘ σ) := hfg.sum_smul_lt_sum_smul_comp_perm_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_le_sum_comp_perm_mul (hfg : antivary f g) : ∑ i, f i * g i ≤ ∑ i, f (σ i) * g i := hfg.sum_smul_le_sum_comp_perm_smul /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_eq_sum_comp_perm_mul_iff (hfg : antivary f g) : ∑ i, f (σ i) * g i = ∑ i, f i * g i ↔ antivary (f ∘ σ) g := hfg.sum_smul_eq_sum_comp_perm_smul_iff /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_lt_sum_comp_perm_mul_iff (hfg : antivary f g) : ∑ i, f i * g i < ∑ i, f (σ i) * g i ↔ ¬ antivary (f ∘ σ) g := hfg.sum_smul_lt_sum_comp_perm_smul_iff end mul
a5dc86f5226ec0a0b316353b4daedc2a955cc5c4
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Meta/UnificationHint.lean
948428b1669426acbe84d18be060af8b477c281b
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,107
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.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.DiscrTree import Lean.Meta.LevelDefEq namespace Lean.Meta structure UnificationHintEntry where keys : Array DiscrTree.Key val : Name deriving Inhabited structure UnificationHints where discrTree : DiscrTree Name := DiscrTree.empty deriving Inhabited instance : ToFormat UnificationHints where format h := fmt h.discrTree def UnificationHints.add (hints : UnificationHints) (e : UnificationHintEntry) : UnificationHints := { hints with discrTree := hints.discrTree.insertCore e.keys e.val } builtin_initialize unificationHintExtension : SimpleScopedEnvExtension UnificationHintEntry UnificationHints ← registerSimpleScopedEnvExtension { name := `unifHints addEntry := UnificationHints.add initial := {} } structure UnificationConstraint where lhs : Expr rhs : Expr structure UnificationHint where pattern : UnificationConstraint constraints : List UnificationConstraint private partial def decodeUnificationHint (e : Expr) : ExceptT MessageData Id UnificationHint := do decode e #[] where decodeConstraint (e : Expr) : ExceptT MessageData Id UnificationConstraint := match e.eq? with | some (_, lhs, rhs) => return UnificationConstraint.mk lhs rhs | none => throw m!"invalid unification hint constraint, unexpected term{indentExpr e}" decode (e : Expr) (cs : Array UnificationConstraint) : ExceptT MessageData Id UnificationHint := do match e with | Expr.forallE _ d b _ => do let c ← decodeConstraint d if b.hasLooseBVars then throw m!"invalid unification hint constraint, unexpected dependency{indentExpr e}" decode b (cs.push c) | _ => do let p ← decodeConstraint e return { pattern := p, constraints := cs.toList } private partial def validateHint (declName : Name) (hint : UnificationHint) : MetaM Unit := do hint.constraints.forM fun c => do unless (← isDefEq c.lhs c.rhs) do throwError! "invalid unification hint, failed to unify constraint left-hand-side{indentExpr c.lhs}\nwith right-hand-side{indentExpr c.rhs}" unless (← isDefEq hint.pattern.lhs hint.pattern.rhs) do throwError! "invalid unification hint, failed to unify pattern left-hand-side{indentExpr hint.pattern.lhs}\nwith right-hand-side{indentExpr hint.pattern.rhs}" def addUnificationHint (declName : Name) (kind : AttributeKind) : MetaM Unit := withNewMCtxDepth do let info ← getConstInfo declName match info.value? with | none => throwError! "invalid unification hint, it must be a definition" | some val => let (_, _, body) ← lambdaMetaTelescope val match decodeUnificationHint body with | Except.error msg => throwError msg | Except.ok hint => let keys ← DiscrTree.mkPath hint.pattern.lhs validateHint declName hint unificationHintExtension.add { keys := keys, val := declName } kind trace[Meta.debug]! "addUnificationHint: {unificationHintExtension.getState (← getEnv)}" builtin_initialize registerBuiltinAttribute { name := `unificationHint descr := "unification hint" add := fun declName stx kind => do Attribute.Builtin.ensureNoArgs stx discard <| addUnificationHint declName kind |>.run } def tryUnificationHints (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.hint]! "{t} =?= {s}" unless (← read).config.unificationHints do return false if t.isMVar then return false let hints := unificationHintExtension.getState (← getEnv) let candidates ← hints.discrTree.getMatch t for candidate in candidates do if (← tryCandidate candidate) then return true return false where isDefEqPattern p e := withReducible <| Meta.isExprDefEqAux p e tryCandidate candidate : MetaM Bool := traceCtx `Meta.isDefEq.hint <| commitWhen do trace[Meta.isDefEq.hint]! "trying hint {candidate} at {t} =?= {s}" let cinfo ← getConstInfo candidate let hint? ← withConfig (fun cfg => { cfg with unificationHints := false }) do let us ← cinfo.lparams.mapM fun _ => mkFreshLevelMVar let val := cinfo.instantiateValueLevelParams us let (_, _, body) ← lambdaMetaTelescope val match decodeUnificationHint body with | Except.error _ => return none | Except.ok hint => if (← isDefEqPattern hint.pattern.lhs t <&&> isDefEqPattern hint.pattern.rhs s) then return some hint else return none match hint? with | none => return false | some hint => trace[Meta.isDefEq.hint]! "{candidate} succeeded, applying constraints" for c in hint.constraints do unless (← Meta.isExprDefEqAux c.lhs c.rhs) do return false return true builtin_initialize registerTraceClass `Meta.isDefEq.hint end Lean.Meta
8488b8169793a4a0581b0266e0daeab7d064716f
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/instances/real.lean
cdc7acb44760454bbd99343d8c1db98dcc3a6beb
[ "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
14,538
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring /-! # Topological properties of ℝ -/ noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos_iff at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (is_open_prod (real.continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (real.continuous_abs _ $ is_open_gt' (abs a₂ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, (set.finite_lt_nat _).image _, _⟩, rintro x ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, use i, split, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma tendsto_coe_nat_real_at_top_iff {f : α → ℕ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨n, le_of_lt hn⟩ lemma tendsto_coe_nat_real_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top := tendsto_coe_nat_real_at_top_iff.2 tendsto_id lemma tendsto_coe_int_real_at_top_iff {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, int.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨(n:ℤ), le_of_lt $ by rwa [int.cast_coe_nat]⟩ lemma tendsto_coe_int_real_at_top_at_top : tendsto (coe : ℤ → ℝ) at_top at_top := tendsto_coe_int_real_at_top_iff.2 tendsto_id section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (compact_Icc.image_of_continuous_on h) end
c5015bf265e02dee343b3b112fb909a214f9b61f
a9e33f9c83301c461f3c3ebc6799d9de1f6d4d20
/assignments/hw2_a_few_easy_pieces.lean
4039bbd1d4ff83dcbfe2472d6c1dbced62d19fe3
[]
no_license
yl4df/Discrete-Mathematics
f1c9a6cf8cfb4686fb617637f69a481e1522f0c2
c93ce9f6a6e36d194e350d9fa0a0360191e97fa0
refs/heads/master
1,598,714,938,443
1,572,275,647,000
1,572,275,647,000
218,074,726
0
0
null
null
null
null
UTF-8
Lean
false
false
5,459
lean
/- UVa CS Discrete Math (Sullivan) Homework #2 -/ /- Note: We distribute homework assignments and even exams as Lean files, as we do now for this assignment. You will answer the questions in one of two ways: by writing an answer in a comment block (such as this one), or by writing mathematical logic (which is what "Lean code" is). For this assignment you will write all your answers as simple comments. -/ /- This assignment has three questions, each with several parts. Be sure to read and answer all parts of all of the questions. Make a copy of this file in your "mywork" directory the read and answer the questions by editing this fie. When you are done, *save it*, then upload it to Collab. That is how you will submit work in this class. Be sure to double check your submission to be sure you uploaded the right file. -/ /- QUESTION #1 (7 Parts, A - G) A. How many functions are there that take one argument of type Boolean (one bit, if you prefer) and that return one value, also of type Boolean? Hint: We discussed this in class. Answer here (inside this comment block): 4 B. How many functions are there that take two arguments of type Boolean and that return one value of type Boolean? Hint: we discussed this in class, too. Answer here: 16 C. How many functions are there that take three bits of input and that return a one bit result? Hint: We discussed this, too. Answer here: 256 D. Give a general formula that you believe to be valid describing the number of functions that take n bits, for any natural number, n, and that return one bit. Use the ^ character to represent exponentiation. Answer: 2^2^n E. How many functions are there that take three bits of input and that return *two* bits as a result? Hint: think about both how many possible combinations of input bits there are. To define a function, you need to specify which two-bit return value is associated with each combination of input values. The number of functions will be the number of ways in which you can assign output values for each combination of input values. Give your answer in a form that involves 3 (inputs) and 2 (output bits). Answer here:(2^2)^(2^3) F. How many functions are there that take 64 bits of input and return a 64 bit result? Give your answer as an algebraic expression. The number is too big to write it out explicitly. Answer here: (2^64)^(2^64) G. How many functions are there that take n bits of input and return m bits of output, where n and m are natural numbers? Give an algebraic expression as your answer, involving the variables m and n. Answer here: (2^m)^(2^n) -/ /- QUESTION #2 (Three parts, A - C) Suppose you are asked to write a program, P(x), taking one argument, x, a "natural number", and that it must satisfy a specification, S(x), that defines a function in a pure functional programming language. A. Using simple English to express your answer, what proposition that must be true for P to be accepted as a correct implementation of S. Hint: We discussed this in class. Answer: P(x) satisfies the specification S for all natural number. B. Why is testing alone generally inadequate to prove pthe correctness of such a program, P? Answer: It is impossible to test all cases. Here, it is impossible to test on each natural number. Therefore, testing alone is inadequate. C. What kind of mathematical "thing" would be needed to show beyond a reasonable doubt that P satisfies S? You can give a one-word answer. Answer: proof -/ /- QUESTION #3 (Four parts, A - D) Consider a new data type, cool, that has three possible values: true (T), false (F), and don't know (D). And now consider the following conjecture: For any natural number, n, the number of combinations of values of n variables of type cool is 3^n. Give a proof of this conjecture by induction. A. What is the first conjecture you must prove? Hint: substitute a specific value for n into the conjecture and rewrite it with that value in place of n. Answer: For natural number 0, the number of combinations of values of 0 variable of type cool is 3^0. B. Prove it. Hint: One approach to proving that two terms are equal is simply to reduce each term to its simplest form, and then show that the reduced terms are exactly the same. In other words, just simplify the expressions on each side of an equals to to show that the values are identical. Answer here: When there is 0 variable, there is only 1 combination of values, which equals to 3^0. C. What is the second conjecture that you must prove to complete your proof by induction? Answer here: If the above conjecture holds for natural number k, then the conjecture for natural number k+1 holds. D. Prove it. Hint, to prove a proposition of the form, P → Q, or P implies Q, you start by *assuming* that P is true (whatever proposition it happens to be), and then you show that in the context of this assumption, that proposition Q must be true. In other words, you want to prove that IF P is true THEN Q must be true, too. Answer here: Since the above conjecture holds for natural number k, then we know the number of combinations of values of k variables of type cool is 3^k. It follows that the number of combinations of values of k+1 variables of type cool is values of 1 variable multiplied by values of k variables, which is 3*3^k=3^(k+1). Thus, the number of combinations of values of k+1 variables of type cool is 3^(k+1). -/
3711c1fc55e84c9604c579d40881ce1581f51eb9
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/ring_theory/free_comm_ring.lean
75232d85b3def1e73702c0b6eab472ac72aae1fb
[ "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
16,014
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import data.equiv.functor import data.mv_polynomial import ring_theory.ideal_operations import ring_theory.free_ring noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v variables (α : Type u) def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring instance : comm_ring (free_comm_ring α) := free_abelian_group.comm_ring _ instance : inhabited (free_comm_ring α) := ⟨0⟩ variables {α} def of (x : α) : free_comm_ring α := free_abelian_group.of ([x] : multiset α) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {β : Type v} [comm_ring β] (f : α → β) /-- Lift a map `α → R` to a ring homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : free_comm_ring α → β := free_abelian_group.lift $ λ s, (s.map f).prod @[simp] lemma lift_zero : lift f 0 = 0 := rfl @[simp] lemma lift_one : lift f 1 = 1 := free_abelian_group.lift.of _ _ @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_add (x y) : lift f (x + y) = lift f x + lift f y := free_abelian_group.lift.add _ _ _ @[simp] lemma lift_neg (x) : lift f (-x) = -lift f x := free_abelian_group.lift.neg _ _ @[simp] lemma lift_sub (x y) : lift f (x - y) = lift f x - lift f y := free_abelian_group.lift.sub _ _ _ @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros s2, conv { to_lhs, dsimp only [(*), mul_zero_class.mul, semiring.mul, ring.mul, semigroup.mul, comm_ring.mul] }, rw [free_abelian_group.lift.of, lift, free_abelian_group.lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros s1, iterate 3 { rw free_abelian_group.lift.of }, calc _ = multiset.prod ((multiset.map f s1) + (multiset.map f s2)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _ }, { intros s1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros s2 ih, rw [mul_neg_eq_neg_mul_symm, lift_neg, lift_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, lift_add, lift_add, mul_add, ih1, ih2] }, end /-- Lift of a map `f : α → β` to `free_comm_ring α` as a ring homomorphism. We don't use it as the canonical form because Lean fails to coerce it to a function. -/ def lift_hom : free_comm_ring α →+* β := ⟨lift f, lift_one f, lift_mul f, lift_zero f, lift_add f⟩ instance : is_ring_hom (lift f) := (lift_hom f).is_ring_hom @[simp] lemma coe_lift_hom : ⇑(lift_hom f : free_comm_ring α →+* β) = lift f := rfl @[simp] lemma lift_pow (x) (n : ℕ) : lift f (x ^ n) = lift f x ^ n := (lift_hom f).map_pow _ _ @[simp] lemma lift_comp_of (f : free_comm_ring α → β) [is_ring_hom f] : lift (f ∘ of) = f := funext $ λ x, free_comm_ring.induction_on x (by rw [lift_neg, lift_one, is_ring_hom.map_neg f, is_ring_hom.map_one f]) (lift_of _) (λ x y ihx ihy, by rw [lift_add, is_ring_hom.map_add f, ihx, ihy]) (λ x y ihx ihy, by rw [lift_mul, is_ring_hom.map_mul f, ihx, ihy]) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α → free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift_hom $ of ∘ f lemma map_zero : map f 0 = 0 := rfl lemma map_one : map f 1 = 1 := rfl lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ lemma map_add (x y) : map f (x + y) = map f x + map f y := lift_add _ _ _ lemma map_neg (x) : map f (-x) = -map f x := lift_neg _ _ lemma map_sub (x y) : map f (x - y) = map f x - map f y := lift_sub _ _ _ lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ lemma map_pow (x) (n : ℕ) : map f (x ^ n) = (map f x) ^ n := lift_pow _ _ _ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ ring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem _ _ _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero : is_supported 0 s := is_add_submonoid.zero_mem theorem is_supported_one : is_supported 1 s := is_submonoid.one_mem theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported def restriction (s : set α) [decidable_pred s] (x : free_comm_ring α) : free_comm_ring s := lift (λ p, if H : p ∈ s then of ⟨p, H⟩ else 0) x section restriction variables (s : set α) [decidable_pred s] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ @[simp] lemma restriction_zero : restriction s 0 = 0 := lift_zero _ @[simp] lemma restriction_one : restriction s 1 = 1 := lift_one _ @[simp] lemma restriction_add : restriction s (x + y) = restriction s x + restriction s y := lift_add _ _ _ @[simp] lemma restriction_neg : restriction s (-x) = -restriction s x := lift_neg _ _ @[simp] lemma restriction_sub : restriction s (x - y) = restriction s x - restriction s y := lift_sub _ _ _ @[simp] lemma restriction_mul : restriction s (x * y) = restriction s x * restriction s y := lift_mul _ _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, ring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin classical, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : polynomial ℤ) else polynomial.X) x = n, { intros x hx, refine ring.in_closure.rec_on hx _ _ _ _, { use 1, rw [lift_one], norm_cast }, { use -1, rw [lift_neg, lift_one], norm_cast }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [lift_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [lift_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw polynomial.int_cast_eq_C at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg one_ne_zero, polynomial.coeff_X, if_pos rfl] at this, apply_instance end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred s] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw restriction_one, refl }, { rw [restriction_neg, map_neg, restriction_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, restriction_of, dif_pos hps, map_mul, map_of, ih] }, { intros x y ihx ihy, rw [restriction_add, map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, set.finite_union hfs hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, set.finite_union hfs hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) def to_free_comm_ring {α} : free_ring α → free_comm_ring α := free_ring.lift free_comm_ring.of instance to_free_comm_ring.is_ring_hom : is_ring_hom (@to_free_comm_ring α) := free_ring.is_ring_hom free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ instance coe.is_ring_hom : is_ring_hom (coe : free_ring α → free_comm_ring α) := free_ring.to_free_comm_ring.is_ring_hom _ @[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := free_ring.lift_neg _ _ @[simp, norm_cast] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := free_ring.lift_add _ _ _ @[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := free_ring.lift_sub _ _ _ @[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := free_ring.lift_mul _ _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact free_ring.lift_add _ _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact free_ring.lift_mul _ _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := begin funext, apply @free_abelian_group.lift.ext _ _ _ (coe : free_ring α → free_comm_ring α) _ _ (free_abelian_group.lift.is_add_group_hom _), intros x, change free_ring.lift free_comm_ring.of (free_abelian_group.of x) = _, change _ = free_abelian_group.of (↑x), induction x with hd tl ih, {refl}, simp only [*, free_ring.lift, free_comm_ring.of, free_abelian_group.of, free_abelian_group.lift, free_group.of, free_group.to_group, free_group.to_group.aux, mul_one, free_group.quot_lift_mk, abelianization.lift.of, bool.cond_tt, list.prod_cons, cond, list.prod_nil, list.map] at *, refl end def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := @ring_equiv.of' (free_ring α) (free_comm_ring α) _ _ (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) $ begin delta functor.map_equiv, rw congr_arg is_ring_hom _, work_on_goal 2 { symmetry, exact coe_eq α }, apply_instance end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by rw [← (subsingleton_equiv_free_comm_ring α).left_inv (y * x), is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, mul_comm, ← is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, (subsingleton_equiv_free_comm_ring α).left_inv], .. free_ring.ring α } end free_ring def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := { to_fun := free_comm_ring.lift $ λ a, mv_polynomial.X a, inv_fun := mv_polynomial.eval₂ coe free_comm_ring.of, left_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, refine free_abelian_group.induction_on x rfl _ _ _, { intro s, refine multiset.induction_on s _ _, { unfold free_comm_ring.lift, rw [free_abelian_group.lift.of], exact mv_polynomial.eval₂_one _ _ }, { intros hd tl ih, show mv_polynomial.eval₂ coe free_comm_ring.of (free_comm_ring.lift (λ a, mv_polynomial.X a) (free_comm_ring.of hd * free_abelian_group.of tl)) = free_comm_ring.of hd * free_abelian_group.of tl, rw [free_comm_ring.lift_mul, free_comm_ring.lift_of, mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, ih] } }, { intros s ih, rw [free_comm_ring.lift_neg, ← neg_one_mul, mv_polynomial.eval₂_mul, ← mv_polynomial.C_1, ← mv_polynomial.C_neg, mv_polynomial.eval₂_C, int.cast_neg, int.cast_one, neg_one_mul, ih] }, { intros x₁ x₂ ih₁ ih₂, rw [free_comm_ring.lift_add, mv_polynomial.eval₂_add, ih₁, ih₂] } end, right_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, have : ∀ i : ℤ, free_comm_ring.lift (λ (a : α), mv_polynomial.X a) ↑i = mv_polynomial.C i, { exact λ i, int.induction_on i (by rw [int.cast_zero, free_comm_ring.lift_zero, mv_polynomial.C_0]) (λ i ih, by rw [int.cast_add, int.cast_one, free_comm_ring.lift_add, free_comm_ring.lift_one, ih, mv_polynomial.C_add, mv_polynomial.C_1]) (λ i ih, by rw [int.cast_sub, int.cast_one, free_comm_ring.lift_sub, free_comm_ring.lift_one, ih, mv_polynomial.C_sub, mv_polynomial.C_1]) }, apply mv_polynomial.induction_on x, { intro i, rw [mv_polynomial.eval₂_C, this] }, { intros p q ihp ihq, rw [mv_polynomial.eval₂_add, free_comm_ring.lift_add, ihp, ihq] }, { intros p a ih, rw [mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, free_comm_ring.lift_mul, free_comm_ring.lift_of, ih] } end, .. free_comm_ring.lift_hom $ λ a, mv_polynomial.X a } def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.pempty_ring_equiv _) def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.punit_ring_equiv _) open free_ring def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
32b0d0fa2cb2796d18e16d33b3df735387f435d7
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170410-rewrite_nth.lean
aab9d01f88526101444a73a5acb8ddb9c93f21e8
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
1,146
lean
open tactic open lean.parser open interactive namespace tactic.interactive open lean open lean.parser private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p.to_raw_expr with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } private meta def to_expr' (p : pexpr) : tactic expr := let e := p.to_raw_expr in match e with | (expr.const c []) := do new_e ← resolve_name' c, save_type_info new_e e, return new_e | (expr.local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e e, return new_e | _ := i_to_expr p end private meta def rw_goal_gos (m : transparency) (r : rw_rule) : tactic unit := save_info r.pos >> to_expr' r.rule >>= rewrite_core m tt tt occurrences.all r.symm meta def rewrite_nth (r : parse ident) (n : nat) : tactic unit := do e ← tactic.mk_const r, tactic.rewrite_core reducible tt tt (occurrences.pos [n]) tt r end tactic.interactive lemma foo (p : 1 = 2): [ 1,1,1,2,1 ] = [ 1,1,2,2,1 ] := begin induction p, rewrite_nth p 3, end
8b73e5d30cb097bc317349f25286a9972a4292e4
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0708.lean
29f64b7890c6c1ae910e0a3b815dfed3e0018ae5
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
115
lean
variables (f : ℕ → ℕ) (k : ℕ) example (h₁ : f 0 = 0) (h₂ : k = 0) : f k = 0 := by simp [h₁, h₂]
1b6503085c86e70035f93e19629fe3bd3b2984ef
e94d3f31e48d06d252ee7307fe71efe1d500f274
/hott/homotopy/susp.hlean
aab3ab60866ed6beb57a93fb902256b4f7ae1ffd
[ "Apache-2.0" ]
permissive
GallagherCommaJack/lean
e4471240a069d82f97cb361d2bf1a029de3f4256
226f8bafeb9baaa5a2ac58000c83d6beb29991e2
refs/heads/master
1,610,725,100,482
1,459,194,829,000
1,459,195,377,000
55,377,224
0
0
null
1,459,731,701,000
1,459,731,700,000
null
UTF-8
Lean
false
false
10,996
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Ulrik Buchholtz Declaration of suspension -/ import hit.pushout types.pointed cubical.square .connectedness open pushout unit eq equiv definition susp (A : Type) : Type := pushout (λ(a : A), star) (λ(a : A), star) namespace susp variable {A : Type} definition north {A : Type} : susp A := inl star definition south {A : Type} : susp A := inr star definition merid (a : A) : @north A = @south A := glue a protected definition rec {P : susp A → Type} (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) (x : susp A) : P x := begin induction x with u u, { cases u, exact PN}, { cases u, exact PS}, { apply Pm}, end protected definition rec_on [reducible] {P : susp A → Type} (y : susp A) (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) : P y := susp.rec PN PS Pm y theorem rec_merid {P : susp A → Type} (PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) (a : A) : apdo (susp.rec PN PS Pm) (merid a) = Pm a := !rec_glue protected definition elim {P : Type} (PN : P) (PS : P) (Pm : A → PN = PS) (x : susp A) : P := susp.rec PN PS (λa, pathover_of_eq (Pm a)) x protected definition elim_on [reducible] {P : Type} (x : susp A) (PN : P) (PS : P) (Pm : A → PN = PS) : P := susp.elim PN PS Pm x theorem elim_merid {P : Type} {PN PS : P} (Pm : A → PN = PS) (a : A) : ap (susp.elim PN PS Pm) (merid a) = Pm a := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (merid a)), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑susp.elim,rec_merid], end protected definition elim_type (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) (x : susp A) : Type := susp.elim PN PS (λa, ua (Pm a)) x protected definition elim_type_on [reducible] (x : susp A) (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) : Type := susp.elim_type PN PS Pm x theorem elim_type_merid (PN : Type) (PS : Type) (Pm : A → PN ≃ PS) (a : A) : transport (susp.elim_type PN PS Pm) (merid a) = Pm a := by rewrite [tr_eq_cast_ap_fn,↑susp.elim_type,elim_merid];apply cast_ua_fn protected definition merid_square {a a' : A} (p : a = a') : square (merid a) (merid a') idp idp := by cases p; apply vrefl end susp attribute susp.north susp.south [constructor] attribute susp.rec susp.elim [unfold 6] [recursor 6] attribute susp.elim_type [unfold 5] attribute susp.rec_on susp.elim_on [unfold 3] attribute susp.elim_type_on [unfold 2] namespace susp open is_trunc is_conn trunc -- Theorem 8.2.1 definition is_conn_susp [instance] (n : trunc_index) (A : Type) [H : is_conn n A] : is_conn (n .+1) (susp A) := is_contr.mk (tr north) begin apply trunc.rec, fapply susp.rec, { reflexivity }, { exact (trunc.rec (λa, ap tr (merid a)) (center (trunc n A))) }, { intro a, generalize (center (trunc n A)), apply trunc.rec, intro a', apply pathover_of_tr_eq, rewrite [transport_eq_Fr,idp_con], revert H, induction n with [n, IH], { intro H, apply is_prop.elim }, { intros H, change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a'), generalize a', apply is_conn_fun.elim n (is_conn_fun_from_unit n A a) (λx : A, trunctype.mk' n (ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid x))), intros, change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a), reflexivity } } end end susp /- Flattening lemma -/ namespace susp open prod prod.ops section universe variable u parameters (A : Type) (PN PS : Type.{u}) (Pm : A → PN ≃ PS) include Pm local abbreviation P [unfold 5] := susp.elim_type PN PS Pm local abbreviation F : A × PN → PN := λz, z.2 local abbreviation G : A × PN → PS := λz, Pm z.1 z.2 protected definition flattening : sigma P ≃ pushout F G := begin apply equiv.trans (pushout.flattening (λ(a : A), star) (λ(a : A), star) (λx, unit.cases_on x PN) (λx, unit.cases_on x PS) Pm), fapply pushout.equiv, { exact sigma.equiv_prod A PN }, { apply sigma.sigma_unit_left }, { apply sigma.sigma_unit_left }, { reflexivity }, { reflexivity } end end end susp /- Functoriality and equivalence -/ namespace susp variables {A B : Type} (f : A → B) include f protected definition functor : susp A → susp B := begin intro x, induction x with a, { exact north }, { exact south }, { exact merid (f a) } end variable [Hf : is_equiv f] include Hf open is_equiv protected definition is_equiv_functor [instance] : is_equiv (susp.functor f) := adjointify (susp.functor f) (susp.functor f⁻¹) abstract begin intro sb, induction sb with b, do 2 reflexivity, apply eq_pathover, rewrite [ap_id,ap_compose' (susp.functor f) (susp.functor f⁻¹)], krewrite [susp.elim_merid,susp.elim_merid], apply transpose, apply susp.merid_square (right_inv f b) end end abstract begin intro sa, induction sa with a, do 2 reflexivity, apply eq_pathover, rewrite [ap_id,ap_compose' (susp.functor f⁻¹) (susp.functor f)], krewrite [susp.elim_merid,susp.elim_merid], apply transpose, apply susp.merid_square (left_inv f a) end end end susp namespace susp variables {A B : Type} (f : A ≃ B) protected definition equiv : susp A ≃ susp B := equiv.mk (susp.functor f) _ end susp namespace susp open pointed definition pointed_susp [instance] [constructor] (X : Type) : pointed (susp X) := pointed.mk north end susp open susp definition psusp [constructor] (X : Type) : pType := pointed.mk' (susp X) namespace susp open pointed variables {X Y Z : pType} definition psusp_functor (f : X →* Y) : psusp X →* psusp Y := begin fconstructor, { exact susp.functor f }, { reflexivity } end definition is_equiv_psusp_functor (f : X →* Y) [Hf : is_equiv f] : is_equiv (psusp_functor f) := susp.is_equiv_functor f definition psusp_equiv (f : X ≃* Y) : psusp X ≃* psusp Y := pequiv_of_equiv (susp.equiv f) idp definition psusp_functor_compose (g : Y →* Z) (f : X →* Y) : psusp_functor (g ∘* f) ~* psusp_functor g ∘* psusp_functor f := begin fconstructor, { intro a, induction a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, rewrite [▸*,ap_compose' _ (psusp_functor f),↑psusp_functor], krewrite +susp.elim_merid } }, { reflexivity } end -- adjunction from Coq-HoTT definition loop_susp_unit [constructor] (X : pType) : X →* Ω(psusp X) := begin fconstructor, { intro x, exact merid x ⬝ (merid pt)⁻¹}, { apply con.right_inv}, end definition loop_susp_unit_natural (f : X →* Y) : loop_susp_unit Y ∘* f ~* ap1 (psusp_functor f) ∘* loop_susp_unit X := begin induction X with X x, induction Y with Y y, induction f with f pf, esimp at *, induction pf, fconstructor, { intro x', esimp [psusp_functor], symmetry, exact !idp_con ⬝ (!ap_con ⬝ whisker_left _ !ap_inv) ⬝ (!elim_merid ◾ (inverse2 !elim_merid)) }, { rewrite [▸*,idp_con (con.right_inv _)], apply inv_con_eq_of_eq_con, refine _ ⬝ !con.assoc', rewrite inverse2_right_inv, refine _ ⬝ !con.assoc', rewrite [ap_con_right_inv], unfold psusp_functor, xrewrite [idp_con_idp, -ap_compose (concat idp)]}, end definition loop_susp_counit [constructor] (X : pType) : psusp (Ω X) →* X := begin fconstructor, { intro x, induction x, exact pt, exact pt, exact a}, { reflexivity}, end definition loop_susp_counit_natural (f : X →* Y) : f ∘* loop_susp_counit X ~* loop_susp_counit Y ∘* (psusp_functor (ap1 f)) := begin induction X with X x, induction Y with Y y, induction f with f pf, esimp at *, induction pf, fconstructor, { intro x', induction x' with p, { reflexivity}, { reflexivity}, { esimp, apply eq_pathover, apply hdeg_square, xrewrite [ap_compose' f, ap_compose' (susp.elim (f x) (f x) (λ (a : f x = f x), a)),▸*], xrewrite [+elim_merid,▸*,idp_con]}}, { reflexivity} end definition loop_susp_counit_unit (X : pType) : ap1 (loop_susp_counit X) ∘* loop_susp_unit (Ω X) ~* pid (Ω X) := begin induction X with X x, fconstructor, { intro p, esimp, refine !idp_con ⬝ (!ap_con ⬝ whisker_left _ !ap_inv) ⬝ (!elim_merid ◾ inverse2 !elim_merid)}, { rewrite [▸*,inverse2_right_inv (elim_merid id idp)], refine !con.assoc ⬝ _, xrewrite [ap_con_right_inv (susp.elim x x (λa, a)) (merid idp),idp_con_idp,-ap_compose]} end definition loop_susp_unit_counit (X : pType) : loop_susp_counit (psusp X) ∘* psusp_functor (loop_susp_unit X) ~* pid (psusp X) := begin induction X with X x, fconstructor, { intro x', induction x', { reflexivity}, { exact merid pt}, { apply eq_pathover, xrewrite [▸*, ap_id, ap_compose' (susp.elim north north (λa, a)), +elim_merid,▸*], apply square_of_eq, exact !idp_con ⬝ !inv_con_cancel_right⁻¹}}, { reflexivity} end definition susp_adjoint_loop (X Y : pType) : map₊ (pointed.mk' (susp X)) Y ≃ map₊ X (Ω Y) := begin fapply equiv.MK, { intro f, exact ap1 f ∘* loop_susp_unit X}, { intro g, exact loop_susp_counit Y ∘* psusp_functor g}, { intro g, apply eq_of_phomotopy, esimp, refine !pwhisker_right !ap1_compose ⬝* _, refine !passoc ⬝* _, refine !pwhisker_left !loop_susp_unit_natural⁻¹* ⬝* _, refine !passoc⁻¹* ⬝* _, refine !pwhisker_right !loop_susp_counit_unit ⬝* _, apply pid_comp}, { intro f, apply eq_of_phomotopy, esimp, refine !pwhisker_left !psusp_functor_compose ⬝* _, refine !passoc⁻¹* ⬝* _, refine !pwhisker_right !loop_susp_counit_natural⁻¹* ⬝* _, refine !passoc ⬝* _, refine !pwhisker_left !loop_susp_unit_counit ⬝* _, apply comp_pid}, end definition susp_adjoint_loop_nat_right (f : psusp X →* Y) (g : Y →* Z) : susp_adjoint_loop X Z (g ∘* f) ~* ap1 g ∘* susp_adjoint_loop X Y f := begin esimp [susp_adjoint_loop], refine _ ⬝* !passoc, apply pwhisker_right, apply ap1_compose end definition susp_adjoint_loop_nat_left (f : Y →* Ω Z) (g : X →* Y) : (susp_adjoint_loop X Z)⁻¹ᵉ (f ∘* g) ~* (susp_adjoint_loop Y Z)⁻¹ᵉ f ∘* psusp_functor g := begin esimp [susp_adjoint_loop], refine _ ⬝* !passoc⁻¹*, apply pwhisker_left, apply psusp_functor_compose end end susp
c404a571f2dab6d74fc2a47fed9ec88cd611bc52
1437b3495ef9020d5413178aa33c0a625f15f15f
/data/dfinsupp.lean
57d1d579c4b19a0822655098433378c2985db965
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,952
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau Dependent functions with finite support (see `data/finsupp.lean`). -/ import data.finset data.set.finite algebra.big_operators algebra.module algebra.pi_instances universes u u₁ u₂ v v₁ v₂ v₃ w x y l variables (ι : Type u) (β : ι → Type v) def decidable_zero_symm {γ : Type w} [has_zero γ] [decidable_pred (eq (0 : γ))] : decidable_pred (λ x, x = (0:γ)) := λ x, decidable_of_iff (0 = x) eq_comm local attribute [instance] decidable_zero_symm namespace dfinsupp variable [Π i, has_zero (β i)] structure pre : Type (max u v) := (to_fun : Π i, β i) (pre_support : multiset ι) (zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0) instance : setoid (pre ι β) := { r := λ x y, ∀ i, x.to_fun i = y.to_fun i, iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm, λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ } end dfinsupp variable {ι} @[reducible] def dfinsupp [Π i, has_zero (β i)] : Type* := quotient (dfinsupp.setoid ι β) variable {β} notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r infix ` →ₚ `:25 := dfinsupp namespace dfinsupp section basic variables [Π i, has_zero (β i)] variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] instance : has_coe_to_fun (Π₀ i, β i) := ⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩ instance : has_zero (Π₀ i, β i) := ⟨⟦⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟧⟩ instance : inhabited (Π₀ i, β i) := ⟨0⟩ @[simp] lemma zero_apply {i : ι} : (0 : Π₀ i, β i) i = 0 := rfl @[extensionality] lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g := quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) H /-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is `map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. -/ def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i := quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma map_range_apply {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {i : ι} : map_range f hf g i = f i (g i) := quotient.induction_on g $ λ x, rfl def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) := begin refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2, λ i, _⟩ : pre ι β)⟧) _, { cases x.3 i with h1 h1, { left, rw multiset.mem_add, left, exact h1 }, cases y.3 i with h2 h2, { left, rw multiset.mem_add, right, exact h2 }, right, rw [h1, h2, hf] }, exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i] end @[simp] lemma zip_with_apply {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} {i : ι} : zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) := quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl end basic section algebra instance [Π i, add_monoid (β i)] : has_add (Π₀ i, β i) := ⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩ @[simp] lemma add_apply [Π i, add_monoid (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ + g₂) i = g₁ i + g₂ i := zip_with_apply instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) := { add_monoid . zero := 0, add := (+), add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc], zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add], add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] } instance [Π i, add_monoid (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) := by refine_struct {..}; simp instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) := ⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩ instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], .. dfinsupp.add_monoid } @[simp] lemma neg_apply [Π i, add_group (β i)] {g : Π₀ i, β i} {i : ι} : (- g) i = - g i := map_range_apply instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) := { add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg], .. dfinsupp.add_monoid, .. (infer_instance : has_neg (Π₀ i, β i)) } @[simp] lemma sub_apply [Π i, add_group (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ - g₂) i = g₁ i - g₂ i := by rw [sub_eq_add_neg]; simp instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], ..dfinsupp.add_group } def to_has_scalar {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : has_scalar γ (Π₀ i, β i) := ⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩ local attribute [instance] to_has_scalar @[simp] lemma smul_apply {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] {i : ι} {b : γ} {v : Π₀ i, β i} : (b • v) i = b • (v i) := map_range_apply def to_module {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : module γ (Π₀ i, β i) := module.of_core { smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add], add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul], one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul], mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul], .. (infer_instance : has_scalar γ (Π₀ i, β i)) } end algebra section filter_and_subtype_domain /-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma filter_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : ι} {f : Π₀ i, β i} : f.filter p i = if p i then f i else 0 := quotient.induction_on f $ λ x, rfl @[simp] lemma filter_apply_pos [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] @[simp] lemma filter_apply_neg [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : ¬ p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] lemma filter_pos_add_filter_neg [Π i, add_monoid (β i)] {f : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : f.filter p + f.filter (λi, ¬ p i) = f := ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add] /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i : subtype p, β i.1 := begin fapply quotient.lift_on f, { intro x, refine ⟦⟨λ i, x.1 i.1, (x.2.filter p).attach.map $ λ j, ⟨j.1, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧, refine λ i, or.cases_on (x.3 i.1) (λ H, _) or.inr, left, rw multiset.mem_map, refine ⟨⟨i.1, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩, apply multiset.mem_attach }, intros x y H, exact quotient.sound (λ i, H i.1) end @[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] : subtype_domain p (0 : Π₀ i, β i) = 0 := rfl @[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : subtype p} {v : Π₀ i, β i} : (subtype_domain p v) i = v (i.val) := quotient.induction_on v $ λ x, rfl @[simp] lemma subtype_domain_add [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ i, by simp only [add_apply, subtype_domain_apply] instance subtype_domain.is_add_monoid_hom [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] : is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) := by refine_struct {..}; simp @[simp] lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ i, by simp only [neg_apply, subtype_domain_apply] @[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ i, by simp only [sub_apply, subtype_domain_apply] end filter_and_subtype_domain variable [decidable_eq ι] section basic variable [Π i, has_zero (β i)] lemma finite_supp (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} := quotient.induction_on f $ λ x, set.finite_subset (finset.finite_to_set x.2.to_finset) $ λ i H, multiset.mem_to_finset.2 $ (x.3 i).resolve_right H def mk (s : finset ι) (x : Π i : (↑s : set ι), β i.1) : Π₀ i, β i := ⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1, λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧ @[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i.1} {i : ι} : (mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_inj (s : finset ι) : function.injective (@mk ι β _ _ s) := begin intros x y H, ext i, have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H}, cases i with i hi, change i ∈ s at hi, dsimp only [mk_apply, subtype.coe_mk] at h1, simpa only [dif_pos hi] using h1 end def single (i : ι) (b : β i) : Π₀ i, β i := mk (finset.singleton i) $ λ j, eq.rec_on (finset.mem_singleton.1 j.2).symm b @[simp] lemma single_apply {i i' b} : (single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) := begin dsimp only [single], by_cases h : i = i', { have h1 : i' ∈ finset.singleton i, { simp only [h, finset.mem_singleton] }, simp only [mk_apply, dif_pos h, dif_pos h1] }, { have h1 : i' ∉ finset.singleton i, { simp only [ne.symm h, finset.mem_singleton, not_false_iff] }, simp only [mk_apply, dif_neg h, dif_neg h1] } end @[simp] lemma single_zero {i} : (single i 0 : Π₀ i, β i) = 0 := quotient.sound $ λ j, if H : j ∈ finset.singleton i then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl else dif_neg H @[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by simp only [single_apply, dif_pos rfl] @[simp] lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 := by simp only [single_apply, dif_neg h] def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2, λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ j, if h : j = i then by simp only [if_pos h] else by simp only [if_neg h, H j] @[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j := quotient.induction_on f $ λ x, rfl @[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp @[simp] lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h] end basic section add_monoid variable [Π i, add_monoid (β i)] @[simp] lemma single_add {i : ι} {b₁ b₂ : β i} : single i (b₁ + b₂) = single i b₁ + single i b₂ := ext $ assume i', begin by_cases h : i = i', { subst h, simp only [add_apply, single_eq_same] }, { simp only [add_apply, single_eq_of_ne h, zero_add] } end lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add] lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero] protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := begin refine quotient.induction_on f (λ x, _), cases x with f s H, revert f H, apply multiset.induction_on s, { intros f H, convert h0, ext i, exact (H i).resolve_left id }, intros i s ih f H, by_cases H1 : i ∈ s, { have H2 : ∀ j, j ∈ s ∨ f j = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { left, rw H3, exact H1 }, { left, exact H3 } }, right, exact H2 }, have H3 : (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) = ⟦{to_fun := f, pre_support := s, zero := H2}⟧, { exact quotient.sound (λ i, rfl) }, rw H3, apply ih }, have H2 : p (erase i ⟦{to_fun := f, pre_support := i :: s, zero := H}⟧), { dsimp only [erase, quotient.lift_on_beta], have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { right, exact if_pos H3 }, { left, exact H3 } }, right, split_ifs; [refl, exact H2] }, have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := i :: s, zero := _}⟧ : Π₀ i, β i) = ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ := quotient.sound (λ i, rfl), rw H3, apply ih }, have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) := single_add_erase, rw ← H3, change p (single i (f i) + _), cases classical.em (f i = 0) with h h, { rw [h, single_zero, zero_add], exact H2 }, refine ha _ _ _ _ h H2, rw erase_same end lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f := dfinsupp.induction f h0 $ λ i b f h1 h2 h3, have h4 : f + single i b = single i b + f, { ext j, by_cases H : i = j, { subst H, simp [h1] }, { simp [H] } }, eq.rec_on h4 $ ha i b f h1 h2 h3 end add_monoid @[simp] lemma mk_add [Π i, add_monoid (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x + y) = mk s x + mk s y := ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add] @[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} : mk s (0 : Π i : (↑s : set ι), β i.1) = 0 := ext $ λ i, by simp only [mk_apply]; split_ifs; refl @[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : mk s (-x) = -mk s x := ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero] @[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x - y) = mk s x - mk s y := ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero] instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) := ⟨λ _ _, mk_add⟩ section local attribute [instance] to_module variables {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] include γ @[simp] lemma mk_smul {s : finset ι} {c : γ} {x : Π i : (↑s : set ι), β i.1} : mk s (c • x) = c • mk s x := ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero] @[simp] lemma single_smul {i : ι} {c : γ} {x : β i} : single i (c • x) = c • single i x := ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl variable β def lmk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →ₗ Π₀ i, β i := ⟨mk s, λ _ _, mk_add, λ _ _, mk_smul⟩ def lsingle (i) : β i →ₗ Π₀ i, β i := ⟨single i, λ _ _, single_add, λ _ _, single_smul⟩ variable {β} @[simp] lemma lmk_apply {s : finset ι} {x} : lmk β s x = mk s x := rfl @[simp] lemma lsingle_apply {i : ι} {x : β i} : lsingle β i x = single i x := rfl end section support_basic variables [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] def support (f : Π₀ i, β i) : finset ι := quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $ begin intros x y Hxy, ext i, split, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ }, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw ← Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ }, end @[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : (mk s x).support ⊆ s := λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1 @[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := begin refine quotient.induction_on f (λ x, _), dsimp only [support, quotient.lift_on_beta], rw [finset.mem_filter, multiset.mem_to_finset], exact and_iff_right_of_imp (x.3 i).resolve_right end theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i.1) := by ext i; by_cases h : f i = 0; try {simp at h}; simp [h] @[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl @[simp] lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 := f.mem_support_to_fun @[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 := ⟨λ H, ext $ by simpa [finset.ext] using H, by simp {contextual:=tt}⟩ instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) := λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ (∀i∉s, f i = 0) := by simp [set.subset_def]; exact forall_congr (assume i, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := begin ext j, by_cases h : i = j, { subst h, simp [hb] }, simp [ne.symm h, h] end lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} := support_mk_subset section map_range_and_zip_with variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] variables [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] lemma map_range_def {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) := begin ext i, by_cases h : g i = 0, { simp [h, hf] }, { simp at h, simp [h, hf] } end lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : (map_range f hf g).support ⊆ g.support := by simp [map_range_def] @[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} : map_range f hf (single i b) = single i (f i b) := dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]] lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) := begin ext i, by_cases h1 : g₁ i = 0; by_cases h2 : g₂ i = 0; try {simp at h1 h2}; simp [h1, h2, hf] end lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by simp [zip_with_def] end map_range_and_zip_with lemma erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) (λ j, f j.1) := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end @[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end section filter_and_subtype_domain variables {p : ι → Prop} [decidable_pred p] lemma filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) (λ i, f i.1) := by ext i; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; simp [h1, h2] @[simp] lemma support_filter (f : Π₀ i, β i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i; simp [h] lemma subtype_domain_def (f : Π₀ i, β i) : f.subtype_domain p = mk (f.support.subtype p) (λ i, f i.1) := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] @[simp] lemma support_subtype_domain {f : Π₀ i, β i} : (subtype_domain p f).support = f.support.subtype p := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] end filter_and_subtype_domain end support_basic lemma support_add [Π i, add_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma support_neg [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} : support (-f) = support f := by ext i; simp instance [decidable_eq ι] [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i)) ⟨assume ⟨h₁, h₂⟩, ext $ assume i, if h : i ∈ f.support then h₂ i h else have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ section prod_and_sum variables {γ : Type w} -- [to_additive dfinsupp.sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/ def sum [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := f.support.sum (λi, g i (f i)) /-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive dfinsupp.sum] def prod [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := f.support.prod (λi, g i (f i)) attribute [to_additive dfinsupp.sum.equations._eqn_1] dfinsupp.prod.equations._eqn_1 @[to_additive dfinsupp.sum_map_range_index] lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] [comm_monoid γ] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ} (h0 : ∀i, h i 0 = 1) : (map_range f hf g).prod h = g.prod (λi b, h i (f i b)) := begin rw [map_range_def], refine (finset.prod_subset support_mk_subset _).trans _, { intros i h1 h2, dsimp, simp [h1] at h2, dsimp at h2, simp [h1, h2, h0] }, { refine finset.prod_congr rfl _, intros i h1, simp [h1] } end @[to_additive dfinsupp.sum_zero_index] lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 := rfl @[to_additive dfinsupp.sum_single_index] lemma prod_single_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := begin by_cases h : b = 0, { simp [h, prod_zero_index, h_zero], refl }, { simp [dfinsupp.prod, support_single_ne_zero h] } end @[to_additive dfinsupp.sum_neg_index] lemma prod_neg_index [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) : (-g).prod h = g.prod (λi b, h i (- b)) := prod_map_range_index h0 @[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} : (f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) := (finset.sum_hom (λf : Π₀ i, β i, f i₂)).symm lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} : (f.sum g).support ⊆ f.support.bind (λi, (g i (f i)).support) := have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 → (∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0), from assume i₁ h, let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨i, (f.mem_support_iff i).mp hi, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this @[simp] lemma sum_zero [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] {f : Π₀ i, β i} : f.sum (λi b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} : f.sum (λi b, h₁ i b + h₂ i b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} : f.sum (λi b, - h i b) = - f.sum h := finset.sum_hom (@has_neg.neg γ _) @[to_additive dfinsupp.sum_add_index] lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λi, h i (f i)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : (f.support ∪ g.support).prod (λi, h i (g i)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc (f + g).support.prod (λi, h i ((f + g) i)) = (f.support ∪ g.support).prod (λi, h i ((f + g) i)) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (f.support ∪ g.support).prod (λi, h i (f i)) * (f.support ∪ g.support).prod (λi, h i (g i)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [Π i, add_comm_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_group γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀i, h i 0 = 0, from assume i, have h i (0 - 0) = h i 0 - h i 0, from h_sub i 0 0, by simpa using this, have h_neg : ∀i b, h i (- b) = - h i b, from assume i b, have h i (0 - b) = h i 0 - h i b, from h_sub i 0 b, by simpa [h_zero] using this, have h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ + h i b₂, from assume i b₁ b₂, have h i (b₁ - (- b₂)) = h i b₁ - h i (- b₂), from h_sub i b₁ (-b₂), by simpa [h_neg] using this, by simp [@sum_add_index ι β _ γ _ _ _ f (-g) h h_zero h_add]; simp [@sum_neg_index ι β _ γ _ _ _ g h h_zero, h_neg]; simp [@sum_neg ι β _ γ _ _ _ g h] @[to_additive dfinsupp.sum_finset_sum_index] lemma prod_finset_sum_index {γ : Type w} {α : Type x} [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] [decidable_eq α] {s : finset α} {g : α → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂): s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) @[to_additive dfinsupp.sum_sum_index] lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂): (f.sum g).prod h = f.prod (λi b, (g i b).prod h) := (prod_finset_sum_index h_zero h_add).symm @[simp] lemma sum_single [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} : f.sum single = f := begin apply dfinsupp.induction f, {rw [sum_zero_index]}, intros i b f H hb ih, rw [sum_add_index, ih, sum_single_index], all_goals { intros, simp } end @[to_additive dfinsupp.sum_subtype_domain_index] lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] {h : Π i, β i → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λi b, h i.1 b) = v.prod h := finset.prod_bij (λp _, p.val) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩) lemma subtype_domain_sum [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (finset.sum_hom _) lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ] [Π c, has_zero (δ c)] [Π c, decidable_pred (eq (0 : δ c))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {p : ι → Prop} [decidable_pred p] {s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end prod_and_sum end dfinsupp
754c0f838eaadd38ef7b3f7befc495a096cc3444
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/system/io.lean
6d5f67226cdd3ea2d113d3126fc9c2fe41d63a06
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,212
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch and Leonardo de Moura -/ universe u constant io : Type u → Type u protected constant io.return : ∀ {α : Type u}, α → io α protected constant io.bind : ∀ {α β : Type u}, io α → (α → io β) → io β protected constant io.map : ∀ {α β : Type u}, (α → β) → io α → io β constant io.put_str : string → io unit constant io.get_line : io string instance : monad io := { pure := @io.return, bind := @io.bind, map := @io.map } namespace io def put {α} [has_to_string α] (s : α) : io unit := put_str ∘ to_string $ s def put_ln {α} [has_to_string α] (s : α) : io unit := put s >> put_str "\n" end io meta constant format.print_using : format → options → io unit meta definition format.print (fmt : format) : io unit := format.print_using fmt options.mk meta definition pp_using {α : Type} [has_to_format α] (a : α) (o : options) : io unit := format.print_using (to_fmt a) o meta definition pp {α : Type} [has_to_format α] (a : α) : io unit := format.print (to_fmt a)
e27b8a053b4e93937726e1ccf249aad3d22df900
4fa161becb8ce7378a709f5992a594764699e268
/src/category_theory/limits/shapes/constructions/limits_of_products_and_equalizers.lean
b488a0b8a7e8bf57195bb115d1d1e08a863c3d61
[ "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
4,767
lean
/- -- Copyright (c) 2017 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.equalizers import category_theory.limits.shapes.finite_products /-! # Constructing limits from products and equalizers. If a category has all products, and all equalizers, then it has all limits. Similarly, if it has all finite products, and all equalizers, then it has all finite limits. TODO: provide the dual result. -/ open category_theory open opposite namespace category_theory.limits universes v u variables {C : Type u} [category.{v} C] variables {J : Type v} [small_category J] -- We hide the "implementation details" inside a namespace namespace has_limit_of_has_products_of_has_equalizers -- We assume here only that we have exactly the products we need, so that we can prove -- variations of the construction (all products gives all limits, finite products gives finite limits...) variables (F : J ⥤ C) [H₁ : has_limit.{v} (discrete.functor F.obj)] [H₂ : has_limit.{v} (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))] include H₁ H₂ /-- Corresponding to any functor `F : J ⥤ C`, we construct a new functor from the walking parallel pair of morphisms to `C`, given by the diagram ``` s ∏_j F j ===> Π_{f : j ⟶ j'} F j' t ``` where the two morphisms `s` and `t` are defined componentwise: * The `s_f` component is the projection `∏_j F j ⟶ F j` followed by `f`. * The `t_f` component is the projection `∏_j F j ⟶ F j'`. In a moment we prove that cones over `F` are isomorphic to cones over this new diagram. -/ @[simp] def diagram : walking_parallel_pair ⥤ C := let pi_obj := limits.pi_obj F.obj in let pi_hom := limits.pi_obj (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2) in let s : pi_obj ⟶ pi_hom := pi.lift (λ f : (Σ p : J × J, p.1 ⟶ p.2), pi.π F.obj f.1.1 ≫ F.map f.2) in let t : pi_obj ⟶ pi_hom := pi.lift (λ f : (Σ p : J × J, p.1 ⟶ p.2), pi.π F.obj f.1.2) in parallel_pair s t /-- The morphism from cones over the walking pair diagram `diagram F` to cones over the original diagram `F`. -/ @[simp] def cones_hom : (diagram F).cones ⟶ F.cones := { app := λ X c, { app := λ j, c.app walking_parallel_pair.zero ≫ pi.π _ j, naturality' := λ j j' f, begin have L := c.naturality walking_parallel_pair_hom.left, have R := c.naturality walking_parallel_pair_hom.right, have t := congr_arg (λ g, g ≫ pi.π _ (⟨(j, j'), f⟩ : Σ (p : J × J), p.fst ⟶ p.snd)) (R.symm.trans L), dsimp at t, dsimp, simpa only [limit.lift_π, fan.mk_π_app, category.assoc, category.id_comp] using t, end }, }. local attribute [semireducible] op unop opposite /-- The morphism from cones over the original diagram `F` to cones over the walking pair diagram `diagram F`. -/ @[simp] def cones_inv : F.cones ⟶ (diagram F).cones := { app := λ X c, begin refine (fork.of_ι _ _).π, { exact pi.lift c.app }, { ext ⟨⟨A,B⟩,f⟩, dsimp, simp only [limit.lift_π, limit.lift_π_assoc, fan.mk_π_app, category.assoc], rw ←(c.naturality f), dsimp, simp only [category.id_comp], } end, naturality' := λ X Y f, by { ext c j, cases j; tidy, } }. /-- The natural isomorphism between cones over the walking pair diagram `diagram F` and cones over the original diagram `F`. -/ def cones_iso : (diagram F).cones ≅ F.cones := { hom := cones_hom F, inv := cones_inv F, hom_inv_id' := begin ext X c j, cases j, { ext, simp }, { ext, have t := c.naturality walking_parallel_pair_hom.left, conv at t { dsimp, to_lhs, simp only [category.id_comp] }, simp [t], } end } end has_limit_of_has_products_of_has_equalizers open has_limit_of_has_products_of_has_equalizers /-- Any category with products and equalizers has all limits. -/ -- This is not an instance, as it is not always how one wants to construct limits! def limits_from_equalizers_and_products [has_products.{v} C] [has_equalizers.{v} C] : has_limits.{v} C := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.of_cones_iso (diagram F) F (cones_iso F) } } /-- Any category with finite products and equalizers has all finite limits. -/ -- This is not an instance, as it is not always how one wants to construct finite limits! def finite_limits_from_equalizers_and_finite_products [has_finite_products.{v} C] [has_equalizers.{v} C] : has_finite_limits.{v} C := { has_limits_of_shape := λ J _ _, by exactI { has_limit := λ F, has_limit.of_cones_iso (diagram F) F (cones_iso F) } } end category_theory.limits
54927aaed4d32df16b19eef568460ba8d7f577ce
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/polynomial/cancel_leads.lean
5d8ac8894f5ba07885d3afcf1f995739e4754f06
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
2,949
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.polynomial.degree.definitions /-! # Cancel the leading terms of two polynomials ## Definition * `cancel_leads p q`: the polynomial formed by multiplying `p` and `q` by monomials so that they have the same leading term, and then subtracting. ## Main Results The degree of `cancel_leads` is less than that of the larger of the two polynomials being cancelled. Thus it is useful for induction or minimal-degree arguments. -/ namespace polynomial noncomputable theory variables {R : Type*} section comm_ring variables [comm_ring R] (p q : polynomial R) /-- `cancel_leads p q` is formed by multiplying `p` and `q` by monomials so that they have the same leading term, and then subtracting. -/ def cancel_leads : polynomial R := C p.leading_coeff * X ^ (p.nat_degree - q.nat_degree) * q - C q.leading_coeff * X ^ (q.nat_degree - p.nat_degree) * p variables {p q} @[simp] lemma neg_cancel_leads : - p.cancel_leads q = q.cancel_leads p := neg_sub _ _ lemma dvd_cancel_leads_of_dvd_of_dvd {r : polynomial R} (pq : p ∣ q) (pr : p ∣ r) : p ∣ q.cancel_leads r := dvd_sub (pr.trans (dvd.intro_left _ rfl)) (pq.trans (dvd.intro_left _ rfl)) end comm_ring lemma nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree [comm_ring R] [is_domain R] {p q : polynomial R} (h : p.nat_degree ≤ q.nat_degree) (hq : 0 < q.nat_degree) : (p.cancel_leads q).nat_degree < q.nat_degree := begin by_cases hp : p = 0, { convert hq, simp [hp, cancel_leads], }, rw [cancel_leads, sub_eq_add_neg, tsub_eq_zero_iff_le.mpr h, pow_zero, mul_one], by_cases h0 : C p.leading_coeff * q + -(C q.leading_coeff * X ^ (q.nat_degree - p.nat_degree) * p) = 0, { convert hq, simp only [h0, nat_degree_zero], }, have hq0 : ¬ q = 0, { contrapose! hq, simp [hq] }, apply lt_of_le_of_ne, { rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree h0, ← degree_eq_nat_degree hq0], apply le_trans (degree_add_le _ _), rw ← leading_coeff_eq_zero at hp hq0, simp only [max_le_iff, degree_C hp, degree_C hq0, le_refl q.degree, true_and, nat.cast_with_bot, nsmul_one, degree_neg, degree_mul, zero_add, degree_X, degree_pow], rw leading_coeff_eq_zero at hp hq0, rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq0, ← with_bot.coe_add, with_bot.coe_le_coe, tsub_add_cancel_of_le h], }, { contrapose! h0, rw [← leading_coeff_eq_zero, leading_coeff, h0, mul_assoc, mul_comm _ p, ← tsub_add_cancel_of_le h, add_comm _ p.nat_degree], simp only [coeff_mul_X_pow, coeff_neg, coeff_C_mul, add_tsub_cancel_left, coeff_add], rw [add_comm p.nat_degree, tsub_add_cancel_of_le h, ← leading_coeff, ← leading_coeff, mul_comm _ q.leading_coeff, ← sub_eq_add_neg, ← mul_sub, sub_self, mul_zero] } end end polynomial
9d26e5dc2cde79e0df49597f22c835449cedaaf9
e4d500be102d7cc2cf7c341f360db71d9125c19b
/src/algebra/ordered_field.lean
4a30fc9938200a11fc7935dae987a23c4a7d17db
[ "Apache-2.0" ]
permissive
mgrabovsky/mathlib
3cbc6c54dab5f277f0abf4195a1b0e6e39b9971f
e397b4c1266ee241e9412e17b1dd8724f56fba09
refs/heads/master
1,664,687,987,155
1,591,255,329,000
1,591,255,329,000
269,361,264
0
0
Apache-2.0
1,591,275,784,000
1,591,275,783,000
null
UTF-8
Lean
false
false
25,406
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro -/ import algebra.ordered_ring import algebra.field set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true variable {α : Type*} @[protect_proj] class linear_ordered_field (α : Type*) extends linear_ordered_ring α, field α section linear_ordered_field variables [linear_ordered_field α] {a b c d e : α} lemma mul_zero_lt_mul_inv_of_pos (h : 0 < a) : a * 0 < a * (1 / a) := calc a * 0 = 0 : by rw mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne.symm (ne_of_lt h))) ... = a * (1 / a) : by rw inv_eq_one_div lemma mul_zero_lt_mul_inv_of_neg (h : a < 0) : a * 0 < a * (1 / a) := calc a * 0 = 0 : by rw mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne_of_lt h)) ... = a * (1 / a) : by rw inv_eq_one_div lemma one_div_pos_of_pos (h : 0 < a) : 0 < 1 / a := lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos h) (le_of_lt h) lemma pos_of_one_div_pos (h : 0 < 1 / a) : 0 < a := one_div_one_div a ▸ one_div_pos_of_pos h lemma one_div_neg_of_neg (h : a < 0) : 1 / a < 0 := gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg h) (le_of_lt h) lemma neg_of_one_div_neg (h : 1 / a < 0) : a < 0 := one_div_one_div a ▸ one_div_neg_of_neg h lemma le_mul_of_ge_one_right (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_ge_one_left (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b := by rw mul_comm; exact le_mul_of_ge_one_right hb h lemma lt_mul_of_gt_one_right (hb : b > 0) (h : a > 1) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, mul_lt_mul_of_pos_left h hb lemma one_le_div_of_le (a : α) {b : α} (hb : b > 0) (h : b ≤ a) : 1 ≤ a / b := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc 1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb') ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt hbinv) ... = a / b : eq.symm $ div_eq_mul_one_div a b lemma le_of_one_le_div (a : α) {b : α} (hb : b > 0) (h : 1 ≤ a / b) : b ≤ a := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), calc b ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt hb) h ... = a : by rw [mul_div_cancel' _ hb'] lemma one_lt_div_of_lt (a : α) {b : α} (hb : b > 0) (h : b < a) : 1 < a / b := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc 1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb') ... < a * (1 / b) : mul_lt_mul_of_pos_right h hbinv ... = a / b : eq.symm $ div_eq_mul_one_div a b lemma lt_of_one_lt_div (a : α) {b : α} (hb : b > 0) (h : 1 < a / b) : b < a := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), calc b < b * (a / b) : lt_mul_of_gt_one_right hb h ... = a : by rw [mul_div_cancel' _ hb'] -- the following lemmas amount to four iffs, for <, ≤, ≥, >. lemma mul_le_of_le_div (hc : 0 < c) (h : a ≤ b / c) : a * c ≤ b := div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_le_mul_of_nonneg_right h (le_of_lt hc) lemma le_div_of_mul_le (hc : 0 < c) (h : a * c ≤ b) : a ≤ b / c := calc a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc)) ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc)) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_lt_of_lt_div (hc : 0 < c) (h : a < b / c) : a * c < b := div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_lt_mul_of_pos_right h hc lemma lt_div_of_mul_lt (hc : 0 < c) (h : a * c < b) : a < b / c := calc a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc)) ... < b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_le_of_div_le_of_neg (hc : c < 0) (h : b / c ≤ a) : a * c ≤ b := div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h (le_of_lt hc) lemma div_le_of_mul_le_of_neg (hc : c < 0) (h : a * c ≤ b) : b / c ≤ a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc)) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_lt_of_gt_div_of_neg (hc : c < 0) (h : a > b / c) : a * c < b := div_mul_cancel b (ne_of_lt hc) ▸ mul_lt_mul_of_neg_right h hc lemma div_lt_of_mul_lt_of_pos (hc : c > 0) (h : b < a * c) : b / c < a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_gt hc) ... > b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma div_lt_of_mul_gt_of_neg (hc : c < 0) (h : a * c < b) : b / c < a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... > b * (1 / c) : mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma div_le_of_le_mul (hb : b > 0) (h : a ≤ b * c) : a / b ≤ c := calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hb)) ... = (b * c) / b : eq.symm $ div_eq_mul_one_div (b * c) b ... = c : by rw [mul_div_cancel_left _ (ne.symm (ne_of_lt hb))] lemma le_mul_of_div_le (hc : c > 0) (h : a / c ≤ b) : a ≤ b * c := calc a = a / c * c : by rw (div_mul_cancel _ (ne.symm (ne_of_lt hc))) ... ≤ b * c : mul_le_mul_of_nonneg_right h (le_of_lt hc) -- following these in the isabelle file, there are 8 biconditionals for the above with - signs -- skipping for now lemma mul_sub_mul_div_mul_neg (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c < b / d) : (a * d - b * c) / (c * d) < 0 := have h1 : a / c - b / d < 0, from calc a / c - b / d < b / d - b / d : sub_lt_sub_right h _ ... = 0 : by rw sub_self, calc 0 > a / c - b / d : h1 ... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd ... = (a * d - b * c) / (c * d) : by rw (mul_comm b c) lemma mul_sub_mul_div_mul_nonpos (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c ≤ b / d) : (a * d - b * c) / (c * d) ≤ 0 := have h1 : a / c - b / d ≤ 0, from calc a / c - b / d ≤ b / d - b / d : sub_le_sub_right h _ ... = 0 : by rw sub_self, calc 0 ≥ a / c - b / d : h1 ... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd ... = (a * d - b * c) / (c * d) : by rw (mul_comm b c) lemma div_lt_div_of_mul_sub_mul_div_neg (hc : c ≠ 0) (hd : d ≠ 0) (h : (a * d - b * c) / (c * d) < 0) : a / c < b / d := have (a * d - c * b) / (c * d) < 0, by rwa [mul_comm c b], have a / c - b / d < 0, by rwa [div_sub_div _ _ hc hd], have a / c - b / d + b / d < 0 + b / d, from add_lt_add_right this _, by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this lemma div_le_div_of_mul_sub_mul_div_nonpos (hc : c ≠ 0) (hd : d ≠ 0) (h : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d := have (a * d - c * b) / (c * d) ≤ 0, by rwa [mul_comm c b], have a / c - b / d ≤ 0, by rwa [div_sub_div _ _ hc hd], have a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right this _, by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this lemma div_pos_of_pos_of_pos : 0 < a → 0 < b → 0 < a / b := begin intros, rw div_eq_mul_one_div, apply mul_pos, assumption, apply one_div_pos_of_pos, assumption end lemma div_nonneg_of_nonneg_of_pos : 0 ≤ a → 0 < b → 0 ≤ a / b := begin intros, rw div_eq_mul_one_div, apply mul_nonneg, assumption, apply le_of_lt, apply one_div_pos_of_pos, assumption end lemma div_neg_of_neg_of_pos : a < 0 → 0 < b → a / b < 0 := begin intros, rw div_eq_mul_one_div, apply mul_neg_of_neg_of_pos, assumption, apply one_div_pos_of_pos, assumption end lemma div_nonpos_of_nonpos_of_pos : a ≤ 0 → 0 < b → a / b ≤ 0 := begin intros, rw div_eq_mul_one_div, apply mul_nonpos_of_nonpos_of_nonneg, assumption, apply le_of_lt, apply one_div_pos_of_pos, assumption end lemma div_neg_of_pos_of_neg : 0 < a → b < 0 → a / b < 0 := begin intros, rw div_eq_mul_one_div, apply mul_neg_of_pos_of_neg, assumption, apply one_div_neg_of_neg, assumption end lemma div_nonpos_of_nonneg_of_neg : 0 ≤ a → b < 0 → a / b ≤ 0 := begin intros, rw div_eq_mul_one_div, apply mul_nonpos_of_nonneg_of_nonpos, assumption, apply le_of_lt, apply one_div_neg_of_neg, assumption end lemma div_pos_of_neg_of_neg : a < 0 → b < 0 → 0 < a / b := begin intros, rw div_eq_mul_one_div, apply mul_pos_of_neg_of_neg, assumption, apply one_div_neg_of_neg, assumption end lemma div_nonneg_of_nonpos_of_neg : a ≤ 0 → b < 0 → 0 ≤ a / b := begin intros, rw div_eq_mul_one_div, apply mul_nonneg_of_nonpos_of_nonpos, assumption, apply le_of_lt, apply one_div_neg_of_neg, assumption end lemma div_lt_div_of_lt_of_pos (h : a < b) (hc : 0 < c) : a / c < b / c := begin intros, rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) end lemma div_le_div_of_le_of_pos (h : a ≤ b) (hc : 0 < c) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc)) end lemma div_lt_div_of_lt_of_neg (h : b < a) (hc : c < 0) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc) end lemma div_le_div_of_le_of_neg (h : b ≤ a) (hc : c < 0) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc)) end lemma add_halves (a : α) : a / 2 + a / 2 = a := by { rw [div_add_div_same, ← two_mul, mul_div_cancel_left], exact two_ne_zero } lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma add_midpoint {a b : α} (h : a < b) : a + (b - a) / 2 < b := begin rw [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg], apply add_lt_of_lt_sub_right, rw [sub_self_div_two, sub_self_div_two], apply div_lt_div_of_lt_of_pos h two_pos end lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_self_div_two (a : α) : (a + a) / 2 = a := eq.symm (iff.mpr (eq_div_iff_mul_eq _ _ (ne_of_gt (add_pos (@zero_lt_one α _) zero_lt_one))) (begin unfold bit0, rw [left_distrib, mul_one] end)) lemma mul_le_mul_of_mul_div_le {a b c d : α} (h : a * (b / c) ≤ d) (hc : c > 0) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rw [mul_comm b], apply le_mul_of_div_le hc h end lemma div_two_lt_of_pos {a : α} (h : a > 0) : a / 2 < a := suffices a / (1 + 1) < a, begin unfold bit0, assumption end, have ha : a / 2 > 0, from div_pos_of_pos_of_pos h (add_pos zero_lt_one zero_lt_one), calc a / 2 < a / 2 + a / 2 : lt_add_of_pos_left _ ha ... = a : add_halves a lemma div_mul_le_div_mul_of_div_le_div_pos {a b c d e : α} (h : a / b ≤ c / d) (he : e > 0) : a / (b * e) ≤ c / (d * e) := begin have h₁ := div_mul_eq_div_mul_one_div a b e, have h₂ := div_mul_eq_div_mul_one_div c d e, rw [h₁, h₂], apply mul_le_mul_of_nonneg_right h, apply le_of_lt, apply one_div_pos_of_pos he end lemma exists_add_lt_and_pos_of_lt {a b : α} (h : b < a) : ∃ c : α, b + c < a ∧ 0 < c := begin apply exists.intro ((a - b) / (1 + 1)), split, {have h2 : a + a > (b + b) + (a - b), calc a + a > b + a : add_lt_add_right h _ ... = b + a + b - b : by rw add_sub_cancel ... = b + b + a - b : by simp [add_comm, add_left_comm] ... = (b + b) + (a - b) : by rw add_sub, have h3 : (a + a) / 2 > ((b + b) + (a - b)) / 2, exact div_lt_div_of_lt_of_pos h2 two_pos, rw [one_add_one_eq_two, sub_eq_add_neg], rw [add_self_div_two, ← div_add_div_same, add_self_div_two, sub_eq_add_neg] at h3, exact h3}, exact div_pos_of_pos_of_pos (sub_pos_of_lt h) two_pos end lemma le_of_forall_sub_le {a b : α} (h : ∀ ε > 0, b - ε ≤ a) : b ≤ a := begin apply le_of_not_gt, intro hb, cases exists_add_lt_and_pos_of_lt hb with c hc, have hc' := h c (and.right hc), apply (not_le_of_gt (and.left hc)) (le_add_of_sub_right_le hc') end lemma one_div_lt_one_div_of_lt {a b : α} (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := begin apply lt_div_of_mul_lt ha, rw [mul_comm, ← div_eq_mul_one_div], apply div_lt_of_mul_lt_of_pos (lt_trans ha h), rwa [one_mul] end lemma one_div_le_one_div_of_le {a b : α} (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := (lt_or_eq_of_le h).elim (λ h, le_of_lt $ one_div_lt_one_div_of_lt ha h) (λ h, by rw [h]) lemma one_div_lt_one_div_of_lt_of_neg {a b : α} (hb : b < 0) (h : a < b) : 1 / b < 1 / a := begin apply div_lt_of_mul_gt_of_neg hb, rw [mul_comm, ← div_eq_mul_one_div], apply div_lt_of_mul_gt_of_neg (lt_trans h hb), rwa [one_mul] end lemma one_div_le_one_div_of_le_of_neg {a b : α} (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := (lt_or_eq_of_le h).elim (λ h, le_of_lt $ one_div_lt_one_div_of_lt_of_neg hb h) (λ h, by rw [h]) lemma le_of_one_div_le_one_div {a b : α} (h : 0 < a) (hl : 1 / a ≤ 1 / b) : b ≤ a := le_of_not_gt $ λ hn, not_lt_of_ge hl $ one_div_lt_one_div_of_lt h hn lemma le_of_one_div_le_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a ≤ 1 / b) : b ≤ a := le_of_not_gt $ λ hn, not_lt_of_ge hl $ one_div_lt_one_div_of_lt_of_neg h hn lemma lt_of_one_div_lt_one_div {a b : α} (h : 0 < a) (hl : 1 / a < 1 / b) : b < a := lt_of_not_ge $ λ hn, not_le_of_gt hl $ one_div_le_one_div_of_le h hn lemma lt_of_one_div_lt_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a < 1 / b) : b < a := lt_of_not_ge $ λ hn, not_le_of_gt hl $ one_div_le_one_div_of_le_of_neg h hn lemma one_div_le_of_one_div_le_of_pos {a b : α} (ha : a > 0) (h : 1 / a ≤ b) : 1 / b ≤ a := begin rw [← one_div_one_div a], apply one_div_le_one_div_of_le _ h, apply one_div_pos_of_pos ha end lemma one_div_le_of_one_div_le_of_neg {a b : α} (hb : b < 0) (h : 1 / a ≤ b) : 1 / b ≤ a := le_of_not_gt $ λ hl, begin have : a < 0, from lt_trans hl (one_div_neg_of_neg hb), rw ← one_div_one_div a at hl, exact not_lt_of_ge h (lt_of_one_div_lt_one_div_of_neg hb hl) end lemma one_lt_one_div {a : α} (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := suffices 1 / 1 < 1 / a, by rwa one_div_one at this, one_div_lt_one_div_of_lt h1 h2 lemma one_le_one_div {a : α} (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := suffices 1 / 1 ≤ 1 / a, by rwa one_div_one at this, one_div_le_one_div_of_le h1 h2 lemma one_div_lt_neg_one {a : α} (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_lt_of_neg h1 h2 lemma one_div_le_neg_one {a : α} (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_le_of_neg h1 h2 lemma div_lt_div_of_pos_of_lt_of_pos (hb : 0 < b) (h : b < a) (hc : 0 < c) : c / a < c / b := begin apply lt_of_sub_neg, rw [div_eq_mul_one_div, div_eq_mul_one_div c b, ← mul_sub_left_distrib], apply mul_neg_of_pos_of_neg, exact hc, apply sub_neg_of_lt, apply one_div_lt_one_div_of_lt; assumption, end lemma div_mul_le_div_mul_of_div_le_div_pos' (h : a / b ≤ c / d) (he : e > 0) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], apply mul_le_mul_of_nonneg_right h, apply le_of_lt, apply one_div_pos_of_pos he end lemma div_pos : 0 < a → 0 < b → 0 < a / b := div_pos_of_pos_of_pos @[simp] lemma inv_pos : ∀ {a : α}, 0 < a⁻¹ ↔ 0 < a := suffices ∀ a : α, 0 < a → 0 < a⁻¹, from λ a, ⟨λ h, inv_inv'' a ▸ this _ h, this a⟩, λ a, one_div_eq_inv a ▸ one_div_pos_of_pos @[simp] lemma inv_lt_zero : ∀ {a : α}, a⁻¹ < 0 ↔ a < 0 := suffices ∀ a : α, a < 0 → a⁻¹ < 0, from λ a, ⟨λ h, inv_inv'' a ▸ this _ h, this a⟩, λ a, one_div_eq_inv a ▸ one_div_neg_of_neg @[simp] lemma inv_nonneg : 0 ≤ a⁻¹ ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 inv_lt_zero @[simp] lemma inv_nonpos : a⁻¹ ≤ 0 ↔ a ≤ 0 := le_iff_le_iff_lt_iff_lt.2 inv_pos lemma one_le_div_iff_le (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := ⟨le_of_one_le_div a hb, one_le_div_of_le a hb⟩ lemma one_lt_div_iff_lt (hb : 0 < b) : 1 < a / b ↔ b < a := ⟨lt_of_one_lt_div a hb, one_lt_div_of_lt a hb⟩ lemma div_le_one_iff_le (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 (one_lt_div_iff_lt hb) lemma div_lt_one_iff_lt (hb : 0 < b) : a / b < 1 ↔ a < b := lt_iff_lt_of_le_iff_le (one_le_div_iff_le hb) lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨mul_le_of_le_div hc, le_div_of_mul_le hc⟩ lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b := ⟨le_mul_of_div_le hb, by rw [mul_comm]; exact div_le_of_le_mul hb⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := ⟨mul_lt_of_lt_div hc, lt_div_of_mul_lt hc⟩ lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨mul_le_of_div_le_of_neg hc, div_le_of_mul_le_of_neg hc⟩ lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c := by rw [← neg_neg c, mul_neg_eq_neg_mul_symm, div_neg, le_neg, div_le_iff (neg_pos.2 hc), neg_mul_eq_neg_mul_symm] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := ⟨mul_lt_of_gt_div_of_neg hc, div_lt_of_mul_gt_of_neg hc⟩ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [inv_eq_one_div, div_le_iff ha, ← div_eq_inv_mul, one_le_div_iff_le hb] lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv'] lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv'] lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div_eq_inv] using inv_le_inv ha hb lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := (one_div_eq_inv a).symm ▸ (one_div_eq_inv b).symm ▸ inv_lt ha hb lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div hb ha) lemma div_nonneg : 0 ≤ a → 0 < b → 0 ≤ a / b := div_nonneg_of_nonneg_of_pos lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_pos h hc), λ h, div_lt_div_of_lt_of_pos h hc⟩ lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right hc) lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := ⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_neg h hc), λ h, div_lt_div_of_lt_of_neg h hc⟩ lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right_of_neg hc) lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := (mul_lt_mul_left ha).trans (inv_lt_inv hb hc) lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b := by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0] lemma div_le_div (hc : 0 ≤ c) (hac : a ≤ c) (hd : 0 < d) (hbd : d ≤ b) : a / b ≤ c / d := begin rw div_le_div_iff (lt_of_lt_of_le hd hbd) hd, exact mul_le_mul hac hbd (le_of_lt hd) hc end lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (lt_of_lt_of_le d0 hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (lt_trans d0 hbd) d0).2 (mul_lt_mul' hac hbd (le_of_lt d0) c0) lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f) {c : α} (hc : 0 ≤ c) : monotone (λ x, (f x) / c) := hf.mul_const (inv_nonneg.2 hc) lemma strict_mono.div_const {β : Type*} [preorder β] {f : β → α} (hf : strict_mono f) {c : α} (hc : 0 < c) : strict_mono (λ x, (f x) / c) := hf.mul_const (inv_pos.2 hc) lemma half_pos {a : α} (h : 0 < a) : 0 < a / 2 := div_pos h two_pos lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := assume a₁ a₂ h, ⟨(a₁ + a₂) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_left h _) two_pos, calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_right h _) two_pos ... = a₂ : add_self_div_two a₂⟩ } instance linear_ordered_field.to_no_top_order : no_top_order α := { no_top := assume a, ⟨a + 1, lt_add_of_le_of_pos (le_refl a) zero_lt_one ⟩ } instance linear_ordered_field.to_no_bot_order : no_bot_order α := { no_bot := assume a, ⟨a + -1, add_lt_of_le_of_neg (le_refl _) (neg_lt_of_neg_lt $ by simp [zero_lt_one]) ⟩ } lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 := by rw [inv_eq_one_div]; exact div_lt_of_mul_lt_of_pos (lt_trans zero_lt_one ha) (by simp *) lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rw [inv_eq_one_div, lt_div_iff h₁]; simp [h₂] lemma inv_le_one (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rw [inv_eq_one_div]; exact div_le_of_le_mul (lt_of_lt_of_le zero_lt_one ha) (by simp *) lemma one_le_inv (ha0 : 0 < a) (ha : a ≤ 1) : 1 ≤ a⁻¹ := le_of_mul_le_mul_left (by simpa [mul_inv_cancel (ne.symm (ne_of_lt ha0))]) ha0 lemma mul_self_inj_of_nonneg (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := (mul_self_eq_mul_self_iff a b).trans $ or_iff_left_of_imp $ λ h, by subst a; rw [le_antisymm (neg_nonneg.1 a0) b0, neg_zero] lemma div_le_div_of_le_left (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then by simp [ha0] else (div_le_div_left (lt_of_le_of_ne ha (ne.symm ha0)) (lt_of_lt_of_le hc h) hc).2 h lemma inv_le_inv_of_le (hb : 0 < b) (h : b ≤ a) : a⁻¹ ≤ b⁻¹ := begin rw [inv_eq_one_div, inv_eq_one_div], exact one_div_le_one_div_of_le hb h end lemma div_nonneg' (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := (lt_or_eq_of_le hb).elim (div_nonneg ha) (λ h, by simp [h.symm]) lemma div_le_div_of_le_of_nonneg (hab : a ≤ b) (hc : 0 ≤ c) : a / c ≤ b / c := mul_le_mul_of_nonneg_right hab (inv_nonneg.2 hc) end linear_ordered_field @[protect_proj] class discrete_linear_ordered_field (α : Type*) extends linear_ordered_field α, decidable_linear_ordered_comm_ring α section discrete_linear_ordered_field variables [discrete_linear_ordered_field α] lemma abs_div (a b : α) : abs (a / b) = abs a / abs b := decidable.by_cases (assume h : b = 0, by rw [h, abs_zero, div_zero, div_zero, abs_zero]) (assume h : b ≠ 0, have h₁ : abs b ≠ 0, from assume h₂, h (eq_zero_of_abs_eq_zero h₂), eq_div_of_mul_eq _ _ h₁ (show abs (a / b) * abs b = abs a, by rw [← abs_mul, div_mul_cancel _ h])) lemma abs_one_div (a : α) : abs (1 / a) = 1 / abs a := by rw [abs_div, abs_of_nonneg (zero_le_one : 1 ≥ (0 : α))] lemma abs_inv (a : α) : abs a⁻¹ = (abs a)⁻¹ := have h : abs (1 / a) = 1 / abs a, begin rw [abs_div, abs_of_nonneg], exact zero_le_one end, by simp [*] at * end discrete_linear_ordered_field
fbb406593f45bc980ce46d46a07bda4d48407760
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/geometry/manifold/whitney_embedding.lean
2532787d986f5cbf35d052f72b0c599c5026bcd9
[ "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
6,268
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 geometry.manifold.partition_of_unity /-! # Whitney embedding theorem In this file we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. ## TODO * Prove the weak Whitney embedding theorem: any `σ`-compact smooth `m`-dimensional manifold can be embedded into `ℝ^(2m+1)`. This requires a version of Sard's theorem: for a locally Lipschitz continuous map `f : ℝ^m → ℝ^n`, `m < n`, the range has Hausdorff dimension at most `m`, hence it has measure zero. ## Tags partition of unity, smooth bump function, whitney theorem -/ universes uι uE uH uM variables {ι : Type uι} {E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory namespace smooth_bump_covering /-! ### Whitney embedding theorem In this section we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. -/ variables [t2_space M] [fintype ι] {s : set M} (f : smooth_bump_covering ι I M s) /-- Smooth embedding of `M` into `(E × ℝ) ^ ι`. -/ def embedding_pi_tangent : C^∞⟮I, M; 𝓘(ℝ, ι → (E × ℝ)), ι → (E × ℝ)⟯ := { to_fun := λ x i, (f i x • ext_chart_at I (f.c i) x, f i x), times_cont_mdiff_to_fun := times_cont_mdiff_pi_space.2 $ λ i, ((f i).smooth_smul times_cont_mdiff_on_ext_chart_at).prod_mk_space ((f i).smooth) } local attribute [simp] lemma embedding_pi_tangent_coe : ⇑f.embedding_pi_tangent = λ x i, (f i x • ext_chart_at I (f.c i) x, f i x) := rfl lemma embedding_pi_tangent_inj_on : inj_on f.embedding_pi_tangent s := begin intros x hx y hy h, simp only [embedding_pi_tangent_coe, funext_iff] at h, obtain ⟨h₁, h₂⟩ := prod.mk.inj_iff.1 (h (f.ind x hx)), rw [f.apply_ind x hx] at h₂, rw [← h₂, f.apply_ind x hx, one_smul, one_smul] at h₁, have := f.mem_ext_chart_at_source_of_eq_one h₂.symm, exact (ext_chart_at I (f.c _)).inj_on (f.mem_ext_chart_at_ind_source x hx) this h₁ end lemma embedding_pi_tangent_injective (f : smooth_bump_covering ι I M) : injective f.embedding_pi_tangent := injective_iff_inj_on_univ.2 f.embedding_pi_tangent_inj_on lemma comp_embedding_pi_tangent_mfderiv (x : M) (hx : x ∈ s) : ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))).comp (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) = mfderiv I I (chart_at H (f.c (f.ind x hx))) x := begin set L := ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))), have := L.has_mfderiv_at.comp x f.embedding_pi_tangent.mdifferentiable_at.has_mfderiv_at, convert has_mfderiv_at_unique this _, refine (has_mfderiv_at_ext_chart_at I (f.mem_chart_at_ind_source x hx)).congr_of_eventually_eq _, refine (f.eventually_eq_one x hx).mono (λ y hy, _), simp only [embedding_pi_tangent_coe, continuous_linear_map.coe_comp', (∘), continuous_linear_map.coe_fst', continuous_linear_map.proj_apply], rw [hy, pi.one_apply, one_smul] end lemma embedding_pi_tangent_ker_mfderiv (x : M) (hx : x ∈ s) : (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x).ker = ⊥ := begin apply bot_unique, rw [← (mdifferentiable_chart I (f.c (f.ind x hx))).ker_mfderiv_eq_bot (f.mem_chart_at_ind_source x hx), ← comp_embedding_pi_tangent_mfderiv], exact linear_map.ker_le_ker_comp _ _ end lemma embedding_pi_tangent_injective_mfderiv (x : M) (hx : x ∈ s) : injective (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) := linear_map.ker_eq_bot.1 (f.embedding_pi_tangent_ker_mfderiv x hx) /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be immersed into the `n`-dimensional Euclidean space. -/ lemma exists_immersion_euclidean (f : smooth_bump_covering ι I M) : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ injective e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin set F := euclidean_space ℝ (fin $ finrank ℝ (ι → (E × ℝ))), letI : is_noetherian ℝ (E × ℝ) := is_noetherian.iff_fg.2 infer_instance, letI : finite_dimensional ℝ (ι → E × ℝ) := is_noetherian.iff_fg.1 infer_instance, set eEF : (ι → (E × ℝ)) ≃L[ℝ] F := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm, refine ⟨_, eEF ∘ f.embedding_pi_tangent, eEF.to_diffeomorph.smooth.comp f.embedding_pi_tangent.smooth, eEF.injective.comp f.embedding_pi_tangent_injective, λ x, _⟩, rw [mfderiv_comp _ eEF.differentiable_at.mdifferentiable_at f.embedding_pi_tangent.mdifferentiable_at, eEF.mfderiv_eq], exact eEF.injective.comp (f.embedding_pi_tangent_injective_mfderiv _ trivial) end end smooth_bump_covering /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be embedded into the `n`-dimensional Euclidean space. -/ lemma exists_embedding_euclidean_of_compact [t2_space M] [compact_space M] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ closed_embedding e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin rcases smooth_bump_covering.exists_is_subordinate I is_closed_univ (λ (x : M) _, univ_mem) with ⟨ι, f, -⟩, haveI := f.fintype, rcases f.exists_immersion_euclidean with ⟨n, e, hsmooth, hinj, hinj_mfderiv⟩, exact ⟨n, e, hsmooth, hsmooth.continuous.closed_embedding hinj, hinj_mfderiv⟩ end
dfc4dd21deecf9b4c44567f8acaba5cc5ce3fca6
59a4b050600ed7b3d5826a8478db0a9bdc190252
/src/category_theory/universal/comparisons/cones.lean
8ad327f99a6a15dcc3f5ea49bf8870079139807d
[]
no_license
rwbarton/lean-category-theory
f720268d800b62a25d69842ca7b5d27822f00652
00df814d463406b7a13a56f5dcda67758ba1b419
refs/heads/master
1,585,366,296,767
1,536,151,349,000
1,536,151,349,000
147,652,096
0
0
null
1,536,226,960,000
1,536,226,960,000
null
UTF-8
Lean
false
false
2,146
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.equivalence import category_theory.universal.cones import category_theory.universal.comma_categories open category_theory open category_theory.comma namespace category_theory.limits universes u v u₁ v₁ u₂ v₂ variables {J : Type v} [small_category J] {C : Type u} [𝒞 : category.{u v} C] variable {F : J ⥤ C} section include 𝒞 @[simp] lemma comma.Cone.commutativity (F : J ⥤ C) (X : C) (cone : ((DiagonalFunctor J C) X) ⟶ ((ObjectAsFunctor.{(max u v) v} F).obj punit.star)) {j k : J} (f : j ⟶ k) : cone j ≫ (F.map f) = cone k := by obviously def comma_Cone_to_Cone (c : (comma.Cone F)) : cone F := { X := c.1.1, π := λ j : J, (c.2) j } @[simp] lemma comma_Cone_to_Cone_cone_maps (c : (comma.Cone F)) (j : J) : (comma_Cone_to_Cone c).π j = (c.2) j := rfl def comma_ConeMorphism_to_ConeMorphism {X Y : (comma.Cone F)} (f : comma.comma_morphism X Y) : (comma_Cone_to_Cone X) ⟶ (comma_Cone_to_Cone Y) := { hom := f.left } def Cone_to_comma_Cone (c : cone F) : comma.Cone F := ⟨ (c.X, by obviously), { app := λ j, c.π j } ⟩ def ConeMorphism_to_comma_ConeMorphism {X Y : cone F} (f : cone_morphism X Y) : (Cone_to_comma_Cone X) ⟶ (Cone_to_comma_Cone Y) := { left := f.hom, right := by obviously } def comma_Cones_to_Cones (F : J ⥤ C) : (comma.Cone F) ⥤ (cone F) := { obj := comma_Cone_to_Cone, map' := λ X Y f, comma_ConeMorphism_to_ConeMorphism f } def Cones_to_comma_Cones (F : J ⥤ C) : (cone F) ⥤ (comma.Cone F) := { obj := Cone_to_comma_Cone, map' := λ X Y f, ConeMorphism_to_comma_ConeMorphism f }. end /- end `include 𝒞` -/ local attribute [back] category.id private meta def dsimp' := `[dsimp at * {unfold_reducible := tt, md := semireducible}] local attribute [tidy] dsimp' include 𝒞 def Cones_agree (F : J ⥤ C) : Equivalence (comma.Cone F) (cone F) := { functor := comma_Cones_to_Cones F, inverse := Cones_to_comma_Cones F } end category_theory.limits
76f88d2c0bc7493217edbaecfeac8ffeda310f9d
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Elab/Tactic/ElabTerm.lean
ba073d2cf0741aaf1ae34be696f00b7b509b78e8
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
9,261
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.CollectMVars import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Constructor import Lean.Meta.Tactic.Assert import Lean.Elab.Tactic.Basic import Lean.Elab.SyntheticMVars namespace Lean.Elab.Tactic open Meta /- `elabTerm` for Tactics and basic tactics that use it. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := withRef stx <| Term.withoutErrToSorry do let e ← Term.elabTerm stx expectedType? Term.synthesizeSyntheticMVars mayPostpone instantiateMVars e def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do let e ← elabTerm stx expectedType? mayPostpone -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here. match expectedType? with | none => return e | some expectedType => let eType ← inferType e unless (← isDefEq eType expectedType) do Term.throwTypeMismatchError none expectedType eType e return e /- Try to close main goal using `x target`, where `target` is the type of the main goal. -/ def closeMainGoalUsing (x : Expr → TacticM Expr) : TacticM Unit := withMainContext do closeMainGoal (← x (← getMainTarget)) @[builtinTactic «exact»] def evalExact : Tactic := fun stx => match stx with | `(tactic| exact $e) => closeMainGoalUsing (fun type => elabTermEnsuringType e type) | _ => throwUnsupportedSyntax def elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := do let val ← elabTermEnsuringType stx expectedType? let newMVarIds ← getMVarsNoDelayed val /- ignore let-rec auxiliary variables, they are synthesized automatically later -/ let newMVarIds ← newMVarIds.filterM fun mvarId => return !(← Term.isLetRecAuxMVar mvarId) let newMVarIds ← if allowNaturalHoles then pure newMVarIds.toList else let naturalMVarIds ← newMVarIds.filterM fun mvarId => return (← getMVarDecl mvarId).kind.isNatural let syntheticMVarIds ← newMVarIds.filterM fun mvarId => return !(← getMVarDecl mvarId).kind.isNatural discard <| Term.logUnassignedUsingErrorInfos naturalMVarIds pure syntheticMVarIds.toList tagUntaggedGoals (← getMainTag) tagSuffix newMVarIds pure (val, newMVarIds) /- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned "natural" metavariables. Recall that "natutal" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be filled by typing constraints. "Synthetic" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/ def refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do withMainContext do let (val, mvarIds') ← elabTermWithHoles stx (← getMainTarget) tagSuffix allowNaturalHoles assignExprMVar (← getMainGoal) val replaceMainGoal mvarIds' @[builtinTactic «refine»] def evalRefine : Tactic := fun stx => match stx with | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false) | _ => throwUnsupportedSyntax @[builtinTactic «refine'»] def evalRefine' : Tactic := fun stx => match stx with | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true) | _ => throwUnsupportedSyntax /-- Given a tactic ``` apply f ``` we want the `apply` tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. A similar method is also used in Lean 3. This method is useful when applying lemmas such as: ``` theorem infLeRight {s t : Set α} : s ⊓ t ≤ t ``` where `s ≤ t` here is defined as ``` ∀ {x : α}, x ∈ s → x ∈ t ``` -/ def elabTermForApply (stx : Syntax) : TacticM Expr := do if stx.isIdent then match (← Term.resolveId? stx) with | some e => return e | _ => pure () elabTerm stx none (mayPostpone := true) def evalApplyLikeTactic (tac : MVarId → Expr → MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do withMainContext do let val ← elabTermForApply e let mvarIds' ← tac (← getMainGoal) val Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' @[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx => match stx with | `(tactic| apply $e) => evalApplyLikeTactic Meta.apply e | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.existsIntro] def evalExistsIntro : Tactic := fun stx => match stx with | `(tactic| exists $e) => evalApplyLikeTactic (fun mvarId e => return [(← Meta.existsIntro mvarId e)]) e | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx => withReducible <| evalTactic stx[1] @[builtinTactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx => withReducibleAndInstances <| evalTactic stx[1] /-- Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable. Note that, the main goal is updated when `Meta.assert` is used in the second case. -/ def elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId := withMainContext do let e ← elabTerm stx none match e with | Expr.fvar fvarId _ => pure fvarId | _ => let type ← inferType e let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do let mvarId ← getMainGoal let (fvarId, mvarId) ← liftMetaM do let mvarId ← Meta.assert mvarId userName type e Meta.intro1Core mvarId preserveBinderNames replaceMainGoal [mvarId] return fvarId match userName? with | none => intro `h false | some userName => intro userName true @[builtinTactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx => match stx with | `(tactic| rename $typeStx:term => $h:ident) => do withMainContext do let fvarId ← withoutModifyingState <| withNewMCtxDepth do let type ← elabTerm typeStx none (mayPostpone := true) let fvarId? ← (← getLCtx).findDeclRevM? fun localDecl => do if (← isDefEq type localDecl.type) then return localDecl.fvarId else return none match fvarId? with | none => throwError "failed to find a hypothesis with type{indentExpr type}" | some fvarId => return fvarId let lctxNew := (← getLCtx).setUserName fvarId h.getId let mvarNew ← mkFreshExprMVarAt lctxNew (← getLocalInstances) (← getMainTarget) MetavarKind.syntheticOpaque (← getMainTag) assignExprMVar (← getMainGoal) mvarNew replaceMainGoal [mvarNew.mvarId!] | _ => throwUnsupportedSyntax /-- Make sure `expectedType` does not contain free and metavariables. It applies zeta-reduction to eliminate let-free-vars. -/ private def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do let mut expectedType ← instantiateMVars expectedType if expectedType.hasFVar then expectedType ← zetaReduce expectedType if expectedType.hasFVar || expectedType.hasMVar then throwError "expected type must not contain free or meta variables{indentExpr expectedType}" return expectedType @[builtinTactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun stx => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let d ← instantiateMVars d let r ← withDefault <| whnf d unless r.isConstOf ``true do throwError "failed to reduce to 'true'{indentExpr r}" let s := d.appArg! -- get instance from `d` let rflPrf ← mkEqRefl (toExpr true) return mkApp3 (Lean.mkConst `ofDecideEqTrue) expectedType s rflPrf private def mkNativeAuxDecl (baseName : Name) (type val : Expr) : TermElabM Name := do let auxName ← Term.mkAuxName baseName let decl := Declaration.defnDecl { name := auxName, levelParams := [], type := type, value := val, hints := ReducibilityHints.abbrev, safety := DefinitionSafety.safe } addDecl decl compileDecl decl pure auxName @[builtinTactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun stx => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let auxDeclName ← mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d let rflPrf ← mkEqRefl (toExpr true) let s := d.appArg! -- get instance from `d` return mkApp3 (Lean.mkConst `ofDecideEqTrue) expectedType s <| mkApp3 (Lean.mkConst `Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf end Lean.Elab.Tactic
7abc51a137ae6fb474be9ba65325f3ff8c1dec81
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/class6.lean
9897342e86b9864526f86194af6823b97e432722
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
293
lean
import standard using pair inductive t1 : Type := | mk1 : t1 inductive t2 : Type := | mk2 : t2 theorem inhabited_t1 : inhabited t1 := inhabited_intro mk1 theorem inhabited_t2 : inhabited t2 := inhabited_intro mk2 instance inhabited_t1 inhabited_t2 theorem T : inhabited (t1 × t2) := _
b242774753f775ab662b2750246b65b0cb20d067
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world3/level2.lean
32e85e82890c085fc94859702798ee149166292b
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
793
lean
import game.world3.level1 -- hide import mynat.mul -- hide namespace mynat -- hide /- # Multiplication World ## Level 2: `mul_one` Remember that you can see everything you have proved so far about multiplication in the drop-down box on the left (and that this list will grow as we proceed). In this level we'll need to use * `one_eq_succ_zero : 1 = succ(0)` which was mentioned back in Addition World and which will be a useful thing to rewrite right now, as we begin to prove a couple of lemmas about how `1` behaves with respect to multiplication. -/ /- Lemma For any natural number $m$, we have $$ m \times 1 = m. $$ -/ lemma mul_one (m : mynat) : m * 1 = m := begin [less_leaky] rw one_eq_succ_zero, rw mul_succ, rw mul_zero, rw zero_add, refl end end mynat -- hide
ce86558eaad4adb564a309ac751e1b91f0be7036
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/apply_tac_bug.lean
fe5bb8224e9492da905cc059aa445a4007ac7699
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
338
lean
import macros import tactic theorem my_proof_irrel {a b : Bool} (H1 : a) (H2 : b) : H1 == H2 := let H1b : b := cast (by simp) H1, H1_eq_H1b : H1 == H1b := hsymm (cast_heq (by simp) H1), H1b_eq_H2 : H1b == H2 := to_heq (proof_irrel H1b H2) in htrans H1_eq_H1b H1b_eq_H2
1037218c58921233f68d65e563264dbc2b771ffc
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/pkg/user_ext/UserExt/FooExt.lean
686ec53f824b3203b0078e5bd285f553d8d88784
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
858
lean
import Lean open Lean initialize fooExtension : SimplePersistentEnvExtension Name NameSet ← registerSimplePersistentEnvExtension { name := `fooExt addEntryFn := NameSet.insert addImportedFn := fun es => mkStateFromImportedEntries NameSet.insert {} es } initialize registerTraceClass `myDebug syntax (name := insertFoo) "insert_foo " ident : command syntax (name := showFoo) "show_foo_set" : command open Lean.Elab open Lean.Elab.Command @[commandElab insertFoo] def elabInsertFoo : CommandElab := fun stx => do trace[myDebug] "testing trace message at insert foo '{stx}'" IO.println s!"inserting {stx[1].getId}" modifyEnv fun env => fooExtension.addEntry env stx[1].getId @[commandElab showFoo] def elabShowFoo : CommandElab := fun stx => do IO.println s!"foo set: {fooExtension.getState (← getEnv) |>.toList}"
623ebab67411ab26bfad733b0865d18d2a843fcc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/autoBoundPostponeLoop.lean
24b7a911dfe57967de24f8ff9e94a8048583cd96
[ "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
131
lean
theorem ex (h₁ : α = β) (as : List α) (bs : List β) (h₂ : (h ▸ as) = bs) : True := True.intro
cc083086c25971456d953ec13fc7300437c2e25d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/decomposition/jordan.lean
e8d1f7ec11632339073e52645aa7dead45ad3029
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
25,242
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.decomposition.signed_hahn import measure_theory.measure.mutually_singular /-! # Jordan decomposition This file proves the existence and uniqueness of the Jordan decomposition for signed measures. The Jordan decomposition theorem states that, given a signed measure `s`, there exists a unique pair of mutually singular measures `μ` and `ν`, such that `s = μ - ν`. The Jordan decomposition theorem for measures is a corollary of the Hahn decomposition theorem and is useful for the Lebesgue decomposition theorem. ## Main definitions * `measure_theory.jordan_decomposition`: a Jordan decomposition of a measurable space is a pair of mutually singular finite measures. We say `j` is a Jordan decomposition of a signed measure `s` if `s = j.pos_part - j.neg_part`. * `measure_theory.signed_measure.to_jordan_decomposition`: the Jordan decomposition of a signed measure. * `measure_theory.signed_measure.to_jordan_decomposition_equiv`: is the `equiv` between `measure_theory.signed_measure` and `measure_theory.jordan_decomposition` formed by `measure_theory.signed_measure.to_jordan_decomposition`. ## Main results * `measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition` : the Jordan decomposition theorem. * `measure_theory.jordan_decomposition.to_signed_measure_injective` : the Jordan decomposition of a signed measure is unique. ## Tags Jordan decomposition theorem -/ noncomputable theory open_locale classical measure_theory ennreal nnreal variables {α β : Type*} [measurable_space α] namespace measure_theory /-- A Jordan decomposition of a measurable space is a pair of mutually singular, finite measures. -/ @[ext] structure jordan_decomposition (α : Type*) [measurable_space α] := (pos_part neg_part : measure α) [pos_part_finite : is_finite_measure pos_part] [neg_part_finite : is_finite_measure neg_part] (mutually_singular : pos_part ⊥ₘ neg_part) attribute [instance] jordan_decomposition.pos_part_finite attribute [instance] jordan_decomposition.neg_part_finite namespace jordan_decomposition open measure vector_measure variable (j : jordan_decomposition α) instance : has_zero (jordan_decomposition α) := { zero := ⟨0, 0, mutually_singular.zero_right⟩ } instance : inhabited (jordan_decomposition α) := { default := 0 } instance : has_neg (jordan_decomposition α) := { neg := λ j, ⟨j.neg_part, j.pos_part, j.mutually_singular.symm⟩ } instance : has_scalar ℝ≥0 (jordan_decomposition α) := { smul := λ r j, ⟨r • j.pos_part, r • j.neg_part, mutually_singular.smul _ (mutually_singular.smul _ j.mutually_singular.symm).symm⟩ } instance has_scalar_real : has_scalar ℝ (jordan_decomposition α) := { smul := λ r j, if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) } @[simp] lemma zero_pos_part : (0 : jordan_decomposition α).pos_part = 0 := rfl @[simp] lemma zero_neg_part : (0 : jordan_decomposition α).neg_part = 0 := rfl @[simp] lemma neg_pos_part : (-j).pos_part = j.neg_part := rfl @[simp] lemma neg_neg_part : (-j).neg_part = j.pos_part := rfl @[simp] lemma smul_pos_part (r : ℝ≥0) : (r • j).pos_part = r • j.pos_part := rfl @[simp] lemma smul_neg_part (r : ℝ≥0) : (r • j).neg_part = r • j.neg_part := rfl lemma real_smul_def (r : ℝ) (j : jordan_decomposition α) : r • j = if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) := rfl @[simp] lemma coe_smul (r : ℝ≥0) : (r : ℝ) • j = r • j := show dite _ _ _ = _, by rw [dif_pos (nnreal.coe_nonneg r), real.to_nnreal_coe] lemma real_smul_nonneg (r : ℝ) (hr : 0 ≤ r) : r • j = r.to_nnreal • j := dif_pos hr lemma real_smul_neg (r : ℝ) (hr : r < 0) : r • j = - ((-r).to_nnreal • j) := dif_neg (not_le.2 hr) lemma real_smul_pos_part_nonneg (r : ℝ) (hr : 0 ≤ r) : (r • j).pos_part = r.to_nnreal • j.pos_part := by { rw [real_smul_def, ← smul_pos_part, dif_pos hr] } lemma real_smul_neg_part_nonneg (r : ℝ) (hr : 0 ≤ r) : (r • j).neg_part = r.to_nnreal • j.neg_part := by { rw [real_smul_def, ← smul_neg_part, dif_pos hr] } lemma real_smul_pos_part_neg (r : ℝ) (hr : r < 0) : (r • j).pos_part = (-r).to_nnreal • j.neg_part := by { rw [real_smul_def, ← smul_neg_part, dif_neg (not_le.2 hr), neg_pos_part] } lemma real_smul_neg_part_neg (r : ℝ) (hr : r < 0) : (r • j).neg_part = (-r).to_nnreal • j.pos_part := by { rw [real_smul_def, ← smul_pos_part, dif_neg (not_le.2 hr), neg_neg_part] } /-- The signed measure associated with a Jordan decomposition. -/ def to_signed_measure : signed_measure α := j.pos_part.to_signed_measure - j.neg_part.to_signed_measure lemma to_signed_measure_zero : (0 : jordan_decomposition α).to_signed_measure = 0 := begin ext1 i hi, erw [to_signed_measure, to_signed_measure_sub_apply hi, sub_self, zero_apply], end lemma to_signed_measure_neg : (-j).to_signed_measure = -j.to_signed_measure := begin ext1 i hi, rw [neg_apply, to_signed_measure, to_signed_measure, to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, neg_sub], refl, end lemma to_signed_measure_smul (r : ℝ≥0) : (r • j).to_signed_measure = r • j.to_signed_measure := begin ext1 i hi, rw [vector_measure.smul_apply, to_signed_measure, to_signed_measure, to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, smul_sub, smul_pos_part, smul_neg_part, ← ennreal.to_real_smul, ← ennreal.to_real_smul], refl end /-- A Jordan decomposition provides a Hahn decomposition. -/ lemma exists_compl_positive_negative : ∃ S : set α, measurable_set S ∧ j.to_signed_measure ≤[S] 0 ∧ 0 ≤[Sᶜ] j.to_signed_measure ∧ j.pos_part S = 0 ∧ j.neg_part Sᶜ = 0 := begin obtain ⟨S, hS₁, hS₂, hS₃⟩ := j.mutually_singular, refine ⟨S, hS₁, _, _, hS₂, hS₃⟩, { refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _), rw [to_signed_measure, to_signed_measure_sub_apply hA, show j.pos_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₂ ▸ measure_mono hA₁), ennreal.zero_to_real, zero_sub, neg_le, zero_apply, neg_zero], exact ennreal.to_real_nonneg }, { refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _), rw [to_signed_measure, to_signed_measure_sub_apply hA, show j.neg_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₃ ▸ measure_mono hA₁), ennreal.zero_to_real, sub_zero], exact ennreal.to_real_nonneg }, end end jordan_decomposition namespace signed_measure open measure vector_measure jordan_decomposition classical variables {s : signed_measure α} {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] /-- Given a signed measure `s`, `s.to_jordan_decomposition` is the Jordan decomposition `j`, such that `s = j.to_signed_measure`. This property is known as the Jordan decomposition theorem, and is shown by `measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition`. -/ def to_jordan_decomposition (s : signed_measure α) : jordan_decomposition α := let i := some s.exists_compl_positive_negative in let hi := some_spec s.exists_compl_positive_negative in { pos_part := s.to_measure_of_zero_le i hi.1 hi.2.1, neg_part := s.to_measure_of_le_zero iᶜ hi.1.compl hi.2.2, pos_part_finite := infer_instance, neg_part_finite := infer_instance, mutually_singular := begin refine ⟨iᶜ, hi.1.compl, _, _⟩, { rw [to_measure_of_zero_le_apply _ _ hi.1 hi.1.compl], simp }, { rw [to_measure_of_le_zero_apply _ _ hi.1.compl hi.1.compl.compl], simp } end } lemma to_jordan_decomposition_spec (s : signed_measure α) : ∃ (i : set α) (hi₁ : measurable_set i) (hi₂ : 0 ≤[i] s) (hi₃ : s ≤[iᶜ] 0), s.to_jordan_decomposition.pos_part = s.to_measure_of_zero_le i hi₁ hi₂ ∧ s.to_jordan_decomposition.neg_part = s.to_measure_of_le_zero iᶜ hi₁.compl hi₃ := begin set i := some s.exists_compl_positive_negative, obtain ⟨hi₁, hi₂, hi₃⟩ := some_spec s.exists_compl_positive_negative, exact ⟨i, hi₁, hi₂, hi₃, rfl, rfl⟩, end /-- **The Jordan decomposition theorem**: Given a signed measure `s`, there exists a pair of mutually singular measures `μ` and `ν` such that `s = μ - ν`. In this case, the measures `μ` and `ν` are given by `s.to_jordan_decomposition.pos_part` and `s.to_jordan_decomposition.neg_part` respectively. Note that we use `measure_theory.jordan_decomposition.to_signed_measure` to represent the signed measure corresponding to `s.to_jordan_decomposition.pos_part - s.to_jordan_decomposition.neg_part`. -/ @[simp] lemma to_signed_measure_to_jordan_decomposition (s : signed_measure α) : s.to_jordan_decomposition.to_signed_measure = s := begin obtain ⟨i, hi₁, hi₂, hi₃, hμ, hν⟩ := s.to_jordan_decomposition_spec, simp only [jordan_decomposition.to_signed_measure, hμ, hν], ext k hk, rw [to_signed_measure_sub_apply hk, to_measure_of_zero_le_apply _ hi₂ hi₁ hk, to_measure_of_le_zero_apply _ hi₃ hi₁.compl hk], simp only [ennreal.coe_to_real, subtype.coe_mk, ennreal.some_eq_coe, sub_neg_eq_add], rw [← of_union _ (measurable_set.inter hi₁ hk) (measurable_set.inter hi₁.compl hk), set.inter_comm i, set.inter_comm iᶜ, set.inter_union_compl _ _], { apply_instance }, { rintro x ⟨⟨hx₁, _⟩, hx₂, _⟩, exact false.elim (hx₂ hx₁) } end section variables {u v w : set α} /-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a positive set `u`. -/ lemma subset_positive_null_set (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : 0 ≤[u] s) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 := begin have : s v + s (w \ v) = 0, { rw [← hw₁, ← of_union set.disjoint_diff hv (hw.diff hv), set.union_diff_self, set.union_eq_self_of_subset_left hwt], apply_instance }, have h₁ := nonneg_of_zero_le_restrict _ (restrict_le_restrict_subset _ _ hu hsu (hwt.trans hw₂)), have h₂ := nonneg_of_zero_le_restrict _ (restrict_le_restrict_subset _ _ hu hsu ((w.diff_subset v).trans hw₂)), linarith, end /-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a negative set `u`. -/ lemma subset_negative_null_set (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : s ≤[u] 0) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, have := subset_positive_null_set hu hv hw hsu, simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this, exact this hw₁ hw₂ hwt, end /-- If the symmetric difference of two positive sets is a null-set, then so are the differences between the two sets. -/ lemma of_diff_eq_zero_of_symm_diff_eq_zero_positive (hu : measurable_set u) (hv : measurable_set v) (hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u Δ v) = 0) : s (u \ v) = 0 ∧ s (v \ u) = 0 := begin rw restrict_le_restrict_iff at hsu hsv, have a := hsu (hu.diff hv) (u.diff_subset v), have b := hsv (hv.diff hu) (v.diff_subset u), erw [of_union (set.disjoint_of_subset_left (u.diff_subset v) set.disjoint_diff) (hu.diff hv) (hv.diff hu)] at hs, rw zero_apply at a b, split, all_goals { linarith <|> apply_instance <|> assumption }, end /-- If the symmetric difference of two negative sets is a null-set, then so are the differences between the two sets. -/ lemma of_diff_eq_zero_of_symm_diff_eq_zero_negative (hu : measurable_set u) (hv : measurable_set v) (hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u Δ v) = 0) : s (u \ v) = 0 ∧ s (v \ u) = 0 := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv, have := of_diff_eq_zero_of_symm_diff_eq_zero_positive hu hv hsu hsv, simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this, exact this hs, end lemma of_inter_eq_of_symm_diff_eq_zero_positive (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u Δ v) = 0) : s (w ∩ u) = s (w ∩ v) := begin have hwuv : s ((w ∩ u) Δ (w ∩ v)) = 0, { refine subset_positive_null_set (hu.union hv) ((hw.inter hu).symm_diff (hw.inter hv)) (hu.symm_diff hv) (restrict_le_restrict_union _ _ hu hsu hv hsv) hs _ _, { exact symm_diff_le_sup u v }, { rintro x (⟨⟨hxw, hxu⟩, hx⟩ | ⟨⟨hxw, hxv⟩, hx⟩); rw [set.mem_inter_eq, not_and] at hx, { exact or.inl ⟨hxu, hx hxw⟩ }, { exact or.inr ⟨hxv, hx hxw⟩ } } }, obtain ⟨huv, hvu⟩ := of_diff_eq_zero_of_symm_diff_eq_zero_positive (hw.inter hu) (hw.inter hv) (restrict_le_restrict_subset _ _ hu hsu (w.inter_subset_right u)) (restrict_le_restrict_subset _ _ hv hsv (w.inter_subset_right v)) hwuv, rw [← of_diff_of_diff_eq_zero (hw.inter hu) (hw.inter hv) hvu, huv, zero_add] end lemma of_inter_eq_of_symm_diff_eq_zero_negative (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u Δ v) = 0) : s (w ∩ u) = s (w ∩ v) := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv, have := of_inter_eq_of_symm_diff_eq_zero_positive hu hv hw hsu hsv, simp only [pi.neg_apply, neg_inj, neg_eq_zero, coe_neg] at this, exact this hs, end end end signed_measure namespace jordan_decomposition open measure vector_measure signed_measure function private lemma eq_of_pos_part_eq_pos_part {j₁ j₂ : jordan_decomposition α} (hj : j₁.pos_part = j₂.pos_part) (hj' : j₁.to_signed_measure = j₂.to_signed_measure) : j₁ = j₂ := begin ext1, { exact hj }, { rw ← to_signed_measure_eq_to_signed_measure_iff, suffices : j₁.pos_part.to_signed_measure - j₁.neg_part.to_signed_measure = j₁.pos_part.to_signed_measure - j₂.neg_part.to_signed_measure, { exact sub_right_inj.mp this }, convert hj' } end /-- The Jordan decomposition of a signed measure is unique. -/ theorem to_signed_measure_injective : injective $ @jordan_decomposition.to_signed_measure α _ := begin /- The main idea is that two Jordan decompositions of a signed measure provide two Hahn decompositions for that measure. Then, from `of_symm_diff_compl_positive_negative`, the symmetric difference of the two Hahn decompositions has measure zero, thus, allowing us to show the equality of the underlying measures of the Jordan decompositions. -/ intros j₁ j₂ hj, -- obtain the two Hahn decompositions from the Jordan decompositions obtain ⟨S, hS₁, hS₂, hS₃, hS₄, hS₅⟩ := j₁.exists_compl_positive_negative, obtain ⟨T, hT₁, hT₂, hT₃, hT₄, hT₅⟩ := j₂.exists_compl_positive_negative, rw ← hj at hT₂ hT₃, -- the symmetric differences of the two Hahn decompositions have measure zero obtain ⟨hST₁, -⟩ := of_symm_diff_compl_positive_negative hS₁.compl hT₁.compl ⟨hS₃, (compl_compl S).symm ▸ hS₂⟩ ⟨hT₃, (compl_compl T).symm ▸ hT₂⟩, -- it suffices to show the Jordan decompositions have the same positive parts refine eq_of_pos_part_eq_pos_part _ hj, ext1 i hi, -- we see that the positive parts of the two Jordan decompositions are equal to their -- associated signed measures restricted on their associated Hahn decompositions have hμ₁ : (j₁.pos_part i).to_real = j₁.to_signed_measure (i ∩ Sᶜ), { rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hS₁.compl), show j₁.neg_part (i ∩ Sᶜ) = 0, by exact nonpos_iff_eq_zero.1 (hS₅ ▸ measure_mono (set.inter_subset_right _ _)), ennreal.zero_to_real, sub_zero], conv_lhs { rw ← set.inter_union_compl i S }, rw [measure_union, show j₁.pos_part (i ∩ S) = 0, by exact nonpos_iff_eq_zero.1 (hS₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add], { refine set.disjoint_of_subset_left (set.inter_subset_right _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) }, { exact hi.inter hS₁.compl } }, have hμ₂ : (j₂.pos_part i).to_real = j₂.to_signed_measure (i ∩ Tᶜ), { rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hT₁.compl), show j₂.neg_part (i ∩ Tᶜ) = 0, by exact nonpos_iff_eq_zero.1 (hT₅ ▸ measure_mono (set.inter_subset_right _ _)), ennreal.zero_to_real, sub_zero], conv_lhs { rw ← set.inter_union_compl i T }, rw [measure_union, show j₂.pos_part (i ∩ T) = 0, by exact nonpos_iff_eq_zero.1 (hT₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add], { exact set.disjoint_of_subset_left (set.inter_subset_right _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) }, { exact hi.inter hT₁.compl } }, -- since the two signed measures associated with the Jordan decompositions are the same, -- and the symmetric difference of the Hahn decompositions have measure zero, the result follows rw [← ennreal.to_real_eq_to_real (measure_ne_top _ _) (measure_ne_top _ _), hμ₁, hμ₂, ← hj], exact of_inter_eq_of_symm_diff_eq_zero_positive hS₁.compl hT₁.compl hi hS₃ hT₃ hST₁, all_goals { apply_instance }, end @[simp] lemma to_jordan_decomposition_to_signed_measure (j : jordan_decomposition α) : (j.to_signed_measure).to_jordan_decomposition = j := (@to_signed_measure_injective _ _ j (j.to_signed_measure).to_jordan_decomposition (by simp)).symm end jordan_decomposition namespace signed_measure open jordan_decomposition /-- `measure_theory.signed_measure.to_jordan_decomposition` and `measure_theory.jordan_decomposition.to_signed_measure` form a `equiv`. -/ @[simps apply symm_apply] def to_jordan_decomposition_equiv (α : Type*) [measurable_space α] : signed_measure α ≃ jordan_decomposition α := { to_fun := to_jordan_decomposition, inv_fun := to_signed_measure, left_inv := to_signed_measure_to_jordan_decomposition, right_inv := to_jordan_decomposition_to_signed_measure } lemma to_jordan_decomposition_zero : (0 : signed_measure α).to_jordan_decomposition = 0 := begin apply to_signed_measure_injective, simp [to_signed_measure_zero], end lemma to_jordan_decomposition_neg (s : signed_measure α) : (-s).to_jordan_decomposition = -s.to_jordan_decomposition := begin apply to_signed_measure_injective, simp [to_signed_measure_neg], end lemma to_jordan_decomposition_smul (s : signed_measure α) (r : ℝ≥0) : (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin apply to_signed_measure_injective, simp [to_signed_measure_smul], end private lemma to_jordan_decomposition_smul_real_nonneg (s : signed_measure α) (r : ℝ) (hr : 0 ≤ r): (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin lift r to ℝ≥0 using hr, rw [jordan_decomposition.coe_smul, ← to_jordan_decomposition_smul], refl end lemma to_jordan_decomposition_smul_real (s : signed_measure α) (r : ℝ) : (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin by_cases hr : 0 ≤ r, { exact to_jordan_decomposition_smul_real_nonneg s r hr }, { ext1, { rw [real_smul_pos_part_neg _ _ (not_le.1 hr), show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg, neg_pos_part, to_jordan_decomposition_smul_real_nonneg, ← smul_neg_part, real_smul_nonneg], all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } }, { rw [real_smul_neg_part_neg _ _ (not_le.1 hr), show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg, neg_neg_part, to_jordan_decomposition_smul_real_nonneg, ← smul_pos_part, real_smul_nonneg], all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } } } end lemma to_jordan_decomposition_eq {s : signed_measure α} {j : jordan_decomposition α} (h : s = j.to_signed_measure) : s.to_jordan_decomposition = j := by rw [h, to_jordan_decomposition_to_signed_measure] /-- The total variation of a signed measure. -/ def total_variation (s : signed_measure α) : measure α := s.to_jordan_decomposition.pos_part + s.to_jordan_decomposition.neg_part lemma total_variation_zero : (0 : signed_measure α).total_variation = 0 := by simp [total_variation, to_jordan_decomposition_zero] lemma total_variation_neg (s : signed_measure α) : (-s).total_variation = s.total_variation := by simp [total_variation, to_jordan_decomposition_neg, add_comm] lemma null_of_total_variation_zero (s : signed_measure α) {i : set α} (hs : s.total_variation i = 0) : s i = 0 := begin rw [total_variation, measure.coe_add, pi.add_apply, add_eq_zero_iff] at hs, rw [← to_signed_measure_to_jordan_decomposition s, to_signed_measure, vector_measure.coe_sub, pi.sub_apply, measure.to_signed_measure_apply, measure.to_signed_measure_apply], by_cases hi : measurable_set i, { rw [if_pos hi, if_pos hi], simp [hs.1, hs.2] }, { simp [if_neg hi] } end lemma absolutely_continuous_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) : s ≪ᵥ μ ↔ s.total_variation ≪ μ.ennreal_to_measure := begin split; intro h, { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec, rw [total_variation, measure.add_apply, hpos, hneg, to_measure_of_zero_le_apply _ _ _ hS₁, to_measure_of_le_zero_apply _ _ _ hS₁], rw ← vector_measure.absolutely_continuous.ennreal_to_measure at h, simp [h (measure_mono_null (i.inter_subset_right S) hS₂), h (measure_mono_null (iᶜ.inter_subset_right S) hS₂)] }, { refine vector_measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), rw ← vector_measure.ennreal_to_measure_apply hS₁ at hS₂, exact null_of_total_variation_zero s (h hS₂) } end lemma total_variation_absolutely_continuous_iff (s : signed_measure α) (μ : measure α) : s.total_variation ≪ μ ↔ s.to_jordan_decomposition.pos_part ≪ μ ∧ s.to_jordan_decomposition.neg_part ≪ μ := begin split; intro h, { split, all_goals { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), have := h hS₂, rw [total_variation, measure.add_apply, add_eq_zero_iff] at this }, exacts [this.1, this.2] }, { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), rw [total_variation, measure.add_apply, h.1 hS₂, h.2 hS₂, add_zero] } end -- TODO: Generalize to vector measures once total variation on vector measures is defined lemma mutually_singular_iff (s t : signed_measure α) : s ⊥ᵥ t ↔ s.total_variation ⊥ₘ t.total_variation := begin split, { rintro ⟨u, hmeas, hu₁, hu₂⟩, obtain ⟨i, hi₁, hi₂, hi₃, hipos, hineg⟩ := s.to_jordan_decomposition_spec, obtain ⟨j, hj₁, hj₂, hj₃, hjpos, hjneg⟩ := t.to_jordan_decomposition_spec, refine ⟨u, hmeas, _, _⟩, { rw [total_variation, measure.add_apply, hipos, hineg, to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas], simp [hu₁ _ (set.inter_subset_right _ _)] }, { rw [total_variation, measure.add_apply, hjpos, hjneg, to_measure_of_zero_le_apply _ _ _ hmeas.compl, to_measure_of_le_zero_apply _ _ _ hmeas.compl], simp [hu₂ _ (set.inter_subset_right _ _)] } }, { rintro ⟨u, hmeas, hu₁, hu₂⟩, exact ⟨u, hmeas, (λ t htu, null_of_total_variation_zero _ (measure_mono_null htu hu₁)), (λ t htv, null_of_total_variation_zero _ (measure_mono_null htv hu₂))⟩ } end lemma mutually_singular_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) : s ⊥ᵥ μ ↔ s.total_variation ⊥ₘ μ.ennreal_to_measure := begin split, { rintro ⟨u, hmeas, hu₁, hu₂⟩, obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec, refine ⟨u, hmeas, _, _⟩, { rw [total_variation, measure.add_apply, hpos, hneg, to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas], simp [hu₁ _ (set.inter_subset_right _ _)] }, { rw vector_measure.ennreal_to_measure_apply hmeas.compl, exact hu₂ _ (set.subset.refl _) } }, { rintro ⟨u, hmeas, hu₁, hu₂⟩, refine vector_measure.mutually_singular.mk u hmeas (λ t htu _, null_of_total_variation_zero _ (measure_mono_null htu hu₁)) (λ t htv hmt, _), rw ← vector_measure.ennreal_to_measure_apply hmt, exact measure_mono_null htv hu₂ } end lemma total_variation_mutually_singular_iff (s : signed_measure α) (μ : measure α) : s.total_variation ⊥ₘ μ ↔ s.to_jordan_decomposition.pos_part ⊥ₘ μ ∧ s.to_jordan_decomposition.neg_part ⊥ₘ μ := measure.mutually_singular.add_left_iff end signed_measure end measure_theory
44c67612dda925a1ab83164f7acf6230af2fd93f
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex49.lean
0261a72d987fab3db6b9b1e409d3cb0d36495a29
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
553
lean
variables (A : Type) (p q : A → Prop) example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x := exists.elim h (take w, assume hw : p w ∧ q w, show ∃ x, q x ∧ p x, from ⟨w, hw^.right, hw^.left⟩) example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x := match h with | ⟨w, hw⟩ := ⟨w, hw^.right, hw^.left⟩ end example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x := match h with | ⟨w, hpw, hqw⟩ := ⟨w, hqw, hpw⟩ end example : (∃ x, p x ∧ q x) → ∃ x, q x ∧ p x := assume ⟨w, hpw, hqw⟩, ⟨w, hqw, hpw⟩
e2230641762c0a9d70b8d9dfe772cd968b591333
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/pfun.lean
9725b94e6207c4bd056ab86a3fd1a1f99d3c47cd
[ "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
22,200
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Jeremy Avigad -/ import data.set.basic data.equiv.basic data.rel logic.relator /-- `roption α` is the type of "partial values" of type `α`. It is similar to `option α` except the domain condition can be an arbitrary proposition, not necessarily decidable. -/ structure {u} roption (α : Type u) : Type u := (dom : Prop) (get : dom → α) namespace roption variables {α : Type*} {β : Type*} {γ : Type*} /-- Convert an `roption α` with a decidable domain to an option -/ def to_option (o : roption α) [decidable o.dom] : option α := if h : dom o then some (o.get h) else none /-- `roption` extensionality -/ def ext' : Π {o p : roption α} (H1 : o.dom ↔ p.dom) (H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p | ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1, by cases t; rw [show o = p, from funext $ λp, H2 p p] /-- `roption` eta expansion -/ @[simp] theorem eta : Π (o : roption α), (⟨o.dom, λ h, o.get h⟩ : roption α) = o | ⟨h, f⟩ := rfl /-- `a ∈ o` means that `o` is defined and equal to `a` -/ protected def mem (a : α) (o : roption α) : Prop := ∃ h, o.get h = a instance : has_mem α (roption α) := ⟨roption.mem⟩ theorem mem_eq (a : α) (o : roption α) : (a ∈ o) = (∃ h, o.get h = a) := rfl theorem dom_iff_mem : ∀ {o : roption α}, o.dom ↔ ∃y, y ∈ o | ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩ theorem get_mem {o : roption α} (h) : get o h ∈ o := ⟨_, rfl⟩ /-- `roption` extensionality -/ def ext {o p : roption α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p := ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst, λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $ λ a b, ((H _).2 ⟨_, rfl⟩).snd /-- The `none` value in `roption` has a `false` domain and an empty function. -/ def none : roption α := ⟨false, false.rec _⟩ @[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst /-- The `some a` value in `roption` has a `true` domain and the function returns `a`. -/ def some (a : α) : roption α := ⟨true, λ_, a⟩ theorem mem_unique : relator.left_unique ((∈) : α → roption α → Prop) | _ ⟨p, f⟩ _ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl theorem get_eq_of_mem {o : roption α} {a} (h : a ∈ o) (h') : get o h' = a := mem_unique ⟨_, rfl⟩ h @[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩ @[simp] theorem mem_some_iff {a b} : b ∈ (some a : roption α) ↔ b = a := ⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩ theorem eq_some_iff {a : α} {o : roption α} : o = some a ↔ a ∈ o := ⟨λ e, e.symm ▸ mem_some _, λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩ theorem eq_none_iff {o : roption α} : o = none ↔ ∀ a, a ∉ o := ⟨λ e, e.symm ▸ not_mem_none, λ h, ext (by simpa [not_mem_none])⟩ theorem eq_none_iff' {o : roption α} : o = none ↔ ¬ o.dom := ⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩ @[simp] lemma some_inj {a b : α} : roption.some a = some b ↔ a = b := function.injective.eq_iff (λ a b h, congr_fun (eq_of_heq (roption.mk.inj h).2) trivial) @[simp] lemma some_get {a : roption α} (ha : a.dom) : roption.some (roption.get a ha) = a := eq.symm (eq_some_iff.2 ⟨ha, rfl⟩) lemma get_eq_iff_eq_some {a : roption α} {ha : a.dom} {b : α} : a.get ha = b ↔ a = some b := ⟨λ h, by simp [h.symm], λ h, by simp [h]⟩ instance none_decidable : decidable (@none α).dom := decidable.false instance some_decidable (a : α) : decidable (some a).dom := decidable.true def get_or_else (a : roption α) [decidable a.dom] (d : α) := if ha : a.dom then a.get ha else d @[simp] lemma get_or_else_none (d : α) : get_or_else none d = d := dif_neg id @[simp] lemma get_or_else_some (a : α) (d : α) : get_or_else (some a) d = a := dif_pos trivial @[simp] theorem mem_to_option {o : roption α} [decidable o.dom] {a : α} : a ∈ to_option o ↔ a ∈ o := begin unfold to_option, by_cases h : o.dom; simp [h], { exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ }, { exact mt Exists.fst h } end /-- Convert an `option α` into an `roption α` -/ def of_option : option α → roption α | option.none := none | (option.some a) := some a @[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o | option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩ | (option.some b) := ⟨λ h, congr_arg option.some h.snd, λ h, ⟨trivial, option.some.inj h⟩⟩ @[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some | option.none := by simp [of_option, none] | (option.some a) := by simp [of_option] theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ := roption.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl] instance : has_coe (option α) (roption α) := ⟨of_option⟩ @[simp] theorem mem_coe {a : α} {o : option α} : a ∈ (o : roption α) ↔ a ∈ o := mem_of_option @[simp] theorem coe_none : (@option.none α : roption α) = none := rfl @[simp] theorem coe_some (a : α) : (option.some a : roption α) = some a := rfl @[elab_as_eliminator] protected lemma roption.induction_on {P : roption α → Prop} (a : roption α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a := (classical.em a.dom).elim (λ h, roption.some_get h ▸ hsome _) (λ h, (eq_none_iff'.2 h).symm ▸ hnone) instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom | option.none := roption.none_decidable | (option.some a) := roption.some_decidable a @[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o := by cases o; refl @[simp] theorem of_to_option (o : roption α) [decidable o.dom] : of_option (to_option o) = o := ext $ λ a, mem_of_option.trans mem_to_option noncomputable def equiv_option : roption α ≃ option α := by haveI := classical.dec; exact ⟨λ o, to_option o, of_option, λ o, of_to_option o, λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩ /-- `assert p f` is a bind-like operation which appends an additional condition `p` to the domain and uses `f` to produce the value. -/ def assert (p : Prop) (f : p → roption α) : roption α := ⟨∃h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩ /-- The bind operation has value `g (f.get)`, and is defined when all the parts are defined. -/ protected def bind (f : roption α) (g : α → roption β) : roption β := assert (dom f) (λb, g (f.get b)) /-- The map operation for `roption` just maps the value and maintains the same domain. -/ def map (f : α → β) (o : roption α) : roption β := ⟨o.dom, f ∘ o.get⟩ theorem mem_map (f : α → β) {o : roption α} : ∀ {a}, a ∈ o → f a ∈ map f o | _ ⟨h, rfl⟩ := ⟨_, rfl⟩ @[simp] theorem mem_map_iff (f : α → β) {o : roption α} {b} : b ∈ map f o ↔ ∃ a ∈ o, f a = b := ⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end, λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩ @[simp] theorem map_none (f : α → β) : map f none = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) := eq_some_iff.2 $ mem_map f $ mem_some _ theorem mem_assert {p : Prop} {f : p → roption α} : ∀ {a} (h : p), a ∈ f h → a ∈ assert p f | _ _ ⟨h, rfl⟩ := ⟨⟨_, _⟩, rfl⟩ @[simp] theorem mem_assert_iff {p : Prop} {f : p → roption α} {a} : a ∈ assert p f ↔ ∃ h : p, a ∈ f h := ⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end, λ ⟨a, h⟩, mem_assert _ h⟩ theorem mem_bind {f : roption α} {g : α → roption β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g | _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨_, _⟩, rfl⟩ @[simp] theorem mem_bind_iff {f : roption α} {g : α → roption β} {b} : b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a := ⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end, λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩ @[simp] theorem bind_none (f : α → roption β) : none.bind f = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem bind_some (a : α) (f : α → roption β) : (some a).bind f = f a := ext $ by simp theorem bind_some_eq_map (f : α → β) (x : roption α) : x.bind (some ∘ f) = map f x := ext $ by simp [eq_comm] theorem bind_assoc {γ} (f : roption α) (g : α → roption β) (k : β → roption γ) : (f.bind g).bind k = f.bind (λ x, (g x).bind k) := ext $ λ a, by simp; exact ⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩, λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩ @[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → roption γ) : (map f x).bind g = x.bind (λ y, g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp @[simp] theorem map_bind {γ} (f : α → roption β) (x : roption α) (g : β → γ) : map g (x.bind f) = x.bind (λ y, map g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map] theorem map_map (g : β → γ) (f : α → β) (o : roption α) : map g (map f o) = map (g ∘ f) o := by rw [← bind_some_eq_map, bind_map, bind_some_eq_map] instance : monad roption := { pure := @some, map := @map, bind := @roption.bind } instance : is_lawful_monad roption := { bind_pure_comp_eq_map := @bind_some_eq_map, id_map := λ β f, by cases f; refl, pure_bind := @bind_some, bind_assoc := @bind_assoc } theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o := by rw [show f = id, from funext H]; exact id_map o @[simp] theorem bind_some_right (x : roption α) : x.bind some = x := by rw [bind_some_eq_map]; simp [map_id'] @[simp] theorem ret_eq_some (a : α) : return a = some a := rfl @[simp] theorem map_eq_map {α β} (f : α → β) (o : roption α) : f <$> o = map f o := rfl @[simp] theorem bind_eq_bind {α β} (f : roption α) (g : α → roption β) : f >>= g = f.bind g := rfl instance : monad_fail roption := { fail := λ_ _, none, ..roption.monad } /- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when `p` implies `o` is defined. -/ def restrict (p : Prop) : ∀ (o : roption α), (p → o.dom) → roption α | ⟨d, f⟩ H := ⟨p, λh, f (H h)⟩ @[simp] theorem mem_restrict (p : Prop) (o : roption α) (h : p → o.dom) (a : α) : a ∈ restrict p o h ↔ p ∧ a ∈ o := begin cases o, dsimp [restrict, mem_eq], split, { rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ }, rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩ end /-- `unwrap o` gets the value at `o`, ignoring the condition. (This function is unsound.) -/ meta def unwrap (o : roption α) : α := o.get undefined theorem assert_defined {p : Prop} {f : p → roption α} : ∀ (h : p), (f h).dom → (assert p f).dom := exists.intro theorem bind_defined {f : roption α} {g : α → roption β} : ∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined @[simp] theorem bind_dom {f : roption α} {g : α → roption β} : (f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl end roption /-- `pfun α β`, or `α →. β`, is the type of partial functions from `α` to `β`. It is defined as `α → roption β`. -/ def pfun (α : Type*) (β : Type*) := α → roption β infixr ` →. `:25 := pfun namespace pfun variables {α : Type*} {β : Type*} {γ : Type*} /-- The domain of a partial function -/ def dom (f : α →. β) : set α := λ a, (f a).dom theorem mem_dom (f : α →. β) (x : α) : x ∈ dom f ↔ ∃ y, y ∈ f x := by simp [dom, set.mem_def, roption.dom_iff_mem] theorem dom_eq (f : α →. β) : dom f = {x | ∃ y, y ∈ f x} := set.ext (mem_dom f) /-- Evaluate a partial function -/ def fn (f : α →. β) (x) (h : dom f x) : β := (f x).get h /-- Evaluate a partial function to return an `option` -/ def eval_opt (f : α →. β) [D : decidable_pred (dom f)] (x : α) : option β := @roption.to_option _ _ (D x) /-- Partial function extensionality -/ def ext' {f g : α →. β} (H1 : ∀ a, a ∈ dom f ↔ a ∈ dom g) (H2 : ∀ a p q, f.fn a p = g.fn a q) : f = g := funext $ λ a, roption.ext' (H1 a) (H2 a) def ext {f g : α →. β} (H : ∀ a b, b ∈ f a ↔ b ∈ g a) : f = g := funext $ λ a, roption.ext (H a) /-- Turn a partial function into a function out of a subtype -/ def as_subtype (f : α →. β) (s : {x // f.dom x}) : β := f.fn s.1 s.2 def equiv_subtype : (α →. β) ≃ (Σ p : α → Prop, subtype p → β) := ⟨λ f, ⟨f.dom, as_subtype f⟩, λ ⟨p, f⟩ x, ⟨p x, λ h, f ⟨x, h⟩⟩, λ f, funext $ λ a, roption.eta _, λ ⟨p, f⟩, by dsimp; congr; funext a; cases a; refl⟩ theorem as_subtype_eq_of_mem {f : α →. β} {x : α} {y : β} (fxy : y ∈ f x) (domx : x ∈ f.dom) : f.as_subtype ⟨x, domx⟩ = y := roption.mem_unique (roption.get_mem _) fxy /-- Turn a total function into a partial function -/ protected def lift (f : α → β) : α →. β := λ a, roption.some (f a) instance : has_coe (α → β) (α →. β) := ⟨pfun.lift⟩ @[simp] theorem lift_eq_coe (f : α → β) : pfun.lift f = f := rfl @[simp] theorem coe_val (f : α → β) (a : α) : (f : α →. β) a = roption.some (f a) := rfl /-- The graph of a partial function is the set of pairs `(x, f x)` where `x` is in the domain of `f`. -/ def graph (f : α →. β) : set (α × β) := {p | p.2 ∈ f p.1} def graph' (f : α →. β) : rel α β := λ x y, y ∈ f x /-- The range of a partial function is the set of values `f x` where `x` is in the domain of `f`. -/ def ran (f : α →. β) : set β := {b | ∃a, b ∈ f a} /-- Restrict a partial function to a smaller domain. -/ def restrict (f : α →. β) {p : set α} (H : p ⊆ f.dom) : α →. β := λ x, roption.restrict (p x) (f x) (@H x) @[simp] theorem mem_restrict {f : α →. β} {s : set α} (h : s ⊆ f.dom) (a : α) (b : β) : b ∈ restrict f h a ↔ a ∈ s ∧ b ∈ f a := by { simp [restrict], reflexivity } def res (f : α → β) (s : set α) : α →. β := restrict (pfun.lift f) (set.subset_univ s) theorem mem_res (f : α → β) (s : set α) (a : α) (b : β) : b ∈ res f s a ↔ (a ∈ s ∧ f a = b) := by { simp [res], split; {intro h, simp [h]} } theorem res_univ (f : α → β) : pfun.res f set.univ = f := rfl theorem dom_iff_graph (f : α →. β) (x : α) : x ∈ f.dom ↔ ∃y, (x, y) ∈ f.graph := roption.dom_iff_mem theorem lift_graph {f : α → β} {a b} : (a, b) ∈ (f : α →. β).graph ↔ f a = b := show (∃ (h : true), f a = b) ↔ f a = b, by simp /-- The monad `pure` function, the total constant `x` function -/ protected def pure (x : β) : α →. β := λ_, roption.some x /-- The monad `bind` function, pointwise `roption.bind` -/ def bind (f : α →. β) (g : β → α →. γ) : α →. γ := λa, roption.bind (f a) (λb, g b a) /-- The monad `map` function, pointwise `roption.map` -/ def map (f : β → γ) (g : α →. β) : α →. γ := λa, roption.map f (g a) instance : monad (pfun α) := { pure := @pfun.pure _, bind := @pfun.bind _, map := @pfun.map _ } instance : is_lawful_monad (pfun α) := { bind_pure_comp_eq_map := λ β γ f x, funext $ λ a, roption.bind_some_eq_map _ _, id_map := λ β f, by funext a; dsimp [functor.map, pfun.map]; cases f a; refl, pure_bind := λ β γ x f, funext $ λ a, roption.bind_some.{u_1 u_2} _ (f x), bind_assoc := λ β γ δ f g k, funext $ λ a, roption.bind_assoc (f a) (λ b, g b a) (λ b, k b a) } theorem pure_defined (p : set α) (x : β) : p ⊆ (@pfun.pure α _ x).dom := set.subset_univ p theorem bind_defined {α β γ} (p : set α) {f : α →. β} {g : β → α →. γ} (H1 : p ⊆ f.dom) (H2 : ∀x, p ⊆ (g x).dom) : p ⊆ (f >>= g).dom := λa ha, (⟨H1 ha, H2 _ ha⟩ : (f >>= g).dom a) def fix (f : α →. β ⊕ α) : α →. β := λ a, roption.assert (acc (λ x y, sum.inr x ∈ f y) a) $ λ h, @well_founded.fix_F _ (λ x y, sum.inr x ∈ f y) _ (λ a IH, roption.assert (f a).dom $ λ hf, by cases e : (f a).get hf with b a'; [exact roption.some b, exact IH _ ⟨hf, e⟩]) a h theorem dom_of_mem_fix {f : α →. β ⊕ α} {a : α} {b : β} (h : b ∈ fix f a) : (f a).dom := let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in by rw well_founded.fix_F_eq at h₂; exact h₂.fst.fst theorem mem_fix_iff {f : α →. β ⊕ α} {a : α} {b : β} : b ∈ fix f a ↔ sum.inl b ∈ f a ∨ ∃ a', sum.inr a' ∈ f a ∧ b ∈ fix f a' := ⟨λ h, let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in begin rw well_founded.fix_F_eq at h₂, simp at h₂, cases h₂ with h₂ h₃, cases e : (f a).get h₂ with b' a'; simp [e] at h₃, { subst b', refine or.inl ⟨h₂, e⟩ }, { exact or.inr ⟨a', ⟨_, e⟩, roption.mem_assert _ h₃⟩ } end, λ h, begin simp [fix], rcases h with ⟨h₁, h₂⟩ | ⟨a', h, h₃⟩, { refine ⟨⟨_, λ y h', _⟩, _⟩, { injection roption.mem_unique ⟨h₁, h₂⟩ h' }, { rw well_founded.fix_F_eq, simp [h₁, h₂] } }, { simp [fix] at h₃, cases h₃ with h₃ h₄, refine ⟨⟨_, λ y h', _⟩, _⟩, { injection roption.mem_unique h h' with e, exact e ▸ h₃ }, { cases h with h₁ h₂, rw well_founded.fix_F_eq, simp [h₁, h₂, h₄] } } end⟩ @[elab_as_eliminator] theorem fix_induction {f : α →. β ⊕ α} {b : β} {C : α → Sort*} {a : α} (h : b ∈ fix f a) (H : ∀ a, b ∈ fix f a → (∀ a', b ∈ fix f a' → sum.inr a' ∈ f a → C a') → C a) : C a := begin replace h := roption.mem_assert_iff.1 h, have := h.snd, revert this, induction h.fst with a ha IH, intro h₂, refine H a (roption.mem_assert_iff.2 ⟨⟨_, ha⟩, h₂⟩) (λ a' ha' fa', _), have := (roption.mem_assert_iff.1 ha').snd, exact IH _ fa' ⟨ha _ fa', this⟩ this end end pfun namespace pfun variables {α : Type*} {β : Type*} (f : α →. β) def image (s : set α) : set β := rel.image f.graph' s lemma image_def (s : set α) : image f s = {y | ∃ x ∈ s, y ∈ f x} := rfl lemma mem_image (y : β) (s : set α) : y ∈ image f s ↔ ∃ x ∈ s, y ∈ f x := iff.refl _ lemma image_mono {s t : set α} (h : s ⊆ t) : f.image s ⊆ f.image t := rel.image_mono _ h lemma image_inter (s t : set α) : f.image (s ∩ t) ⊆ f.image s ∩ f.image t := rel.image_inter _ s t lemma image_union (s t : set α) : f.image (s ∪ t) = f.image s ∪ f.image t := rel.image_union _ s t def preimage (s : set β) : set α := rel.preimage (λ x y, y ∈ f x) s lemma preimage_def (s : set β) : preimage f s = {x | ∃ y ∈ s, y ∈ f x} := rfl def mem_preimage (s : set β) (x : α) : x ∈ preimage f s ↔ ∃ y ∈ s, y ∈ f x := iff.refl _ lemma preimage_subset_dom (s : set β) : f.preimage s ⊆ f.dom := assume x ⟨y, ys, fxy⟩, roption.dom_iff_mem.mpr ⟨y, fxy⟩ lemma preimage_mono {s t : set β} (h : s ⊆ t) : f.preimage s ⊆ f.preimage t := rel.preimage_mono _ h lemma preimage_inter (s t : set β) : f.preimage (s ∩ t) ⊆ f.preimage s ∩ f.preimage t := rel.preimage_inter _ s t lemma preimage_union (s t : set β) : f.preimage (s ∪ t) = f.preimage s ∪ f.preimage t := rel.preimage_union _ s t lemma preimage_univ : f.preimage set.univ = f.dom := by ext; simp [mem_preimage, mem_dom] def core (s : set β) : set α := rel.core f.graph' s lemma core_def (s : set β) : core f s = {x | ∀ y, y ∈ f x → y ∈ s} := rfl lemma mem_core (x : α) (s : set β) : x ∈ core f s ↔ (∀ y, y ∈ f x → y ∈ s) := iff.rfl lemma compl_dom_subset_core (s : set β) : -f.dom ⊆ f.core s := assume x hx y fxy, absurd ((mem_dom f x).mpr ⟨y, fxy⟩) hx lemma core_mono {s t : set β} (h : s ⊆ t) : f.core s ⊆ f.core t := rel.core_mono _ h lemma core_inter (s t : set β) : f.core (s ∩ t) = f.core s ∩ f.core t := rel.core_inter _ s t lemma mem_core_res (f : α → β) (s : set α) (t : set β) (x : α) : x ∈ core (res f s) t ↔ (x ∈ s → f x ∈ t) := begin simp [mem_core, mem_res], split, { intros h h', apply h _ h', reflexivity }, intros h y xs fxeq, rw ←fxeq, exact h xs end section local attribute [instance] classical.prop_decidable lemma core_res (f : α → β) (s : set α) (t : set β) : core (res f s) t = -s ∪ f ⁻¹' t := by { ext, rw mem_core_res, by_cases h : x ∈ s; simp [h] } end lemma core_restrict (f : α → β) (s : set β) : core (f : α →. β) s = set.preimage f s := by ext x; simp [core_def] lemma preimage_subset_core (f : α →. β) (s : set β) : f.preimage s ⊆ f.core s := assume x ⟨y, ys, fxy⟩ y' fxy', have y = y', from roption.mem_unique fxy fxy', this ▸ ys lemma preimage_eq (f : α →. β) (s : set β) : f.preimage s = f.core s ∩ f.dom := set.eq_of_subset_of_subset (set.subset_inter (preimage_subset_core f s) (preimage_subset_dom f s)) (assume x ⟨xcore, xdom⟩, let y := (f x).get xdom in have ys : y ∈ s, from xcore _ (roption.get_mem _), show x ∈ preimage f s, from ⟨(f x).get xdom, ys, roption.get_mem _⟩) lemma core_eq (f : α →. β) (s : set β) : f.core s = f.preimage s ∪ -f.dom := by rw [preimage_eq, set.union_distrib_right, set.union_comm (dom f), set.compl_union_self, set.inter_univ, set.union_eq_self_of_subset_right (compl_dom_subset_core f s)] lemma preimage_as_subtype (f : α →. β) (s : set β) : f.as_subtype ⁻¹' s = subtype.val ⁻¹' pfun.preimage f s := begin ext x, simp only [set.mem_preimage, set.mem_set_of_eq, pfun.as_subtype, pfun.mem_preimage], show pfun.fn f (x.val) _ ∈ s ↔ ∃ y ∈ s, y ∈ f (x.val), exact iff.intro (assume h, ⟨_, h, roption.get_mem _⟩) (assume ⟨y, ys, fxy⟩, have f.fn x.val x.property ∈ f x.val := roption.get_mem _, roption.mem_unique fxy this ▸ ys) end end pfun
1be8b680dec47bdce07a9d24e0c7aa6294d2149e
2272e503179a58556187901b8698b789fad7e0c4
/src/morphism.lean
eabc1849592579a56da3440c0de1e58f9c668f02
[]
no_license
kckennylau/category-theory
f15e582be862379453a5341d83b8cd5ebc686729
b24962838c7370b5257e38b7648040aec95922bb
refs/heads/master
1,583,605,043,449
1,525,154,882,000
1,525,154,882,000
127,633,452
0
0
null
null
null
null
UTF-8
Lean
false
false
1,481
lean
import .basic universes u v namespace category variables {α : Type u} (C : category.{u v} α) variables {x y z : α} (f : C.Mor x y) @[reducible] def monomorphism : Prop := ∀ {z : α} (g h : C.Mor z x) (H : C.Comp _ _ _ f g = C.Comp _ _ _ f h), g = h @[reducible] def epimorphism : Prop := ∀ {z : α} (g h : C.Mor y z) (H : C.Comp _ _ _ g f = C.Comp _ _ _ h f), g = h @[reducible] def split_monomorphism : Type v := { g : C.Mor y x // C.Comp _ _ _ g f = C.Id x } @[reducible] def split_epimorphism : Type v := { g : C.Mor y x // C.Comp _ _ _ f g = C.Id y } variables x y structure isomorphism : Type v := (to_mor : C.Mor x y) (inv_mor : C.Mor y x) (split_monomorphism : C.Comp _ _ _ inv_mor to_mor = C.Id x) (split_epimorphism : C.Comp _ _ _ to_mor inv_mor = C.Id y) @[refl] def isomorphism.refl : isomorphism C x x := ⟨C.Id x, C.Id x, C.Hid_left _ _ _, C.Hid_right _ _ _⟩ @[symm] def isomorphism.symm (e : isomorphism C x y) : isomorphism C y x := ⟨e.inv_mor, e.to_mor, e.split_epimorphism, e.split_monomorphism⟩ @[trans] def isomorphism.trans (e₁ : isomorphism C x y) (e₂ : isomorphism C y z) : isomorphism C x z := ⟨C.Comp _ _ _ e₂.to_mor e₁.to_mor, C.Comp _ _ _ e₁.inv_mor e₂.inv_mor, by rw [C.Hassoc, ← C.Hassoc x y, e₂.split_monomorphism, C.Hid_left, e₁.split_monomorphism], by rw [C.Hassoc, ← C.Hassoc z y, e₁.split_epimorphism, C.Hid_left, e₂.split_epimorphism]⟩ end category
a5bae4b61a5eefcfad4151dfaf028d62ab0401aa
a726f88081e44db9edfd14d32cfe9c4393ee56a4
/world_experiments/world9/level2.lean
b43f45a5043cd36e8e1fedc26df2a5787593bfef
[]
no_license
b-mehta/natural_number_game
80451bf10277adc89a55dbe8581692c36d822462
9faf799d0ab48ecbc89b3d70babb65ba64beee3b
refs/heads/master
1,598,525,389,186
1,573,516,674,000
1,573,516,674,000
217,339,684
0
0
null
1,571,933,100,000
1,571,933,099,000
null
UTF-8
Lean
false
false
2,004
lean
import game.world5.level1 -- hide namespace mynat -- hide /- # World 5 : Inequality world ## Level 2 : `le_succ` In this level we will find ourselves with a *hypothesis* of the form `h : ∃ c, P` where `P` is some proposition (which probably depends on `c`). To extract `c` from `h` you can use the `cases` tactic. If `h : ∃ c, P` is as above, then `cases h with c hc` will create your term `c` as well as creating a proof `hc` of `P`, i.e., `hc` is the proof that `c` satisfies `P`. For example, if we have ``` h : ∃ c : mynat, c + c = 12 ``` then `cases h with c hc` will turn it into ``` c : mynat, hc : c + c = 12 ``` Of course if you don't want it to be called `c`, you can do `cases h with n hn` and if you want `n + n = 12` to be called H12 you can do `cases h with n H12`. -/ /- Tactic : cases If you have a hypothesis `h : ∃ n, P(n)` where `P(n)` is a proposition depending on `n`, then `cases h with d hd` will produce a new term `d` and also a proof `hd` of `P(d)`. ## Example If the local context contains ``` h : ∃ c : mynat, c + c = 12 ``` then `cases h with c hc` will turn it into ``` c : mynat, hc : c + c = 12 ``` -/ /- I also need to tell you that `rw` works on hypotheses as well as on the goal. In the level below, we have an inequality in the hypothesis as well as in the goal. So perhaps a natural way to start this level is ``` rw le_def at h, rw le_def, ``` and now you can use `cases` on `h` and `use` for the goal. Pro tip: `rw le_def at h ⊢` does both rewrites at once. You can get the goal sign by typing `\|-`. -/ /- Lemma For all naturals $a$, $b$, if $a\leq b$ then $a\leq \operatorname{succ}(b)$. -/ theorem le_succ {a b : mynat} (h : a ≤ b) : a ≤ (succ b) := begin [less_leaky] rw le_def at h ⊢, cases h with c hc, use (succ c), rw hc, rw add_succ, refl, end /- Did you use `succ c` or `c + 1` or `1 + c`? Those numbers are all equal, right? So it doesn't matter which one you use, right? -/ end mynat -- hide
171872854a768e9093615fd9261f283ed184738f
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/analysis/special_functions/integrals.lean
cca70a2cd21fe95c4258e1b8cc6190598aebd497
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
14,160
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import measure_theory.interval_integral /-! # Integration of specific interval integrals This file contains proofs of the integrals of various specific functions. This includes: * Integrals of simple functions, such as `id`, `pow`, `exp`, `inv` * Integrals of some trigonometric functions, such as `sin`, `cos`, `1 / (1 + x^2)` * The integral of `cos x ^ 2 - sin x ^ 2` * Reduction formulae for the integrals of `sin x ^ n` and `cos x ^ n` for `n ≥ 2` * The computation of `∫ x in 0..π, sin x ^ n` as a product for even and odd `n` (used in proving the Wallis product for pi) With these lemmas, many simple integrals can be computed by `simp` or `norm_num`. See `test/integration.lean` for specific examples. This file also contains some facts about the interval integrability of specific functions. This file is still being developed. ## Tags integrate, integration, integrable, integrability -/ open real nat set finset open_locale real big_operators variables {a b : ℝ} (n : ℕ) namespace interval_integral open measure_theory variables {f : ℝ → ℝ} {μ ν : measure ℝ} [locally_finite_measure μ] (c d : ℝ) /-! ### Interval integrability -/ @[simp] lemma interval_integrable_pow : interval_integrable (λ x, x^n) μ a b := (continuous_pow n).interval_integrable a b @[simp] lemma interval_integrable_id : interval_integrable (λ x, x) μ a b := continuous_id.interval_integrable a b @[simp] lemma interval_integrable_const : interval_integrable (λ x, c) μ a b := continuous_const.interval_integrable a b @[simp] lemma interval_integrable.const_mul (h : interval_integrable f ν a b) : interval_integrable (λ x, c * f x) ν a b := by convert h.smul c @[simp] lemma interval_integrable.mul_const (h : interval_integrable f ν a b) : interval_integrable (λ x, f x * c) ν a b := by simp only [mul_comm, interval_integrable.const_mul c h] @[simp] lemma interval_integrable.div (h : interval_integrable f ν a b) : interval_integrable (λ x, f x / c) ν a b := interval_integrable.mul_const c⁻¹ h lemma interval_integrable_one_div (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0) (hf : continuous_on f (interval a b)) : interval_integrable (λ x, 1 / f x) μ a b := (continuous_on_const.div hf h).interval_integrable @[simp] lemma interval_integrable_inv (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0) (hf : continuous_on f (interval a b)) : interval_integrable (λ x, (f x)⁻¹) μ a b := by simpa only [one_div] using interval_integrable_one_div h hf @[simp] lemma interval_integrable_exp : interval_integrable exp μ a b := continuous_exp.interval_integrable a b @[simp] lemma interval_integrable.log (hf : continuous_on f (interval a b)) (h : ∀ x : ℝ, x ∈ interval a b → f x ≠ 0) : interval_integrable (λ x, log (f x)) μ a b := (continuous_on.log hf h).interval_integrable @[simp] lemma interval_integrable_log (h : (0:ℝ) ∉ interval a b) : interval_integrable log μ a b := interval_integrable.log continuous_on_id $ λ x hx, ne_of_mem_of_not_mem hx h @[simp] lemma interval_integrable_sin : interval_integrable sin μ a b := continuous_sin.interval_integrable a b @[simp] lemma interval_integrable_cos : interval_integrable cos μ a b := continuous_cos.interval_integrable a b lemma interval_integrable_one_div_one_add_sq : interval_integrable (λ x : ℝ, 1 / (1 + x^2)) μ a b := begin refine (continuous_const.div _ (λ x, _)).interval_integrable a b, { continuity }, { nlinarith }, end @[simp] lemma interval_integrable_inv_one_add_sq : interval_integrable (λ x : ℝ, (1 + x^2)⁻¹) μ a b := by simpa only [one_div] using interval_integrable_one_div_one_add_sq /-! ### Integral of a function scaled by a constant -/ @[simp] lemma integral_const_mul : ∫ x in a..b, c * f x = c * ∫ x in a..b, f x := integral_smul c @[simp] lemma integral_mul_const : ∫ x in a..b, f x * c = (∫ x in a..b, f x) * c := by simp only [mul_comm, integral_const_mul] @[simp] lemma integral_div : ∫ x in a..b, f x / c = (∫ x in a..b, f x) / c := integral_mul_const c⁻¹ /-! ### Integrals of the form `c * ∫ x in a..b, f (c * x + d)` -/ @[simp] lemma mul_integral_comp_mul_right : c * ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := smul_integral_comp_mul_right f c @[simp] lemma mul_integral_comp_mul_left : c * ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := smul_integral_comp_mul_left f c @[simp] lemma inv_mul_integral_comp_div : c⁻¹ * ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := inv_smul_integral_comp_div f c @[simp] lemma mul_integral_comp_mul_add : c * ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := smul_integral_comp_mul_add f c d @[simp] lemma mul_integral_comp_add_mul : c * ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := smul_integral_comp_add_mul f c d @[simp] lemma inv_mul_integral_comp_div_add : c⁻¹ * ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := inv_smul_integral_comp_div_add f c d @[simp] lemma inv_mul_integral_comp_add_div : c⁻¹ * ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := inv_smul_integral_comp_add_div f c d @[simp] lemma mul_integral_comp_mul_sub : c * ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := smul_integral_comp_mul_sub f c d @[simp] lemma mul_integral_comp_sub_mul : c * ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := smul_integral_comp_sub_mul f c d @[simp] lemma inv_mul_integral_comp_div_sub : c⁻¹ * ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := inv_smul_integral_comp_div_sub f c d @[simp] lemma inv_mul_integral_comp_sub_div : c⁻¹ * ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := inv_smul_integral_comp_sub_div f c d end interval_integral open interval_integral /-! ### Integrals of simple functions -/ @[simp] lemma integral_pow : ∫ x in a..b, x ^ n = (b ^ (n + 1) - a ^ (n + 1)) / (n + 1) := begin have hderiv : deriv (λ x : ℝ, x ^ (n + 1) / (n + 1)) = λ x, x ^ n, { ext, have hne : (n + 1 : ℝ) ≠ 0 := by exact_mod_cast succ_ne_zero n, simp [mul_div_assoc, mul_div_cancel' _ hne] }, rw integral_deriv_eq_sub' _ hderiv; norm_num [div_sub_div_same, continuous_on_pow], end @[simp] lemma integral_id : ∫ x in a..b, x = (b ^ 2 - a ^ 2) / 2 := by simpa using integral_pow 1 @[simp] lemma integral_one : ∫ x in a..b, (1 : ℝ) = b - a := by simp only [mul_one, smul_eq_mul, integral_const] @[simp] lemma integral_exp : ∫ x in a..b, exp x = exp b - exp a := by rw integral_deriv_eq_sub'; norm_num [continuous_on_exp] @[simp] lemma integral_inv (h : (0:ℝ) ∉ interval a b) : ∫ x in a..b, x⁻¹ = log (b / a) := begin have h' := λ x hx, ne_of_mem_of_not_mem hx h, rw [integral_deriv_eq_sub' _ deriv_log' (λ x hx, differentiable_at_log (h' x hx)) (continuous_on_inv'.mono $ subset_compl_singleton_iff.mpr h), log_div (h' b right_mem_interval) (h' a left_mem_interval)], end @[simp] lemma integral_inv_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x in a..b, x⁻¹ = log (b / a) := integral_inv $ not_mem_interval_of_lt ha hb @[simp] lemma integral_inv_of_neg (ha : a < 0) (hb : b < 0) : ∫ x in a..b, x⁻¹ = log (b / a) := integral_inv $ not_mem_interval_of_gt ha hb lemma integral_one_div (h : (0:ℝ) ∉ interval a b) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv h] lemma integral_one_div_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv_of_pos ha hb] lemma integral_one_div_of_neg (ha : a < 0) (hb : b < 0) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv_of_neg ha hb] @[simp] lemma integral_sin : ∫ x in a..b, sin x = cos a - cos b := by rw integral_deriv_eq_sub' (λ x, -cos x); norm_num [continuous_on_sin] @[simp] lemma integral_cos : ∫ x in a..b, cos x = sin b - sin a := by rw integral_deriv_eq_sub'; norm_num [continuous_on_cos] lemma integral_cos_sq_sub_sin_sq : ∫ x in a..b, cos x ^ 2 - sin x ^ 2 = sin b * cos b - sin a * cos a := by simpa only [sq, sub_eq_add_neg, neg_mul_eq_mul_neg] using integral_deriv_mul_eq_sub (λ x hx, has_deriv_at_sin x) (λ x hx, has_deriv_at_cos x) continuous_on_cos continuous_on_sin.neg @[simp] lemma integral_inv_one_add_sq : ∫ x : ℝ in a..b, (1 + x^2)⁻¹ = arctan b - arctan a := begin simp only [← one_div], refine integral_deriv_eq_sub' _ _ _ (continuous_const.div _ (λ x, _)).continuous_on, { norm_num }, { norm_num }, { continuity }, { nlinarith }, end lemma integral_one_div_one_add_sq : ∫ x : ℝ in a..b, 1 / (1 + x^2) = arctan b - arctan a := by simp only [one_div, integral_inv_one_add_sq] /-! ### Integral of `sin x ^ n` -/ lemma integral_sin_pow_aux : ∫ x in a..b, sin x ^ (n + 2) = sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) := begin let C := sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b, have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring, have hu : ∀ x ∈ _, has_deriv_at (λ y, sin y ^ (n + 1)) ((n + 1) * cos x * sin x ^ n) x := λ x hx, by simpa [mul_right_comm] using (has_deriv_at_sin x).pow, have hv : ∀ x ∈ interval a b, has_deriv_at (-cos) (sin x) x := λ x hx, by simpa only [neg_neg] using (has_deriv_at_cos x).neg, have H := integral_mul_deriv_eq_deriv_mul hu hv _ _, calc ∫ x in a..b, sin x ^ (n + 2) = ∫ x in a..b, sin x ^ (n + 1) * sin x : by simp only [pow_succ'] ... = C + (n + 1) * ∫ x in a..b, cos x ^ 2 * sin x ^ n : by simp [H, h, sq] ... = C + (n + 1) * ∫ x in a..b, sin x ^ n - sin x ^ (n + 2) : by simp [cos_sq', sub_mul, ← pow_add, add_comm] ... = C + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) : by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity, all_goals { apply continuous.continuous_on, continuity }, end /-- The reduction formula for the integral of `sin x ^ n` for any natural `n ≥ 2`. -/ lemma integral_sin_pow : ∫ x in a..b, sin x ^ (n + 2) = (sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b) / (n + 2) + (n + 1) / (n + 2) * ∫ x in a..b, sin x ^ n := begin have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ, field_simp, convert eq_sub_iff_add_eq.mp (integral_sin_pow_aux n), ring, end @[simp] lemma integral_sin_sq : ∫ x in a..b, sin x ^ 2 = (sin a * cos a - sin b * cos b + b - a) / 2 := by field_simp [integral_sin_pow, add_sub_assoc] theorem integral_sin_pow_odd : ∫ x in 0..π, sin x ^ (2 * n + 1) = 2 * ∏ i in range n, (2 * i + 2) / (2 * i + 3) := begin induction n with k ih, { norm_num }, rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow], norm_cast, simp [-cast_add] with field_simps, end theorem integral_sin_pow_even : ∫ x in 0..π, sin x ^ (2 * n) = π * ∏ i in range n, (2 * i + 1) / (2 * i + 2) := begin induction n with k ih, { simp }, rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow], norm_cast, simp [-cast_add] with field_simps, end lemma integral_sin_pow_pos : 0 < ∫ x in 0..π, sin x ^ n := begin rcases even_or_odd' n with ⟨k, (rfl | rfl)⟩; simp only [integral_sin_pow_even, integral_sin_pow_odd]; refine mul_pos (by norm_num [pi_pos]) (prod_pos (λ n hn, div_pos _ _)); norm_cast; linarith, end lemma integral_sin_pow_antimono : ∫ x in 0..π, sin x ^ (n + 1) ≤ ∫ x in 0..π, sin x ^ n := begin refine integral_mono_on _ _ pi_pos.le (λ x hx, _), { exact ((continuous_pow (n + 1)).comp continuous_sin).interval_integrable 0 π }, { exact ((continuous_pow n).comp continuous_sin).interval_integrable 0 π }, { refine pow_le_pow_of_le_one (sin_nonneg_of_mem_Icc _) (sin_le_one x) (nat.le_add_right n 1), rwa interval_of_le pi_pos.le at hx }, end /-! ### Integral of `cos x ^ n` -/ lemma integral_cos_pow_aux : ∫ x in a..b, cos x ^ (n + 2) = cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) := begin let C := cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a, have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring, have hu : ∀ x ∈ _, has_deriv_at (λ y, cos y ^ (n + 1)) (-(n + 1) * sin x * cos x ^ n) x := λ x hx, by simpa [mul_right_comm, -neg_add_rev] using (has_deriv_at_cos x).pow, have hv : ∀ x ∈ interval a b, has_deriv_at sin (cos x) x := λ x hx, has_deriv_at_sin x, have H := integral_mul_deriv_eq_deriv_mul hu hv _ _, calc ∫ x in a..b, cos x ^ (n + 2) = ∫ x in a..b, cos x ^ (n + 1) * cos x : by simp only [pow_succ'] ... = C + (n + 1) * ∫ x in a..b, sin x ^ 2 * cos x ^ n : by simp [H, h, sq, -neg_add_rev] ... = C + (n + 1) * ∫ x in a..b, cos x ^ n - cos x ^ (n + 2) : by simp [sin_sq, sub_mul, ← pow_add, add_comm] ... = C + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) : by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity, all_goals { apply continuous.continuous_on, continuity }, end /-- The reduction formula for the integral of `cos x ^ n` for any natural `n ≥ 2`. -/ lemma integral_cos_pow : ∫ x in a..b, cos x ^ (n + 2) = (cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a) / (n + 2) + (n + 1) / (n + 2) * ∫ x in a..b, cos x ^ n := begin have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ, field_simp, convert eq_sub_iff_add_eq.mp (integral_cos_pow_aux n), ring, end @[simp] lemma integral_cos_sq : ∫ x in a..b, cos x ^ 2 = (cos b * sin b - cos a * sin a + b - a) / 2 := by field_simp [integral_cos_pow, add_sub_assoc]
23fd3598ebb768fe5c716b820b90e4db31721f6e
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/limits/lattice.lean
891f61767791d25797d06bee4e24e84e56012245
[ "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
2,490
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_limits import order.complete_lattice universes u open category_theory namespace category_theory.limits variables {α : Type u} @[priority 100] -- see Note [lower instance priority] instance has_finite_limits_of_semilattice_inf_top [semilattice_inf_top α] : has_finite_limits α := { has_limits_of_shape := λ J 𝒥₁ 𝒥₂, by exactI { has_limit := λ F, { cone := { X := finset.univ.inf F.obj, π := { app := λ j, ⟨⟨finset.inf_le (fintype.complete _)⟩⟩ } }, is_limit := { lift := λ s, ⟨⟨finset.le_inf (λ j _, (s.π.app j).down.down)⟩⟩ } } } } @[priority 100] -- see Note [lower instance priority] instance has_finite_colimits_of_semilattice_sup_bot [semilattice_sup_bot α] : has_finite_colimits α := { has_colimits_of_shape := λ J 𝒥₁ 𝒥₂, by exactI { has_colimit := λ F, { cocone := { X := finset.univ.sup F.obj, ι := { app := λ i, ⟨⟨finset.le_sup (fintype.complete _)⟩⟩ } }, is_colimit := { desc := λ s, ⟨⟨finset.sup_le (λ j _, (s.ι.app j).down.down)⟩⟩ } } } } -- It would be nice to only use the `Inf` half of the complete lattice, but -- this seems not to have been described separately. @[priority 100] -- see Note [lower instance priority] instance has_limits_of_complete_lattice [complete_lattice α] : has_limits α := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, { cone := { X := Inf (set.range F.obj), π := { app := λ j, ⟨⟨complete_lattice.Inf_le _ _ (set.mem_range_self _)⟩⟩ } }, is_limit := { lift := λ s, ⟨⟨complete_lattice.le_Inf _ _ begin rintros _ ⟨j, rfl⟩, exact (s.π.app j).down.down, end⟩⟩ } } } } @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_complete_lattice [complete_lattice α] : has_colimits α := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, { cocone := { X := Sup (set.range F.obj), ι := { app := λ j, ⟨⟨complete_lattice.le_Sup _ _ (set.mem_range_self _)⟩⟩ } }, is_colimit := { desc := λ s, ⟨⟨complete_lattice.Sup_le _ _ begin rintros _ ⟨j, rfl⟩, exact (s.ι.app j).down.down, end⟩⟩ } } } } end category_theory.limits
f27a9a1d494851a2fbcf0862fa2b1880058e3ac3
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/group_theory/group_action/basic.lean
3ec60f4ea2825a4ea17627039405db009956ee14
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,306
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action.defs import group_theory.group_action.group import group_theory.coset /-! # Basic properties of group actions -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open_locale big_operators open function namespace mul_action variables (α) [monoid α] [mul_action α β] /-- The orbit of an element under an action. -/ def orbit (b : β) := set.range (λ x : α, x • b) variable {α} lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ := iff.rfl @[simp] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b := ⟨x, rfl⟩ @[simp] lemma mem_orbit_self (b : β) : b ∈ orbit α b := ⟨1, by simp [mul_action.one_smul]⟩ variable (α) /-- The stabilizer of an element under an action, i.e. what sends the element to itself. Note that this is a set: for the group stabilizer see `stabilizer`. -/ def stabilizer_carrier (b : β) : set α := {x : α | x • b = b} variable {α} @[simp] lemma mem_stabilizer_iff {b : β} {x : α} : x ∈ stabilizer_carrier α b ↔ x • b = b := iff.rfl variables (α) (β) /-- The set of elements fixed under the whole action. -/ def fixed_points : set β := {b : β | ∀ x : α, x • b = b} /-- `fixed_by g` is the subfield of elements fixed by `g`. -/ def fixed_by (g : α) : set β := { x | g • x = x } theorem fixed_eq_Inter_fixed_by : fixed_points α β = ⋂ g : α, fixed_by α β g := set.ext $ λ x, ⟨λ hx, set.mem_Inter.2 $ λ g, hx g, λ hx g, by exact (set.mem_Inter.1 hx g : _)⟩ variables {α} (β) @[simp] lemma mem_fixed_points {b : β} : b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl @[simp] lemma mem_fixed_by {g : α} {b : β} : b ∈ fixed_by α β g ↔ g • b = b := iff.rfl lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔ (∀ b', b' ∈ orbit α b → b' = b) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _))⟩ variables (α) {β} /-- The stabilizer of a point `b` as a submonoid of `α`. -/ def stabilizer.submonoid (b : β) : submonoid α := { carrier := stabilizer_carrier α b, one_mem' := one_smul _ b, mul_mem' := λ a a' (ha : a • b = b) (hb : a' • b = b), by rw [mem_stabilizer_iff, ←smul_smul, hb, ha] } end mul_action namespace mul_action variable (α) variables [group α] [mul_action α β] /-- The stabilizer of an element under an action, i.e. what sends the element to itself. A subgroup. -/ def stabilizer (b : β) : subgroup α := { inv_mem' := λ a (ha : a • b = b), show a⁻¹ • b = b, by rw [inv_smul_eq_iff, ha] ..stabilizer.submonoid α b } variables {α} {β} lemma orbit_eq_iff {a b : β} : orbit α a = orbit α b ↔ a ∈ orbit α b:= ⟨λ h, h ▸ mem_orbit_self _, λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x, show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩, λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹, show (y * x⁻¹) • a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_action.mul_smul, hx]}⟩⟩)⟩ variables (α) {β} /-- The stabilizer of a point `b` as a subgroup of `α`. -/ def stabilizer.subgroup (b : β) : subgroup α := { inv_mem' := λ x (hx : x • b = b), show x⁻¹ • b = b, by rw [← hx, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul, hx], ..stabilizer.submonoid α b } variables {β} @[simp] lemma mem_orbit_smul (g : α) (a : β) : a ∈ orbit α (g • a) := ⟨g⁻¹, by simp⟩ @[simp] lemma smul_mem_orbit_smul (g h : α) (a : β) : g • a ∈ orbit α (h • a) := ⟨g * h⁻¹, by simp [mul_smul]⟩ variables (α) (β) /-- The relation "in the same orbit". -/ def orbit_rel : setoid β := { r := λ a b, a ∈ orbit α b, iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm], λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ } variables {α β} open quotient_group mul_action /-- Action on left cosets. -/ def mul_left_cosets (H : subgroup α) (x : α) (y : quotient H) : quotient H := quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y)) (λ a b (hab : _ ∈ H), quotient_group.eq.2 (by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) instance quotient (H : subgroup α) : mul_action α (quotient H) := { smul := mul_left_cosets H, one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [subgroup.one_mem])), mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [mul_inv_rev, subgroup.one_mem, mul_assoc])) } instance mul_left_cosets_comp_subtype_val (H I : subgroup α) : mul_action I (quotient H) := mul_action.comp_hom (quotient H) (subgroup.subtype I) variables (α) {β} (x : β) /-- The canonical map from the quotient of the stabilizer to the set. -/ def of_quotient_stabilizer (g : quotient (mul_action.stabilizer α x)) : β := quotient.lift_on' g (•x) $ λ g1 g2 H, calc g1 • x = g1 • (g1⁻¹ * g2) • x : congr_arg _ H.symm ... = g2 • x : by rw [smul_smul, mul_inv_cancel_left] @[simp] theorem of_quotient_stabilizer_mk (g : α) : of_quotient_stabilizer α x (quotient_group.mk g) = g • x := rfl theorem of_quotient_stabilizer_mem_orbit (g) : of_quotient_stabilizer α x g ∈ orbit α x := quotient.induction_on' g $ λ g, ⟨g, rfl⟩ theorem of_quotient_stabilizer_smul (g : α) (g' : quotient (mul_action.stabilizer α x)) : of_quotient_stabilizer α x (g • g') = g • of_quotient_stabilizer α x g' := quotient.induction_on' g' $ λ _, mul_smul _ _ _ theorem injective_of_quotient_stabilizer : function.injective (of_quotient_stabilizer α x) := λ y₁ y₂, quotient.induction_on₂' y₁ y₂ $ λ g₁ g₂ (H : g₁ • x = g₂ • x), quotient.sound' $ show (g₁⁻¹ * g₂) • x = x, by rw [mul_smul, ← H, inv_smul_smul] /-- Orbit-stabilizer theorem. -/ noncomputable def orbit_equiv_quotient_stabilizer (b : β) : orbit α b ≃ quotient (stabilizer α b) := equiv.symm $ equiv.of_bijective (λ g, ⟨of_quotient_stabilizer α b g, of_quotient_stabilizer_mem_orbit α b g⟩) ⟨λ x y hxy, injective_of_quotient_stabilizer α b (by convert congr_arg subtype.val hxy), λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩ @[simp] theorem orbit_equiv_quotient_stabilizer_symm_apply (b : β) (a : α) : ((orbit_equiv_quotient_stabilizer α b).symm a : β) = a • b := rfl end mul_action section variables [monoid α] [add_monoid β] [distrib_mul_action α β] lemma list.smul_sum {r : α} {l : list β} : r • l.sum = (l.map ((•) r)).sum := (const_smul_hom β r).map_list_sum l end section variables [monoid α] [add_comm_monoid β] [distrib_mul_action α β] lemma multiset.smul_sum {r : α} {s : multiset β} : r • s.sum = (s.map ((•) r)).sum := (const_smul_hom β r).map_multiset_sum s lemma finset.smul_sum {r : α} {f : γ → β} {s : finset γ} : r • ∑ x in s, f x = ∑ x in s, r • f x := (const_smul_hom β r).map_sum f s end
0ce7ae40fccbb5c6cc7e4b78b1a93ffbe819e7ad
130d371f971f05e5686dfbc39bba9b3867057815
/src/basic.lean
b14f780029c23e774c0bebcf1de7131fb3e7f3d1
[]
no_license
JasonKYi/analysis_with_filters
7d5df1a0966e21d54e3baa5b7e2b72938f190fa6
a1182aa3965f034d27b5cf493ee9737972cbbf2a
refs/heads/master
1,669,288,659,683
1,596,107,251,000
1,596,107,251,000
283,021,905
1
1
null
null
null
null
UTF-8
Lean
false
false
8,303
lean
import order.filter.basic topology.separation tactic variables {α : Type*} noncomputable theory open set classical local attribute [instance] classical.prop_decidable /- structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) -- A filter on `α` is a set of sets of `α` containing `α` itself, closed under -- supersets and intersection. -- NB. This definition of filters does not require `∅ ∉ sets`. This is done so -- we can create a lattice structure. `∅ ∉ sets` should be included as a -- seperate proposition in lemmas. -/ -- I'm going to follow -- https://web.archive.org/web/20071009170540/http://www.efnet-math.org/~david/mathematics/filters.pdf -- First, we will find a way to generate filters for any given set of sets of α -- To achieve this, we consider that the intersection of a collection of filters -- is also a filter, so therefore, a filter can be generated form a set of sets -- by taking the intersection of all filters containing this set, i.e. if `S` is -- type `set (set α)`, then the filter generated by `S` is -- ⋂₀ { F : filter α | S ⊆ F.sets } namespace filter instance : has_coe (filter α) (set (set α)) := ⟨λ F, F.sets⟩ /-! ### Basics -/ /- /-- The intersection of two filters is a filter-/ instance : has_inter (filter α) := ⟨λ F G, { sets := (F : set (set α)) ∩ (G : set (set α)), univ_sets := ⟨F.univ_sets, G.univ_sets⟩, sets_of_superset := λ _ _ ⟨hxF, hxG⟩ hsub, ⟨F.sets_of_superset hxF hsub, G.sets_of_superset hxG hsub⟩, inter_sets := λ x y ⟨hxF, hxG⟩ ⟨hyF, hyG⟩, ⟨F.inter_sets hxF hyF, G.inter_sets hxG hyG⟩ }⟩ -/ /-- The intersection of a collection of filters is a filter -/ instance : has_Inf (filter α) := { Inf := λ 𝒞, { sets := ⋂ (F ∈ 𝒞), (F : set (set α)), univ_sets := mem_bInter $ λ F hF, F.univ_sets, sets_of_superset := λ _ _ hx hsub, mem_bInter $ λ F hF, F.sets_of_superset (mem_bInter_iff.1 hx F hF) hsub, inter_sets := λ x y hx hy, mem_bInter $ λ F hF, F.inter_sets (mem_bInter_iff.1 hx F hF) (mem_bInter_iff.1 hy F hF) }} -- With that we can now define the filter generated by an arbitary set of sets /-- The filter generated from `S`, a set of sets of `α` is the Inf of all filters containing `S` -/ def generated_from (S : set (set α)) : filter α := Inf { F : filter α | S ⊆ F.sets } -- The method above generates the smallest filter that contains `S : set (set α)` -- On the other hand, we can generate a filter using `s : set α` be letting the -- filter be all supersets of `s`, this is called `principal s` localized "notation `𝓟` := filter.principal" in filter variables {S : set (set α)} lemma le_generated_from : S ⊆ generated_from S := λ s hs, mem_bInter (λ F hF, hF hs) -- Straightaway, we see that if `∅ ∈ S`, then `filter_generated_from S` is the -- powerset of `α` lemma generated_of_empty (hS : ∅ ∈ S) (s : set α) : s ∈ generated_from S := (generated_from S).sets_of_superset (le_generated_from hS) (empty_subset s) /-- Let `F` be a `ne_bot` filter on `α`, `F` is an ultra filter if for all `S : set α`, `S ∈ F` or `Sᶜ ∈ F` -/ @[class] structure ultra (F : filter α) := (ne_bot : ne_bot F) (mem_or_compl_mem {S : set α} : S ∈ F ∨ Sᶜ ∈ F) -- The ultra filter theorem states that for all `F : filter α`, there exists -- some ultra filter `𝕌`, `F ⊆ 𝕌`. -- The proof of this follows from Zorn's lemma. -- Let `F` be a filter on `α`, We have the filters of `α` that contain `F` form -- a poset. Let `𝒞` be a chain (a totaly ordered set) within this set, then by -- Zorn's lemma, `𝒞` has at least one maximum element. Thus, by checking this -- maximum element is indeed an ultra filter, we have found a ultra filter -- containing `F`. -- #check exists_maximal_of_chains_bounded -- theorem exists_ultra_ge (F : filter α) [ne_bot F] : -- ∃ (G : filter α) [H : ultra G], F ≤ G := sorry -- Let X be a Hausdorff space variables {X : Type*} [topological_space X] /-- A filter `F` on a Hausdorff space `X` has at most one limit -/ theorem tendsto_unique {x y : X} {F : filter X} [H : ne_bot F] [t2_space X] (hFx : tendsto id F (nhds x)) (hFy : tendsto id F (nhds y)) : x = y := begin by_contra hneq, rcases t2_space.t2 _ _ hneq with ⟨U, V, hU, hV, hxU, hyV, hdisj⟩, apply H, rw [←empty_in_sets_eq_bot, ←hdisj], refine F.inter_sets _ _, { rw ←@preimage_id _ U, exact tendsto_def.1 hFx U (mem_nhds_sets hU hxU) }, { rw ←@preimage_id _ V, exact tendsto_def.1 hFy V (mem_nhds_sets hV hyV) } end variables {Y : Type*} [topological_space Y] @[reducible] def filter_image (f : X → Y) (F : filter X) : filter Y := generate $ (λ s : set X, f '' s) '' F -- We'll use mathlib's `generate` and `map` which are the same -- as the ones we've defined but there is more APIs to work with /-- A filter `F : filter X` is said to converge to some `x : X` if `nhds x ⊆ F` -/ @[reducible] private def converge_to (F : filter X) (x : X) : Prop := (nhds x : set (set X)) ⊆ F -- This definition is equivalent to `tendsto id F (nhds x)` private lemma converge_to_iff (F : filter X) (x : X) : converge_to F x ↔ tendsto id F (nhds x) := begin refine ⟨λ h, tendsto_def.1 $ λ s hs, _, λ h, _⟩, { rw map_id, simpa using h hs }, { simp_rw [tendsto_def, preimage_id] at h, exact h } end /-- The neighbourhood filter of `x` converges to `x` -/ lemma nhds_tendsto (x : X) : tendsto id (nhds x) (nhds x) := λ U hU, by rwa map_id lemma mem_filter_image_iff {f : X → Y} {F : filter X} (V) : V ∈ map f F ↔ ∃ U ∈ F, f '' U ⊆ V := begin refine ⟨λ h, ⟨_, h, image_preimage_subset _ _⟩, λ h, _⟩, rcases h with ⟨U, hU₀, hU₁⟩, rw mem_map, apply F.sets_of_superset hU₀, intros u hu, rw mem_set_of_eq, apply hU₁, rw mem_image, exact ⟨u, hu, rfl⟩ end lemma nhds_subset_filter_of_tendsto {x : X} {F : filter X} (hF : tendsto id F (nhds x)) : (nhds x : set (set X)) ⊆ F := begin intros s hs, have := tendsto_def.1 hF _ hs, rwa preimage_id at this end /-- A map between topological spaces `f : X → Y` is continuous at some `x : X` if for all `F : filter X` that tends to `x`, `map F` tends to `f(x)` -/ theorem continuous_of_filter_tendsto {x : X} (f : X → Y) (hF : ∀ F : filter X, tendsto id F (nhds x) → tendsto id (map f F) (nhds (f x))) : continuous_at f x := λ _ hU, tendsto_def.1 (hF _ $ nhds_tendsto x) _ hU /-- If `f : X → Y` is a continuous map between topological spaces, then for all `F : filter X` that tends to `x`, `map F` tends to `f(x)` -/ theorem filter_tendsto_of_continuous {x : X} {F : filter X} (f : X → Y) (hf : continuous_at f x) (hF : tendsto id F (nhds x)) : tendsto id (map f F) (nhds (f x)) := begin rw tendsto_def at *, intros U hU, exact nhds_subset_filter_of_tendsto hF (hf hU), end /-! ### Product Filters -/ /- Given two filters `F` and `G` on the topological spaces `X` and `Y` respectively, we define the the product filter `F × G` as a filter on the product space `X × Y` such that `prod F G := F.comap prod.fst ⊓ G.comap prod.snd` where `prod.fst = (a, b) ↦ a`, `prod.snd = (a, b) ↦ b` and `(C : filter β).comap (f : α → β)` is the filter generated by the set of preimages of sets contained in `C`, i.e. `(C.comap f).sets = generate { f⁻¹(s) | s ∈ C }`. -/ -- We borrow the notation of product filters from mathlib localized "infix ` ×ᶠ `:60 := filter.prod" in filter -- Write some theorems here maybe? -- TODO : make the natural projection : filter (X × Y) → filter X /-! ### Compactness -/ variables {C : Type*} [topological_space C] [compact_space C] /- In mathlib a compact space is a topological space that satisfy the `is_compact` proposition where `def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃ a ∈ s, cluster_pt a f` (`cluset_pt a f` means a is a limit point of f) -/ end filter
954994dc679e39f52d77023d4de8dbf65194ef88
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/sum.lean
00aec690287945d9a99bbffa9d02c1d0fafb2a8e
[ "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
4,107
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro More theorems about the sum type. -/ universes u v variables {α : Type u} {β : Type v} open sum attribute [derive decidable_eq] sum @[simp] theorem sum.forall {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ (∀ b, p (inr b)) := ⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩ @[simp] theorem sum.exists {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) := ⟨λ h, match h with | ⟨inl a, h⟩ := or.inl ⟨a, h⟩ | ⟨inr b, h⟩ := or.inr ⟨b, h⟩ end, λ h, match h with | or.inl ⟨a, h⟩ := ⟨inl a, h⟩ | or.inr ⟨b, h⟩ := ⟨inr b, h⟩ end⟩ namespace sum protected def map {α α' β β'} (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β' | (sum.inl x) := sum.inl (f x) | (sum.inr x) := sum.inr (g x) @[simp] theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b := ⟨inl.inj, congr_arg _⟩ @[simp] theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b := ⟨inr.inj, congr_arg _⟩ @[simp] theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b. @[simp] theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a. protected def elim {α β γ : Sort*} (f : α → γ) (g : β → γ) : α ⊕ β → γ := λ x, sum.rec_on x f g @[simp] lemma elim_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : α) : sum.elim f g (inl x) = f x := rfl @[simp] lemma elim_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : β) : sum.elim f g (inr x) = g x := rfl lemma elim_injective {α β γ : Sort*} {f : α → γ} {g : β → γ} (hf : function.injective f) (hg : function.injective g) (hfg : ∀ a b, f a ≠ g b) : function.injective (sum.elim f g) := λ x y, sum.rec_on x (sum.rec_on y (λ x y hxy, by rw hf hxy) (λ x y hxy, false.elim $ hfg _ _ hxy)) (sum.rec_on y (λ x y hxy, false.elim $ hfg x y hxy.symm) (λ x y hxy, by rw hg hxy)) section variables (ra : α → α → Prop) (rb : β → β → Prop) /-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`, otherwise use the respective order on `α` or `β`. -/ inductive lex : α ⊕ β → α ⊕ β → Prop | inl {a₁ a₂} (h : ra a₁ a₂) : lex (inl a₁) (inl a₂) | inr {b₁ b₂} (h : rb b₁ b₂) : lex (inr b₁) (inr b₂) | sep (a b) : lex (inl a) (inr b) variables {ra rb} @[simp] theorem lex_inl_inl {a₁ a₂} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ := ⟨λ h, by cases h; assumption, lex.inl _⟩ @[simp] theorem lex_inr_inr {b₁ b₂} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ := ⟨λ h, by cases h; assumption, lex.inr _⟩ @[simp] theorem lex_inr_inl {b a} : ¬ lex ra rb (inr b) (inl a) := λ h, by cases h attribute [simp] lex.sep theorem lex_acc_inl {a} (aca : acc ra a) : acc (lex ra rb) (inl a) := begin induction aca with a H IH, constructor, intros y h, cases h with a' _ h', exact IH _ h' end theorem lex_acc_inr (aca : ∀ a, acc (lex ra rb) (inl a)) {b} (acb : acc rb b) : acc (lex ra rb) (inr b) := begin induction acb with b H IH, constructor, intros y h, cases h with _ _ _ b' _ h' a, { exact IH _ h' }, { exact aca _ } end theorem lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) := have aca : ∀ a, acc (lex ra rb) (inl a), from λ a, lex_acc_inl (ha.apply a), ⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩ end /-- Swap the factors of a sum type -/ @[simp] def swap : α ⊕ β → β ⊕ α | (inl a) := inr a | (inr b) := inl b @[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x := by cases x; refl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) := funext $ swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap end sum
b95f38d09cb6261499b4354b916e312dea5dcfa1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/casesRec.lean
2adf9e10e19929745caf7e0465687724ff6162bd
[ "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,029
lean
namespace Ex1 def f (x : Nat) : Nat := by cases x with | zero => exact 1 | succ x' => apply Nat.mul 2 exact f x' #eval f 10 example : f x.succ = 2 * f x := rfl end Ex1 namespace Ex2 inductive Foo where | mk : List Foo → Foo mutual def g (x : Foo) : Nat := by cases x with | mk xs => exact gs xs def gs (xs : List Foo) : Nat := by cases xs with | nil => exact 1 | cons x xs => apply Nat.add exact g x exact gs xs end end Ex2 namespace Ex3 inductive Foo where | a | b | c | pair: Foo × Foo → Foo def Foo.deq (a b : Foo) : Decidable (a = b) := by cases a <;> cases b any_goals apply isFalse Foo.noConfusion any_goals apply isTrue rfl case pair a b => let (a₁, a₂) := a let (b₁, b₂) := b exact match deq a₁ b₁, deq a₂ b₂ with | isTrue h₁, isTrue h₂ => isTrue (by rw [h₁,h₂]) | isFalse h₁, _ => isFalse (fun h => by cases h; cases (h₁ rfl)) | _, isFalse h₂ => isFalse (fun h => by cases h; cases (h₂ rfl)) end Ex3
ac523f793c39eb291340ebd7ca82dc9c643cc451
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Init/Data/String/Basic.lean
204a4371a7132809e420ad9d975e45357aff6b88
[ "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
17,122
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 universe u def List.asString (s : List Char) : String := ⟨s⟩ namespace String instance : LT 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) partial def findAux (s : String) (p : Char → Bool) (stopPos : Pos) (pos : Pos) : Pos := if pos == stopPos then pos else if p (s.get pos) then pos else findAux s p stopPos (s.next pos) @[inline] def find (s : String) (p : Char → Bool) : Pos := findAux s p s.bsize 0 partial def revFindAux (s : String) (p : Char → Bool) (pos : Pos) : Option Pos := if p (s.get pos) then some pos else if pos == 0 then none else revFindAux s p (s.prev pos) def revFind (s : String) (p : Char → Bool) : Option Pos := if s.bsize == 0 then none else revFindAux s p (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 := (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 : 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 where 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 → α) (init : α) (s : String) : α := foldlAux f s s.bsize 0 init @[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 → α → α) (init : α) (s : String) : α := foldrAux f init 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 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⟩ /-- Return the codepoint at the given offset into the substring. -/ @[inline] def get : Substring → String.Pos → Char | ⟨s, b, _⟩, p => s.get (b+p) /-- Given an offset of a codepoint into the substring, return the offset there of the next codepoint. -/ @[inline] private def next : Substring → String.Pos → String.Pos | ⟨s, b, e⟩, p => let absP := b+p if absP = e then p else s.next absP - b /-- Given an offset of a codepoint into the substring, return the offset there of the previous codepoint. -/ @[inline] private def prev : Substring → String.Pos → String.Pos | ⟨s, b, _⟩, p => let absP := b+p if absP = b then p else s.prev absP - b private def nextn : Substring → Nat → String.Pos → String.Pos | ss, 0, p => p | ss, i+1, p => ss.nextn i (ss.next p) private 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 /-- Return the offset into `s` of the first occurence of `c` in `s`, or `s.bsize` if `c` doesn't occur. -/ @[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, b + ss.nextn n 0, e⟩ @[inline] def dropRight : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b, b + ss.prevn n ss.bsize⟩ @[inline] def take : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b, b + ss.nextn n 0⟩ @[inline] def takeRight : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b + ss.prevn n ss.bsize, 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 → α) (init : α) (s : Substring) : α := match s with | ⟨s, b, e⟩ => String.foldlAux f s e b init @[inline] def foldr {α : Type u} (f : Char → α → α) (init : α) (s : Substring) : α := match s with | ⟨s, b, e⟩ => String.foldrAux f init 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] private 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] private 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 := -- TODO: should not allocate ss1.bsize == ss2.bsize && 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 takeRightWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.takeRightWhile p).toString def dropRightWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.dropRightWhile p).toString def startsWith (s pre : String) : Bool := s.toSubstring.take pre.length == pre.toSubstring def endsWith (s post : String) : Bool := s.toSubstring.takeRight post.length == post.toSubstring 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 toUpper (s : String) : String := s.map Char.toUpper def toLower (s : String) : String := s.map Char.toLower def capitalize (s : String) := s.set 0 <| s.get 0 |>.toUpper def decapitalize (s : String) := s.set 0 <| s.get 0 |>.toLower end String protected def Char.toString (c : Char) : String := String.singleton c
753377a714b0f90c4716082c99855751aed7f432
80162757f50b09d3cad5564907e4c9b00742e045
/order.lean
5246db0197c907b766004faff60917e0c97e217c
[]
no_license
EdAyers/edlib
cc30d0a54fed347a85b6df6045f68e6b48bc71a3
78b8c5d91f023f939c102837d748868e2f3ed27d
refs/heads/master
1,586,459,758,216
1,571,322,179,000
1,571,322,179,000
160,538,917
2
0
null
null
null
null
UTF-8
Lean
false
false
1,603
lean
def order_dual (α : Type*) := α namespace order_dual instance has_le (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance has_lt (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ instance has_preorder (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, .. order_dual.has_le α } instance has_partial_order (α : Type*) [po : partial_order α] : partial_order (order_dual α) := { le_antisymm := begin intros, apply @le_antisymm _ po, assumption, assumption end , ..(order_dual.has_preorder α) } instance has_linear_order (α : Type*) [po : linear_order α] : linear_order (order_dual α) := { le_total := λ a b, or.swap $ le_total a b , ..(order_dual.has_partial_order α) } instance has_decidable_le (α : Type*) [hle : has_le α] [d : decidable_rel hle.le] : decidable_rel (order_dual.has_le α).le := λ x y, d y x instance has_decidable_lt (α : Type*) [hlt : has_lt α] [d : decidable_rel hlt.lt] : decidable_rel (order_dual.has_lt α).lt := λ x y, d y x lemma transitive_lt (α : Type*) [hlt : has_lt α] [tr : transitive hlt.lt] : transitive (@order_dual.has_lt α hlt).lt := λ x y z p q, tr q p instance has_decidable_linear_order (α : Type*) [dlo : decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_eq := λ a b, @decidable_linear_order.decidable_eq α dlo a b , decidable_le := λ a b, @decidable_linear_order.decidable_le α dlo b a , ..(order_dual.has_linear_order α) } end order_dual
d67b69d0e03261deaa5196bed150a84049223a64
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/list/intervals.lean
0e6984b4b3ccddc3cbd68cf3be08477ebcc7864c
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,956
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.list.lattice import data.list.range /-! # Intervals in ℕ > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines intervals of naturals. `list.Ico m n` is the list of integers greater than `m` and strictly less than `n`. ## TODO - Define `Ioo` and `Icc`, state basic lemmas about them. - Also do the versions for integers? - One could generalise even further, defining 'locally finite partial orders', for which `set.Ico a b` is `[finite]`, and 'locally finite total orders', for which there is a list model. - Once the above is done, get rid of `data.int.range` (and maybe `list.range'`?). -/ open nat namespace list /-- `Ico n m` is the list of natural numbers `n ≤ x < m`. (Ico stands for "interval, closed-open".) See also `data/set/intervals.lean` for `set.Ico`, modelling intervals in general preorders, and `multiset.Ico` and `finset.Ico` for `n ≤ x < m` as a multiset or as a finset. -/ def Ico (n m : ℕ) : list ℕ := range' n (m - n) namespace Ico theorem zero_bot (n : ℕ) : Ico 0 n = range n := by rw [Ico, tsub_zero, range_eq_range'] @[simp] theorem length (n m : ℕ) : length (Ico n m) = m - n := by { dsimp [Ico], simp only [length_range'] } theorem pairwise_lt (n m : ℕ) : pairwise (<) (Ico n m) := by { dsimp [Ico], simp only [pairwise_lt_range'] } theorem nodup (n m : ℕ) : nodup (Ico n m) := by { dsimp [Ico], simp only [nodup_range'] } @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := suffices n ≤ l ∧ l < n + (m - n) ↔ n ≤ l ∧ l < m, by simp [Ico, this], begin cases le_total n m with hnm hmn, { rw [add_tsub_cancel_of_le hnm] }, { rw [tsub_eq_zero_iff_le.mpr hmn, add_zero], exact and_congr_right (assume hnl, iff.intro (assume hln, (not_le_of_gt hln hnl).elim) (assume hlm, lt_of_lt_of_le hlm hmn)) } end theorem eq_nil_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = [] := by simp [Ico, tsub_eq_zero_iff_le.mpr h] theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := by rw [Ico, Ico, map_add_range', add_tsub_add_eq_tsub_right, add_comm n k] theorem map_sub (n m k : ℕ) (h₁ : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := by rw [Ico, Ico, tsub_tsub_tsub_cancel_right h₁, map_sub_range' _ _ _ h₁] @[simp] theorem self_empty {n : ℕ} : Ico n n = [] := eq_nil_of_le (le_refl n) @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = [] ↔ m ≤ n := iff.intro (assume h, tsub_eq_zero_iff_le.mp $ by rw [← length, h, list.length]) eq_nil_of_le lemma append_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ++ Ico m l = Ico n l := begin dunfold Ico, convert range'_append _ _ _, { exact (add_tsub_cancel_of_le hnm).symm }, { rwa [← add_tsub_assoc_of_le hnm, tsub_add_cancel_of_le] } end @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = [] := begin apply eq_nil_iff_forall_not_mem.2, intro a, simp only [and_imp, not_and, not_lt, list.mem_inter, list.Ico.mem], intros h₁ h₂ h₃, exfalso, exact not_lt_of_ge h₃ h₂ end @[simp] lemma bag_inter_consecutive (n m l : ℕ) : list.bag_inter (Ico n m) (Ico m l) = [] := (bag_inter_nil_iff_inter_nil _ _).2 (inter_consecutive n m l) @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = [n] := by { dsimp [Ico], simp [add_tsub_cancel_left] } theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] := by { rwa [← succ_singleton, append_consecutive], exact nat.le_succ _ } theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := by { rw [← append_consecutive (nat.le_succ n) h, succ_singleton], refl } @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = [m - 1] := by { dsimp [Ico], rw tsub_tsub_cancel_of_le (succ_le_of_lt h), simp } theorem chain'_succ (n m : ℕ) : chain' (λa b, b = succ a) (Ico n m) := begin by_cases n < m, { rw [eq_cons h], exact chain_succ_range' _ _ }, { rw [eq_nil_of_le (le_of_not_gt h)], trivial } end @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := by simp lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := filter_eq_self.2 $ assume k hk, lt_of_lt_of_le (mem.1 hk).2 hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = [] := filter_eq_nil.2 $ assume k hk, not_lt_of_le $ le_trans hln $ (mem.1 hk).1 lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := begin cases le_total n l with hnl hln, { rw [← append_consecutive hnl hlm, filter_append, filter_lt_of_top_le (le_refl l), filter_lt_of_le_bot (le_refl l), append_nil] }, { rw [eq_nil_of_le hln, filter_lt_of_le_bot hln] } end @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := begin cases le_total m l with hml hlm, { rw [min_eq_left hml, filter_lt_of_top_le hml] }, { rw [min_eq_right hlm, filter_lt_of_ge hlm] } end lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := filter_eq_self.2 $ assume k hk, le_trans hln (mem.1 hk).1 lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = [] := filter_eq_nil.2 $ assume k hk, not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml) lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := begin cases le_total l m with hlm hml, { rw [← append_consecutive hnl hlm, filter_append, filter_le_of_top_le (le_refl l), filter_le_of_le_bot (le_refl l), nil_append] }, { rw [eq_nil_of_le hml, filter_le_of_top_le hml] } end @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := begin cases le_total n l with hnl hln, { rw [max_eq_right hnl, filter_le_of_le hnl] }, { rw [max_eq_left hln, filter_le_of_le_bot hln] } end lemma filter_lt_of_succ_bot {n m : ℕ} (hnm : n < m) : (Ico n m).filter (λ x, x < n + 1) = [n] := begin have r : min m (n + 1) = n + 1 := (@inf_eq_right _ _ m (n + 1)).mpr hnm, simp [filter_lt n m (n + 1), r], end @[simp] lemma filter_le_of_bot {n m : ℕ} (hnm : n < m) : (Ico n m).filter (λ x, x ≤ n) = [n] := begin rw ←filter_lt_of_succ_bot hnm, exact filter_congr' (λ _ _, lt_succ_iff.symm), end /-- For any natural numbers n, a, and b, one of the following holds: 1. n < a 2. n ≥ b 3. n ∈ Ico a b -/ lemma trichotomy (n a b : ℕ) : n < a ∨ b ≤ n ∨ n ∈ Ico a b := begin by_cases h₁ : n < a, { left, exact h₁ }, { right, by_cases h₂ : n ∈ Ico a b, { right, exact h₂ }, { left, simp only [Ico.mem, not_and, not_lt] at *, exact h₂ h₁ }} end end Ico end list
8e505b2c9a586a23ebc2b843a0c9da119f8b95a2
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/computability/partrec_code.lean
6602923d380a5cb239c1cb8aa74f39016d0667ed
[ "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
38,845
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Godel numbering for partial recursive functions. -/ import computability.partrec open encodable denumerable namespace nat.partrec open nat (mkpair) theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) := partrec₂.unpaired'.2 $ begin refine partrec.map ((@partrec₂.unpaired' (λ (a b : ℕ), nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + b))))).1 _) (primrec.nat_add.comp primrec.snd $ primrec.snd.comp primrec.fst).to_comp.to₂, have := rfind (partrec₂.unpaired'.2 ((partrec.nat_iff.2 hf).comp (primrec₂.mkpair.comp (primrec.fst.comp $ primrec.unpair.comp primrec.fst) (primrec.nat_add.comp primrec.snd (primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).to₂), simp at this, exact this end inductive code : Type | zero : code | succ : code | left : code | right : code | pair : code → code → code | comp : code → code → code | prec : code → code → code | rfind' : code → code end nat.partrec namespace nat.partrec.code open nat (mkpair unpair) open nat.partrec (code) instance : inhabited code := ⟨zero⟩ protected def const : ℕ → code | 0 := zero | (n+1) := comp succ (const n) theorem const_inj : Π {n₁ n₂}, nat.partrec.code.const n₁ = nat.partrec.code.const n₂ → n₁ = n₂ | 0 0 h := by simp | (n₁+1) (n₂+1) h := by { dsimp [nat.partrec.code.const] at h, injection h with h₁ h₂, simp only [const_inj h₂] } protected def id : code := pair left right def curry (c : code) (n : ℕ) : code := comp c (pair (code.const n) code.id) def encode_code : code → ℕ | zero := 0 | succ := 1 | left := 2 | right := 3 | (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4 def of_nat_code : ℕ → code | 0 := zero | 1 := succ | 2 := left | 3 := right | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, match n.bodd, n.div2.bodd with | ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, tt := rfind' (of_nat_code m) end private theorem encode_of_nat_code : ∀ n, encode_code (of_nat_code n) = n | 0 := by simp [of_nat_code, encode_code] | 1 := by simp [of_nat_code, encode_code] | 2 := by simp [of_nat_code, encode_code] | 3 := by simp [of_nat_code, encode_code] | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, have IH : _ := encode_of_nat_code m, have IH1 : _ := encode_of_nat_code m.unpair.1, have IH2 : _ := encode_of_nat_code m.unpair.2, begin transitivity, swap, rw [← nat.bit_decomp n, ← nat.bit_decomp n.div2], simp [encode_code, of_nat_code, -add_comm], cases n.bodd; cases n.div2.bodd; simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit] end instance : denumerable code := mk' ⟨encode_code, of_nat_code, λ c, by induction c; try {refl}; simp [ encode_code, of_nat_code, -add_comm, *], encode_of_nat_code⟩ theorem encode_code_eq : encode = encode_code := rfl theorem of_nat_code_eq : of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)), exact ⟨ lt_of_le_of_lt (nat.left_le_mkpair _ _) this, lt_of_le_of_lt (nat.right_le_mkpair _ _) this⟩ end theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code] end theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code], end theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, refine lt_of_le_of_lt (le_trans this _) (lt_add_of_pos_right _ (dec_trivial:0<4)), exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $ nat.bit0_lt_bit1 $ le_refl _), end section open primrec theorem pair_prim : primrec₂ pair := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem comp_prim : primrec₂ comp := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit1.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem prec_prim : primrec₂ prec := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem rfind_prim : primrec rfind' := of_nat_iff.2 $ encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit1.comp $ encode_iff.2 $ primrec.of_nat code) (const 4) theorem rec_prim' {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code × code × σ × σ → σ} (hpr : primrec₂ pr) {co : α → code × code × σ × σ → σ} (hco : primrec₂ co) {pc : α → code × code × σ × σ → σ} (hpc : primrec₂ pc) {rf : α → code × σ → σ} (hrf : primrec₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in primrec (λ a, F a (c a) : α → σ) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((primrec.of_nat code).comp m).pair s)) (hpc.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end theorem rec_prim {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code → code → σ → σ → σ} (hpr : primrec (λ a : α × code × code × σ × σ, pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {co : α → code → code → σ → σ → σ} (hco : primrec (λ a : α × code × code × σ × σ, co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {pc : α → code → code → σ → σ → σ} (hpc : primrec (λ a : α × code × code × σ × σ, pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {rf : α → code → σ → σ} (hrf : primrec (λ a : α × code × σ, rf a.1 a.2.1 a.2.2)) : let F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m) s) (pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)) (cond n.div2.bodd (co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂) (pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s)) (hpc.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end section open computable /- TODO(Mario): less copy-paste from previous proof -/ theorem rec_computable {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : computable c) {z : α → σ} (hz : computable z) {s : α → σ} (hs : computable s) {l : α → σ} (hl : computable l) {r : α → σ} (hr : computable r) {pr : α → code × code × σ × σ → σ} (hpr : computable₂ pr) {co : α → code × code × σ × σ → σ} (hco : computable₂ co) {pc : α → code × code × σ × σ → σ} (hpc : computable₂ pc) {rf : α → code × σ → σ} (hrf : computable₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in computable (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : computable G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (computable.unpair.comp m), have m₂ := snd.comp (computable.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((computable.of_nat code).comp m).pair s)) (hpc.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) (computable.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : computable₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp computable.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end def eval : code → ℕ →. ℕ | zero := pure 0 | succ := nat.succ | left := ↑(λ n : ℕ, n.unpair.1) | right := ↑(λ n : ℕ, n.unpair.2) | (pair cf cg) := λ n, mkpair <$> eval cf n <*> eval cg n | (comp cf cg) := λ n, eval cg n >>= eval cf | (prec cf cg) := nat.unpaired (λ a n, n.elim (eval cf a) (λ y IH, do i ← IH, eval cg (mkpair a (mkpair y i)))) | (rfind' cf) := nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> eval cf (mkpair a (n + m)))).map (+ m)) instance : has_mem (ℕ →. ℕ) code := ⟨λ f c, eval c = f⟩ @[simp] theorem eval_const : ∀ n m, eval (code.const n) m = part.some n | 0 m := rfl | (n+1) m := by simp! * @[simp] theorem eval_id (n) : eval code.id n = part.some n := by simp! [(<*>)] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) := by simp! [(<*>)] theorem const_prim : primrec code.const := (primrec.id.nat_iterate (primrec.const zero) (comp_prim.comp (primrec.const succ) primrec.snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, code.const, function.iterate_succ'] theorem curry_prim : primrec₂ curry := comp_prim.comp primrec.fst $ pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id) theorem curry_inj {c₁ c₂ n₁ n₂} (h : curry c₁ n₁ = curry c₂ n₂) : c₁ = c₂ ∧ n₁ = n₂ := ⟨by injection h, by { injection h, injection h with h₁ h₂, injection h₂ with h₃ h₄, exact const_inj h₃ }⟩ theorem smn : ∃ f : code → ℕ → code, computable₂ f ∧ ∀ c n x, eval (f c n) x = eval c (mkpair n x) := ⟨curry, primrec₂.to_comp curry_prim, eval_curry⟩ theorem exists_code {f : ℕ →. ℕ} : nat.partrec f ↔ ∃ c : code, eval c = f := ⟨λ h, begin induction h, case nat.partrec.zero { exact ⟨zero, rfl⟩ }, case nat.partrec.succ { exact ⟨succ, rfl⟩ }, case nat.partrec.left { exact ⟨left, rfl⟩ }, case nat.partrec.right { exact ⟨right, rfl⟩ }, case nat.partrec.pair : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨pair cf cg, rfl⟩ }, case nat.partrec.comp : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨comp cf cg, rfl⟩ }, case nat.partrec.prec : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨prec cf cg, rfl⟩ }, case nat.partrec.rfind : f pf hf { rcases hf with ⟨cf, rfl⟩, refine ⟨comp (rfind' cf) (pair code.id zero), _⟩, simp [eval, (<*>), pure, pfun.pure, part.map_id'] }, end, λ h, begin rcases h with ⟨c, rfl⟩, induction c, case nat.partrec.code.zero { exact nat.partrec.zero }, case nat.partrec.code.succ { exact nat.partrec.succ }, case nat.partrec.code.left { exact nat.partrec.left }, case nat.partrec.code.right { exact nat.partrec.right }, case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg }, case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg }, case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg }, case nat.partrec.code.rfind' : cf pf { exact pf.rfind' }, end⟩ def evaln : ∀ k : ℕ, code → ℕ → option ℕ | 0 _ := λ m, none | (k+1) zero := λ n, guard (n ≤ k) >> pure 0 | (k+1) succ := λ n, guard (n ≤ k) >> pure (nat.succ n) | (k+1) left := λ n, guard (n ≤ k) >> pure n.unpair.1 | (k+1) right := λ n, guard (n ≤ k) >> pure n.unpair.2 | (k+1) (pair cf cg) := λ n, guard (n ≤ k) >> mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n | (k+1) (comp cf cg) := λ n, guard (n ≤ k) >> do x ← evaln (k+1) cg n, evaln (k+1) cf x | (k+1) (prec cf cg) := λ n, guard (n ≤ k) >> n.unpaired (λ a n, n.cases (evaln (k+1) cf a) $ λ y, do i ← evaln k (prec cf cg) (mkpair a y), evaln (k+1) cg (mkpair a (mkpair y i))) | (k+1) (rfind' cf) := λ n, guard (n ≤ k) >> n.unpaired (λ a m, do x ← evaln (k+1) cf (mkpair a m), if x = 0 then pure m else evaln k (rfind' cf) (mkpair a (m+1))) theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k | 0 c n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin suffices : ∀ {o : option ℕ}, x ∈ guard (n ≤ k) >> o → n < k + 1, { cases c; rw [evaln] at h; exact this h }, simpa [(>>)] using nat.lt_succ_of_le end theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n | 0 k₂ c n x hl h := by simp [evaln] at h; cases h | (k+1) (k₂+1) c n x hl h := begin have hl' := nat.le_of_succ_le_succ hl, have : ∀ {k k₂ n x : ℕ} {o₁ o₂ : option ℕ}, k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) → x ∈ guard (n ≤ k) >> o₁ → x ∈ guard (n ≤ k₂) >> o₂, { simp [(>>)], introv h h₁ h₂ h₃, exact ⟨le_trans h₂ h, h₁ h₃⟩ }, simp at h ⊢, induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; rw [evaln] at h ⊢; refine this hl' (λ h, _) h, iterate 4 {exact h}, { -- pair cf cg simp [(<*>)] at h ⊢, exact h.imp (λ a, and.imp (hf _ _) $ Exists.imp $ λ b, and.imp_left (hg _ _)) }, { -- comp cf cg simp at h ⊢, exact h.imp (λ a, and.imp (hg _ _) (hf _ _)) }, { -- prec cf cg revert h, simp, induction n.unpair.2; simp, { apply hf }, { exact λ y h₁ h₂, ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩ } }, { -- rfind' cf simp at h ⊢, refine h.imp (λ x, and.imp (hf _ _) _), by_cases x0 : x = 0; simp [x0], exact evaln_mono hl' } end theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n | 0 _ n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; simp [eval, evaln, (>>), (<*>)] at h ⊢; cases h with _ h, iterate 4 {simpa [pure, pfun.pure, eq_comm] using h}, { -- pair cf cg rcases h with ⟨y, ef, z, eg, rfl⟩, exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ }, { --comp hf hg rcases h with ⟨y, eg, ef⟩, exact ⟨_, hg _ _ eg, hf _ _ ef⟩ }, { -- prec cf cg revert h, induction n.unpair.2 with m IH generalizing x; simp, { apply hf }, { refine λ y h₁ h₂, ⟨y, IH _ _, _⟩, { have := evaln_mono k.le_succ h₁, simp [evaln, (>>)] at this, exact this.2 }, { exact hg _ _ h₂ } } }, { -- rfind' cf rcases h with ⟨m, h₁, h₂⟩, by_cases m0 : m = 0; simp [m0] at h₂, { exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, λ m, (nat.not_lt_zero _).elim⟩, by injection h₂ with h₂; simp [h₂]⟩ }, { have := evaln_sound h₂, simp [eval] at this, rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, refine ⟨ y+1, ⟨by simpa [add_comm, add_left_comm] using hy₁, λ i im, _⟩, by simp [add_comm, add_left_comm] ⟩, cases i with i, { exact ⟨m, by simpa using hf _ _ h₁, m0⟩ }, { rcases hy₂ (nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩, exact ⟨z, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hz, z0⟩ } } } end theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := ⟨λ h, begin suffices : ∃ k, x ∈ evaln (k+1) c n, { exact let ⟨k, h⟩ := this in ⟨k+1, h⟩ }, induction c generalizing n x; simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h ⊢, iterate 4 { exact ⟨⟨_, le_refl _⟩, h.symm⟩ }, case nat.partrec.code.pair : cf cg hf hg { rcases h with ⟨x, hx, y, hy, rfl⟩, rcases hf hx with ⟨k₁, hk₁⟩, rcases hg hy with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, refine ⟨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂, rfl⟩ }, case nat.partrec.code.comp : cf cg hf hg { rcases h with ⟨y, hy, hx⟩, rcases hg hy with ⟨k₁, hk₁⟩, rcases hf hx with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ }, case nat.partrec.code.prec : cf cg hf hg { revert h, generalize : n.unpair.1 = n₁, generalize : n.unpair.2 = n₂, induction n₂ with m IH generalizing x n; simp, { intro, rcases hf h with ⟨k, hk⟩, exact ⟨_, le_max_left _ _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk⟩ }, { intros y hy hx, rcases IH hy with ⟨k₁, nk₁, hk₁⟩, rcases hg hx with ⟨k₂, hk₂⟩, refine ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_of_le_left $ le_trans (le_max_left _ (mkpair n₁ m)) nk₁, y, evaln_mono (nat.succ_le_succ $ le_max_left _ _) _, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hk₂⟩, simp [evaln, (>>)], exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩ } }, case nat.partrec.code.rfind' : cf hf { rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, suffices : ∃ k, y + n.unpair.2 ∈ evaln (k+1) (rfind' cf) (mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]}, revert hy₁ hy₂, generalize : n.unpair.2 = m, intros, induction y with y IH generalizing m; simp [evaln, (>>)], { simp at hy₁, rcases hf hy₁ with ⟨k, hk⟩, exact ⟨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; refl⟩ }, { rcases hy₂ (nat.succ_pos _) with ⟨a, ha, a0⟩, rcases hf ha with ⟨k₁, hk₁⟩, rcases IH m.succ (by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₁) (λ i hi, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₂ (nat.succ_lt_succ hi)) with ⟨k₂, hk₂⟩, use (max k₁ k₂).succ, rw [zero_add] at hk₁, use (nat.le_succ_of_le $ le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁), use a, use evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hk₁, simpa [nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right, add_comm, add_left_comm] using evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂ } } end, λ ⟨k, h⟩, evaln_sound h⟩ section open primrec private def lup (L : list (list (option ℕ))) (p : ℕ × code) (n : ℕ) := do l ← L.nth (encode p), o ← l.nth n, o private lemma hlup : primrec (λ p:_×(_×_)×_, lup p.1 p.2.1 p.2.2) := option_bind (list_nth.comp fst (primrec.encode.comp $ fst.comp snd)) (option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd) private def G (L : list (list (option ℕ))) : option (list (option ℕ)) := option.some $ let a := of_nat (ℕ × code) L.length, k := a.1, c := a.2 in (list.range k).map (λ n, k.cases none $ λ k', nat.partrec.code.rec_on c (some 0) -- zero (some (nat.succ n)) (some n.unpair.1) (some n.unpair.2) (λ cf cg _ _, do x ← lup L (k, cf) n, y ← lup L (k, cg) n, some (mkpair x y)) (λ cf cg _ _, do x ← lup L (k, cg) n, lup L (k, cf) x) (λ cf cg _ _, let z := n.unpair.1 in n.unpair.2.cases (lup L (k, cf) z) (λ y, do i ← lup L (k', c) (mkpair z y), lup L (k, cg) (mkpair z (mkpair y i)))) (λ cf _, let z := n.unpair.1, m := n.unpair.2 in do x ← lup L (k, cf) (mkpair z m), x.cases (some m) (λ _, lup L (k', c) (mkpair z (m+1))))) private lemma hG : primrec G := begin have a := (primrec.of_nat (ℕ × code)).comp list_length, have k := fst.comp a, refine option_some.comp (list_map (list_range.comp k) (_ : primrec _)), replace k := k.comp fst, have n := snd, refine nat_cases k (const none) (_ : primrec _), have k := k.comp fst, have n := n.comp fst, have k' := snd, have c := snd.comp (a.comp $ fst.comp fst), apply rec_prim c (const (some 0)) (option_some.comp (primrec.succ.comp n)) (option_some.comp (fst.comp $ primrec.unpair.comp n)) (option_some.comp (snd.comp $ primrec.unpair.comp n)), { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cf).pair n) (option_map ((hlup.comp $ L.pair $ (k.pair cg).pair n).comp fst) (primrec₂.mkpair.comp (snd.comp fst) snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cg).pair n) (hlup.comp ((L.comp fst).pair $ ((k.pair cf).comp fst).pair snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, have z := fst.comp (primrec.unpair.comp n), refine nat_cases (snd.comp (primrec.unpair.comp n)) (hlup.comp $ L.pair $ (k.pair cf).pair z) (_ : primrec _), have L := L.comp fst, have z := z.comp fst, have y := snd, refine option_bind (hlup.comp $ L.pair $ (((k'.pair c).comp fst).comp fst).pair (primrec₂.mkpair.comp z y)) (_ : primrec _), have z := z.comp fst, have y := y.comp fst, have i := snd, exact hlup.comp ((L.comp fst).pair $ ((k.pair cg).comp $ fst.comp fst).pair $ primrec₂.mkpair.comp z $ primrec₂.mkpair.comp y i) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have z := fst.comp (primrec.unpair.comp n), have m := snd.comp (primrec.unpair.comp n), refine option_bind (hlup.comp $ L.pair $ (k.pair cf).pair (primrec₂.mkpair.comp z m)) (_ : primrec _), have m := m.comp fst, exact nat_cases snd (option_some.comp m) ((hlup.comp ((L.comp fst).pair $ ((k'.pair c).comp $ fst.comp fst).pair (primrec₂.mkpair.comp (z.comp fst) (primrec.succ.comp m)))).comp fst) } end private lemma evaln_map (k c n) : (((list.range k).nth n).map (evaln k c)).bind (λ b, b) = evaln k c n := begin by_cases kn : n < k, { simp [list.nth_range kn] }, { rw list.nth_len_le, { cases e : evaln k c n, {refl}, exact kn.elim (evaln_bound e) }, simpa using kn } end theorem evaln_prim : primrec (λ (a : (ℕ × code) × ℕ), evaln a.1.1 a.1.2 a.2) := have primrec₂ (λ (_:unit) (n : ℕ), let a := of_nat (ℕ × code) n in (list.range a.1).map (evaln a.1 a.2)), from primrec.nat_strong_rec _ (hG.comp snd).to₂ $ λ _ p, begin simp [G], rw (_ : (of_nat (ℕ × code) _).snd = of_nat code p.unpair.2), swap, {simp}, apply list.map_congr (λ n, _), rw (by simp : list.range p = list.range (mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))), generalize : p.unpair.1 = k, generalize : of_nat code p.unpair.2 = c, intro nk, cases k with k', {simp [evaln]}, let k := k'+1, change k'.succ with k, simp [nat.lt_succ_iff] at nk, have hg : ∀ {k' c' n}, mkpair k' (encode c') < mkpair k (encode c) → lup ((list.range (mkpair k (encode c))).map (λ n, (list.range n.unpair.1).map (evaln n.unpair.1 (of_nat code n.unpair.2)))) (k', c') n = evaln k' c' n, { intros k₁ c₁ n₁ hl, simp [lup, list.nth_range hl, evaln_map, (>>=)] }, cases c with cf cg cf cg cf cg cf; simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure], { cases encode_lt_pair cf cg with lf lg, rw [hg (nat.mkpair_lt_mkpair_right _ lf), hg (nat.mkpair_lt_mkpair_right _ lg)], cases evaln k cf n, {refl}, cases evaln k cg n; refl }, { cases encode_lt_comp cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lg), cases evaln k cg n, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lf)] }, { cases encode_lt_prec cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases n.unpair.2, {refl}, simp, rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self), cases evaln k' _ _, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lg)] }, { have lf := encode_lt_rfind' cf, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases evaln k cf n with x, {refl}, simp, cases x; simp [nat.succ_ne_zero], rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) } end, (option_bind (list_nth.comp (this.comp (const ()) (encode_iff.2 fst)) snd) snd.to₂).of_eq $ λ ⟨⟨k, c⟩, n⟩, by simp [evaln_map] end section open partrec computable theorem eval_eq_rfind_opt (c n) : eval c n = nat.rfind_opt (λ k, evaln k c n) := part.ext $ λ x, begin refine evaln_complete.trans (nat.rfind_opt_mono _).symm, intros a m n hl, apply evaln_mono hl, end theorem eval_part : partrec₂ eval := (rfind_opt (evaln_prim.to_comp.comp ((snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq $ λ a, by simp [eval_eq_rfind_opt] theorem fixed_point {f : code → code} (hf : computable f) : ∃ c : code, eval (f c) = eval c := let g (x y : ℕ) : part ℕ := eval (of_nat code x) x >>= λ b, eval (of_nat code b) y in have partrec₂ g := (eval_part.comp ((computable.of_nat _).comp fst) fst).bind (eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).to₂, let ⟨cg, eg⟩ := exists_code.1 this in have eg' : ∀ a n, eval cg (mkpair a n) = part.map encode (g a n) := by simp [eg], let F (x : ℕ) : code := f (curry cg x) in have computable F := hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp, let ⟨cF, eF⟩ := exists_code.1 this in have eF' : eval cF (encode cF) = part.some (encode (F (encode cF))), by simp [eF], ⟨curry cg (encode cF), funext (λ n, show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n, by simp [eg', eF', part.map_id', g])⟩ theorem fixed_point₂ {f : code → ℕ →. ℕ} (hf : partrec₂ f) : ∃ c : code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf in (fixed_point (curry_prim.comp (primrec.const cf) primrec.encode).to_comp).imp $ λ c e, funext $ λ n, by simp [e.symm, ef, part.map_id'] end end nat.partrec.code
d02fbdfed7f61cda92498eafd973409dd7dbd671
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/algebra/monoid.lean
cc0e1c518b7e307e4f77f1b51959fdb3937bdbe4
[ "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
16,078
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.continuous_on import group_theory.submonoid.operations import algebra.group.prod import algebra.pointwise import algebra.big_operators.finprod /-! # Theory of topological monoids In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many applications the underlying type is a monoid (multiplicative or additive), we do not require this in the definitions. -/ open classical set filter topological_space open_locale classical topological_space big_operators variables {ι α X M N : Type*} [topological_space X] @[to_additive] lemma continuous_one [topological_space M] [has_one M] : continuous (1 : X → M) := @continuous_const _ _ _ _ 1 /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `M`, for example, is obtained by requiring both the instances `add_monoid M` and `has_continuous_add M`. -/ class has_continuous_add (M : Type*) [topological_space M] [has_add M] : Prop := (continuous_add : continuous (λ p : M × M, p.1 + p.2)) /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `M`, for example, is obtained by requiring both the instances `monoid M` and `has_continuous_mul M`. -/ @[to_additive] class has_continuous_mul (M : Type*) [topological_space M] [has_mul M] : Prop := (continuous_mul : continuous (λ p : M × M, p.1 * p.2)) section has_continuous_mul variables [topological_space M] [has_mul M] [has_continuous_mul M] @[to_additive] lemma continuous_mul : continuous (λp:M×M, p.1 * p.2) := has_continuous_mul.continuous_mul @[continuity, to_additive] lemma continuous.mul {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg : _) -- should `to_additive` be doing this? attribute [continuity] continuous.add @[to_additive] lemma continuous_mul_left (a : M) : continuous (λ b:M, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : M) : continuous (λ b:M, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul {f g : X → M} {s : set X} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) @[to_additive] lemma tendsto_mul {a b : M} : tendsto (λp:M×M, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b) @[to_additive] lemma filter.tendsto.mul {f g : α → M} {x : filter α} {a b : M} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto_mul.comp (hf.prod_mk_nhds hg) @[to_additive] lemma filter.tendsto.const_mul (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), b * f k) l (𝓝 (b * c)) := tendsto_const_nhds.mul h @[to_additive] lemma filter.tendsto.mul_const (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), f k * b) l (𝓝 (c * b)) := h.mul tendsto_const_nhds @[to_additive] lemma continuous_at.mul {f g : X → M} {x : X} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x * g x) x := hf.mul hg @[to_additive] lemma continuous_within_at.mul {f g : X → M} {s : set X} {x : X} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, f x * g x) s x := hf.mul hg @[to_additive] instance [topological_space N] [has_mul N] [has_continuous_mul N] : has_continuous_mul (M × N) := ⟨((continuous_fst.comp continuous_fst).mul (continuous_fst.comp continuous_snd)).prod_mk ((continuous_snd.comp continuous_fst).mul (continuous_snd.comp continuous_snd))⟩ @[to_additive] instance pi.has_continuous_mul {C : ι → Type*} [∀ i, topological_space (C i)] [∀ i, has_mul (C i)] [∀ i, has_continuous_mul (C i)] : has_continuous_mul (Π i, C i) := { continuous_mul := continuous_pi (λ i, continuous.mul ((continuous_apply i).comp continuous_fst) ((continuous_apply i).comp continuous_snd)) } @[priority 100, to_additive] instance has_continuous_mul_of_discrete_topology [topological_space N] [has_mul N] [discrete_topology N] : has_continuous_mul N := ⟨continuous_of_discrete_topology⟩ open_locale filter open function @[to_additive] lemma has_continuous_mul.of_nhds_one {M : Type*} [monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : has_continuous_mul M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ p : M × M, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : M × M), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, hleft x₀, hright y₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by { rw [key, ← filter.map_map], } ... ≤ map ((λ (x : M), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← hright, hleft y₀, filter.map_map, key₂, ← hleft] end⟩ @[to_additive] lemma has_continuous_mul_of_comm_of_nhds_one (M : Type*) [comm_monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : has_continuous_mul M := begin apply has_continuous_mul.of_nhds_one hmul hleft, intros x₀, simp_rw [mul_comm, hleft x₀] end end has_continuous_mul section has_continuous_mul variables [topological_space M] [monoid M] [has_continuous_mul M] @[to_additive] lemma submonoid.top_closure_mul_self_subset (s : submonoid M) : (closure (s : set M)) * closure (s : set M) ⊆ closure (s : set M) := calc (closure (s : set M)) * closure (s : set M) = (λ p : M × M, p.1 * p.2) '' (closure ((s : set M).prod s)) : by simp [closure_prod_eq] ... ⊆ closure ((λ p : M × M, p.1 * p.2) '' ((s : set M).prod s)) : image_closure_subset_closure_image continuous_mul ... = closure s : by simp [s.coe_mul_self_eq] @[to_additive] lemma submonoid.top_closure_mul_self_eq (s : submonoid M) : (closure (s : set M)) * closure (s : set M) = closure (s : set M) := subset.antisymm s.top_closure_mul_self_subset (λ x hx, ⟨x, 1, hx, subset_closure s.one_mem, mul_one _⟩) /-- The (topological-space) closure of a submonoid of a space `M` with `has_continuous_mul` is itself a submonoid. -/ @[to_additive "The (topological-space) closure of an additive submonoid of a space `M` with `has_continuous_add` is itself an additive submonoid."] def submonoid.topological_closure (s : submonoid M) : submonoid M := { carrier := closure (s : set M), one_mem' := subset_closure s.one_mem, mul_mem' := λ a b ha hb, s.top_closure_mul_self_subset ⟨a, b, ha, hb, rfl⟩ } @[to_additive] instance submonoid.topological_closure_has_continuous_mul (s : submonoid M) : has_continuous_mul (s.topological_closure) := { continuous_mul := begin apply continuous_induced_rng, change continuous (λ p : s.topological_closure × s.topological_closure, (p.1 : M) * (p.2 : M)), continuity, end } lemma submonoid.submonoid_topological_closure (s : submonoid M) : s ≤ s.topological_closure := subset_closure lemma submonoid.is_closed_topological_closure (s : submonoid M) : is_closed (s.topological_closure : set M) := by convert is_closed_closure lemma submonoid.topological_closure_minimal (s : submonoid M) {t : submonoid M} (h : s ≤ t) (ht : is_closed (t : set M)) : s.topological_closure ≤ t := closure_minimal h ht @[to_additive exists_open_nhds_zero_half] lemma exists_open_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ ∀ (v ∈ V) (w ∈ V), v * w ∈ s := have ((λa:M×M, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : M × M), from tendsto_mul (by simpa only [one_mul] using hs), by simpa only [prod_subset_iff] using exists_nhds_square this @[to_additive exists_nhds_zero_half] lemma exists_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ (v ∈ V) (w ∈ V), v * w ∈ s := let ⟨V, Vo, V1, hV⟩ := exists_open_nhds_one_split hs in ⟨V, is_open.mem_nhds Vo V1, hV⟩ @[to_additive exists_nhds_zero_quarter] lemma exists_nhds_one_split4 {u : set M} (hu : u ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_one_split hu with ⟨W, W1, h⟩, rcases exists_nhds_one_split W1 with ⟨V, V1, h'⟩, use [V, V1], intros v w s t v_in w_in s_in t_in, simpa only [mul_assoc] using h _ (h' v v_in w w_in) _ (h' s s_in t t_in) end /-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma exists_open_nhds_one_mul_subset {U : set M} (hU : U ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ V * V ⊆ U := begin rcases exists_open_nhds_one_split hU with ⟨V, Vo, V1, hV⟩, use [V, Vo, V1], rintros _ ⟨x, y, hx, hy, rfl⟩, exact hV _ hx _ hy end @[to_additive] lemma tendsto_list_prod {f : ι → α → M} {x : filter α} {a : ι → M} : ∀ l:list ι, (∀i∈l, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp only [list.map_cons, list.prod_cons], exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod {f : ι → X → M} (l : list ι) (h : ∀i∈l, continuous (f i)) : continuous (λa, (l.map (λi, f i a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x -- @[to_additive continuous_smul] @[continuity] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : M, a ^ n) | 0 := by simpa using continuous_const | (k+1) := by { simp only [pow_succ], exact continuous_id.mul (continuous_pow _) } @[continuity] lemma continuous.pow {f : X → M} (h : continuous f) (n : ℕ) : continuous (λ b, (f b) ^ n) := (continuous_pow n).comp h lemma continuous_on_pow {s : set M} (n : ℕ) : continuous_on (λ x, x ^ n) s := (continuous_pow n).continuous_on end has_continuous_mul section op open opposite /-- Put the same topological space structure on the opposite monoid as on the original space. -/ instance [_i : topological_space α] : topological_space αᵒᵖ := topological_space.induced (unop : αᵒᵖ → α) _i variables [topological_space α] lemma continuous_unop : continuous (unop : αᵒᵖ → α) := continuous_induced_dom lemma continuous_op : continuous (op : α → αᵒᵖ) := continuous_induced_rng continuous_id variables [monoid α] [has_continuous_mul α] /-- If multiplication is continuous in the monoid `α`, then it also is in the monoid `αᵒᵖ`. -/ instance : has_continuous_mul αᵒᵖ := ⟨ let h₁ := @continuous_mul α _ _ _ in let h₂ : continuous (λ p : α × α, _) := continuous_snd.prod_mk continuous_fst in continuous_induced_rng $ (h₁.comp h₂).comp (continuous_unop.prod_map continuous_unop) ⟩ end op namespace units open opposite variables [topological_space α] [monoid α] /-- The units of a monoid are equipped with a topology, via the embedding into `α × α`. -/ instance : topological_space (units α) := topological_space.induced (embed_product α) (by apply_instance) lemma continuous_embed_product : continuous (embed_product α) := continuous_induced_dom lemma continuous_coe : continuous (coe : units α → α) := by convert continuous_fst.comp continuous_induced_dom variables [has_continuous_mul α] /-- If multiplication on a monoid is continuous, then multiplication on the units of the monoid, with respect to the induced topology, is continuous. Inversion is also continuous, but we register this in a later file, `topology.algebra.group`, because the predicate `has_continuous_inv` has not yet been defined. -/ instance : has_continuous_mul (units α) := ⟨ let h := @continuous_mul (α × αᵒᵖ) _ _ _ in continuous_induced_rng $ h.comp $ continuous_embed_product.prod_map continuous_embed_product ⟩ end units section variables [topological_space M] [comm_monoid M] @[to_additive] lemma submonoid.mem_nhds_one (S : submonoid M) (oS : is_open (S : set M)) : (S : set M) ∈ 𝓝 (1 : M) := is_open.mem_nhds oS S.one_mem variable [has_continuous_mul M] @[to_additive] lemma tendsto_multiset_prod {f : ι → α → M} {x : filter α} {a : ι → M} (s : multiset ι) : (∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simpa using tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : ι → α → M} {x : filter α} {a : ι → M} (s : finset ι) : (∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := tendsto_multiset_prod _ @[to_additive, continuity] lemma continuous_multiset_prod {f : ι → X → M} (s : multiset ι) : (∀i ∈ s, continuous (f i)) → continuous (λ a, (s.map (λ i, f i a)).prod) := by { rcases s with ⟨l⟩, simpa using continuous_list_prod l } attribute [continuity] continuous_multiset_sum @[continuity, to_additive] lemma continuous_finset_prod {f : ι → X → M} (s : finset ι) : (∀ i ∈ s, continuous (f i)) → continuous (λa, ∏ i in s, f i a) := continuous_multiset_prod _ -- should `to_additive` be doing this? attribute [continuity] continuous_finset_sum open function @[to_additive] lemma continuous_finprod {f : ι → X → M} (hc : ∀ i, continuous (f i)) (hf : locally_finite (λ i, mul_support (f i))) : continuous (λ x, ∏ᶠ i, f i x) := begin refine continuous_iff_continuous_at.2 (λ x, _), rcases hf x with ⟨U, hxU, hUf⟩, have : continuous_at (λ x, ∏ i in hUf.to_finset, f i x) x, from tendsto_finset_prod _ (λ i hi, (hc i).continuous_at), refine this.congr (mem_sets_of_superset hxU $ λ y hy, _), refine (finprod_eq_prod_of_mul_support_subset _ (λ i hi, _)).symm, rw [hUf.coe_to_finset], exact ⟨y, hi, hy⟩ end @[to_additive] lemma continuous_finprod_cond {f : ι → X → M} {p : ι → Prop} (hc : ∀ i, p i → continuous (f i)) (hf : locally_finite (λ i, mul_support (f i))) : continuous (λ x, ∏ᶠ i (hi : p i), f i x) := begin simp only [← finprod_subtype_eq_finprod_cond], exact continuous_finprod (λ i, hc i i.2) (hf.comp_injective subtype.coe_injective) end end instance additive.has_continuous_add {M} [h : topological_space M] [has_mul M] [has_continuous_mul M] : @has_continuous_add (additive M) h _ := { continuous_add := @continuous_mul M _ _ _ } instance multiplicative.has_continuous_mul {M} [h : topological_space M] [has_add M] [has_continuous_add M] : @has_continuous_mul (multiplicative M) h _ := { continuous_mul := @continuous_add M _ _ _ }
58a01c2d640925fe5f8763bee4d18ff7db267fc3
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/algebra_tower.lean
41686bb7dd95cd46c6a51801c199ecdad814882f
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
14,082
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.invertible import ring_theory.adjoin.fg import linear_algebra.basis import algebra.algebra.tower import algebra.algebra.restrict_scalars /-! # Towers of algebras We set up the basic theory of algebra towers. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. In `field_theory/tower.lean` we use this to prove the tower law for finite extensions, that if `R` and `S` are both fields, then `[A:R] = [A:S] [S:A]`. In this file we prepare the main lemma: if `{bi | i ∈ I}` is an `R`-basis of `S` and `{cj | j ∈ J}` is a `S`-basis of `A`, then `{bi cj | i ∈ I, j ∈ J}` is an `R`-basis of `A`. This statement does not require the base rings to be a field, so we also generalize the lemma to rings in this file. -/ open_locale pointwise universes u v w u₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) namespace is_scalar_tower section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R S A B) /-- Suppose that `R -> S -> A` is a tower of algebras. If an element `r : R` is invertible in `S`, then it is invertible in `A`. -/ def invertible.algebra_tower (r : R) [invertible (algebra_map R S r)] : invertible (algebra_map R A r) := invertible.copy (invertible.map (algebra_map S A : S →* A) (algebra_map R S r)) (algebra_map R A r) (by rw [ring_hom.coe_monoid_hom, is_scalar_tower.algebra_map_apply R S A]) /-- A natural number that is invertible when coerced to `R` is also invertible when coerced to any `R`-algebra. -/ def invertible_algebra_coe_nat (n : ℕ) [inv : invertible (n : R)] : invertible (n : A) := by { haveI : invertible (algebra_map ℕ R n) := inv, exact invertible.algebra_tower ℕ R A n } end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] end comm_semiring end is_scalar_tower namespace algebra theorem adjoin_algebra_map' {R : Type u} {S : Type v} {A : Type w} [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] (s : set S) : adjoin R (algebra_map S (restrict_scalars R S A) '' s) = (adjoin R s).map ((algebra.of_id S (restrict_scalars R S A)).restrict_scalars R) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) theorem adjoin_algebra_map (R : Type u) (S : Type v) (A : Type w) [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (s : set S) : adjoin R (algebra_map S A '' s) = subalgebra.map (adjoin R s) (is_scalar_tower.to_alg_hom R S A) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) lemma adjoin_restrict_scalars (C D E : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E] [algebra C D] [algebra C E] [algebra D E] [is_scalar_tower C D E] (S : set E) : (algebra.adjoin D S).restrict_scalars C = (algebra.adjoin ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) S).restrict_scalars C := begin suffices : set.range (algebra_map D E) = set.range (algebra_map ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) E), { ext x, change x ∈ subsemiring.closure (_ ∪ S) ↔ x ∈ subsemiring.closure (_ ∪ S), rw this }, ext x, split, { rintros ⟨y, hy⟩, exact ⟨⟨algebra_map D E y, ⟨y, ⟨algebra.mem_top, rfl⟩⟩⟩, hy⟩ }, { rintros ⟨⟨y, ⟨z, ⟨h0, h1⟩⟩⟩, h2⟩, exact ⟨z, eq.trans h1 h2⟩ }, end lemma adjoin_res_eq_adjoin_res (C D E F : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E] [comm_semiring F] [algebra C D] [algebra C E] [algebra C F] [algebra D F] [algebra E F] [is_scalar_tower C D F] [is_scalar_tower C E F] {S : set D} {T : set E} (hS : algebra.adjoin C S = ⊤) (hT : algebra.adjoin C T = ⊤) : (algebra.adjoin E (algebra_map D F '' S)).restrict_scalars C = (algebra.adjoin D (algebra_map E F '' T)).restrict_scalars C := by rw [adjoin_restrict_scalars C E, adjoin_restrict_scalars C D, ←hS, ←hT, ←algebra.adjoin_image, ←algebra.adjoin_image, ←alg_hom.coe_to_ring_hom, ←alg_hom.coe_to_ring_hom, is_scalar_tower.coe_to_alg_hom, is_scalar_tower.coe_to_alg_hom, ←adjoin_union_eq_adjoin_adjoin, ←adjoin_union_eq_adjoin_adjoin, set.union_comm] end algebra section open_locale classical lemma algebra.fg_trans' {R S A : Type*} [comm_semiring R] [comm_semiring S] [comm_semiring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (hRS : (⊤ : subalgebra R S).fg) (hSA : (⊤ : subalgebra S A).fg) : (⊤ : subalgebra R A).fg := let ⟨s, hs⟩ := hRS, ⟨t, ht⟩ := hSA in ⟨s.image (algebra_map S A) ∪ t, by rw [finset.coe_union, finset.coe_image, algebra.adjoin_union_eq_adjoin_adjoin, algebra.adjoin_algebra_map, hs, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom, ht, subalgebra.restrict_scalars_top]⟩ end section algebra_map_coeffs variables {R} (A) {ι M : Type*} [comm_semiring R] [semiring A] [add_comm_monoid M] variables [algebra R A] [module A M] [module R M] [is_scalar_tower R A M] variables (b : basis ι R M) (h : function.bijective (algebra_map R A)) /-- If `R` and `A` have a bijective `algebra_map R A` and act identically on `M`, then a basis for `M` as `R`-module is also a basis for `M` as `R'`-module. -/ @[simps] noncomputable def basis.algebra_map_coeffs : basis ι A M := b.map_coeffs (ring_equiv.of_bijective _ h) (λ c x, by simp) lemma basis.algebra_map_coeffs_apply (i : ι) : b.algebra_map_coeffs A h i = b i := b.map_coeffs_apply _ _ _ @[simp] lemma basis.coe_algebra_map_coeffs : (b.algebra_map_coeffs A h : ι → M) = b := b.coe_map_coeffs _ _ end algebra_map_coeffs section semiring open finsupp open_locale big_operators classical universes v₁ w₁ variables {R S A} variables [comm_semiring R] [semiring S] [add_comm_monoid A] variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A] theorem linear_independent_smul {ι : Type v₁} {b : ι → S} {ι' : Type w₁} {c : ι' → A} (hb : linear_independent R b) (hc : linear_independent S c) : linear_independent R (λ p : ι × ι', b p.1 • c p.2) := begin rw linear_independent_iff' at hb hc, rw linear_independent_iff'', rintros s g hg hsg ⟨i, k⟩, by_cases hik : (i, k) ∈ s, { have h1 : ∑ i in (s.image prod.fst).product (s.image prod.snd), g i • b i.1 • c i.2 = 0, { rw ← hsg, exact (finset.sum_subset finset.subset_product $ λ p _ hp, show g p • b p.1 • c p.2 = 0, by rw [hg p hp, zero_smul]).symm }, rw finset.sum_product_right at h1, simp_rw [← smul_assoc, ← finset.sum_smul] at h1, exact hb _ _ (hc _ _ h1 k (finset.mem_image_of_mem _ hik)) i (finset.mem_image_of_mem _ hik) }, exact hg _ hik end /-- `basis.smul (b : basis ι R S) (c : basis ι S A)` is the `R`-basis on `A` where the `(i, j)`th basis vector is `b i • c j`. -/ noncomputable def basis.smul {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) : basis (ι × ι') R A := basis.of_repr ((c.repr.restrict_scalars R) ≪≫ₗ ((finsupp.lcongr (equiv.refl _) b.repr) ≪≫ₗ ((finsupp_prod_lequiv R).symm ≪≫ₗ ((finsupp.lcongr (equiv.prod_comm ι' ι) (linear_equiv.refl _ _)))))) @[simp] theorem basis.smul_repr {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (x ij): (b.smul c).repr x ij = b.repr (c.repr x ij.2) ij.1 := by simp [basis.smul] theorem basis.smul_repr_mk {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (x i j): (b.smul c).repr x (i, j) = b.repr (c.repr x j) i := b.smul_repr c x (i, j) @[simp] theorem basis.smul_apply {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (ij) : (b.smul c) ij = b ij.1 • c ij.2 := begin obtain ⟨i, j⟩ := ij, rw basis.apply_eq_iff, ext ⟨i', j'⟩, rw [basis.smul_repr, linear_equiv.map_smul, basis.repr_self, finsupp.smul_apply, finsupp.single_apply], dsimp only, split_ifs with hi, { simp [hi, finsupp.single_apply] }, { simp [hi] }, end end semiring section ring variables {R S} variables [comm_ring R] [ring S] [algebra R S] lemma basis.algebra_map_injective {ι : Type*} [no_zero_divisors R] [nontrivial S] (b : basis ι R S) : function.injective (algebra_map R S) := have no_zero_smul_divisors R S := b.no_zero_smul_divisors, by exactI no_zero_smul_divisors.algebra_map_injective R S end ring section artin_tate variables (C : Type*) section semiring variables [comm_semiring A] [comm_semiring B] [semiring C] variables [algebra A B] [algebra B C] [algebra A C] [is_scalar_tower A B C] open finset submodule open_locale classical lemma exists_subalgebra_of_fg (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) : ∃ B₀ : subalgebra A B, B₀.fg ∧ (⊤ : submodule B₀ C).fg := begin cases hAC with x hx, cases hBC with y hy, have := hy, simp_rw [eq_top_iff', mem_span_finset] at this, choose f hf, let s : finset B := (finset.product (x ∪ (y * y)) y).image (function.uncurry f), have hsx : ∀ (xi ∈ x) (yj ∈ y), f xi yj ∈ s := λ xi hxi yj hyj, show function.uncurry f (xi, yj) ∈ s, from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_left _ hxi, hyj⟩, have hsy : ∀ (yi yj yk ∈ y), f (yi * yj) yk ∈ s := λ yi hyi yj hyj yk hyk, show function.uncurry f (yi * yj, yk) ∈ s, from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_right _ $ finset.mul_mem_mul hyi hyj, hyk⟩, have hxy : ∀ xi ∈ x, xi ∈ span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) := λ xi hxi, hf xi ▸ sum_mem _ (λ yj hyj, smul_mem (span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C)) ⟨f xi yj, algebra.subset_adjoin $ hsx xi hxi yj hyj⟩ (subset_span $ mem_insert_of_mem hyj)), have hyy : span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) * span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) ≤ span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C), { rw [span_mul_span, span_le, coe_insert], rintros _ ⟨yi, yj, rfl | hyi, rfl | hyj, rfl⟩, { rw mul_one, exact subset_span (set.mem_insert _ _) }, { rw one_mul, exact subset_span (set.mem_insert_of_mem _ hyj) }, { rw mul_one, exact subset_span (set.mem_insert_of_mem _ hyi) }, { rw ← hf (yi * yj), exact set_like.mem_coe.2 (sum_mem _ $ λ yk hyk, smul_mem (span (algebra.adjoin A (↑s : set B)) (insert 1 ↑y : set C)) ⟨f (yi * yj) yk, algebra.subset_adjoin $ hsy yi hyi yj hyj yk hyk⟩ (subset_span $ set.mem_insert_of_mem _ hyk : yk ∈ _)) } }, refine ⟨algebra.adjoin A (↑s : set B), subalgebra.fg_adjoin_finset _, insert 1 y, _⟩, refine restrict_scalars_injective A _ _ _, rw [restrict_scalars_top, eq_top_iff, ← algebra.top_to_submodule, ← hx, algebra.adjoin_eq_span, span_le], refine λ r hr, submonoid.closure_induction hr (λ c hc, hxy c hc) (subset_span $ mem_insert_self _ _) (λ p q hp hq, hyy $ submodule.mul_mem_mul hp hq) end end semiring section ring variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra A B] [algebra B C] [algebra A C] [is_scalar_tower A B C] /-- Artin--Tate lemma: if A ⊆ B ⊆ C is a chain of subrings of commutative rings, and A is noetherian, and C is algebra-finite over A, and C is module-finite over B, then B is algebra-finite over A. References: Atiyah--Macdonald Proposition 7.8; Stacks 00IS; Altman--Kleiman 16.17. -/ theorem fg_of_fg_of_fg [is_noetherian_ring A] (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) (hBCi : function.injective (algebra_map B C)) : (⊤ : subalgebra A B).fg := let ⟨B₀, hAB₀, hB₀C⟩ := exists_subalgebra_of_fg A B C hAC hBC in algebra.fg_trans' (B₀.fg_top.2 hAB₀) $ subalgebra.fg_of_submodule_fg $ have is_noetherian_ring B₀, from is_noetherian_ring_of_fg hAB₀, have is_noetherian B₀ C, by exactI is_noetherian_of_fg_of_noetherian' hB₀C, by exactI fg_of_injective (is_scalar_tower.to_alg_hom B₀ B C).to_linear_map hBCi end ring end artin_tate section alg_hom_tower variables {A} {C D : Type*} [comm_semiring A] [comm_semiring C] [comm_semiring D] [algebra A C] [algebra A D] variables (f : C →ₐ[A] D) (B) [comm_semiring B] [algebra A B] [algebra B C] [is_scalar_tower A B C] /-- Restrict the domain of an `alg_hom`. -/ def alg_hom.restrict_domain : B →ₐ[A] D := f.comp (is_scalar_tower.to_alg_hom A B C) /-- Extend the scalars of an `alg_hom`. -/ def alg_hom.extend_scalars : @alg_hom B C D _ _ _ _ (f.restrict_domain B).to_ring_hom.to_algebra := { commutes' := λ _, rfl .. f } variables {B} /-- `alg_hom`s from the top of a tower are equivalent to a pair of `alg_hom`s. -/ def alg_hom_equiv_sigma : (C →ₐ[A] D) ≃ Σ (f : B →ₐ[A] D), @alg_hom B C D _ _ _ _ f.to_ring_hom.to_algebra := { to_fun := λ f, ⟨f.restrict_domain B, f.extend_scalars B⟩, inv_fun := λ fg, let alg := fg.1.to_ring_hom.to_algebra in by exactI fg.2.restrict_scalars A, left_inv := λ f, by { dsimp only, ext, refl }, right_inv := begin rintros ⟨⟨f, _, _, _, _, _⟩, g, _, _, _, _, hg⟩, have : f = λ x, g (algebra_map B C x) := by { ext, exact (hg x).symm }, subst this, refl, end } end alg_hom_tower
7f438be354222454db6b6423ea6793dfa193257c
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/formal/cylinder/sdr.lean
20bdb60346a3b041e454a9440e8c03e3a10c5505
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
2,065
lean
import .homotopy universes v u open category_theory open category_theory.category local notation f ` ∘ `:80 g:80 := g ≫ f namespace homotopy_theory.cylinder variables {C : Type u} [category.{v} C] [has_cylinder C] -- A map j : A → X is the inclusion of a strong deformation retract if -- it admits a retraction r : X → A for which j ∘ r is homotopic to -- the identity rel j. structure sdr_inclusion {a x : C} (j : a ⟶ x) := (r : x ⟶ a) (h : r ∘ j = 𝟙 a) (H : j ∘ r ≃ 𝟙 x rel j) def is_sdr_inclusion {a x : C} (j : a ⟶ x) : Prop := nonempty (sdr_inclusion j) lemma pushout_of_sdr_inclusion {a x a' x' : C} {j : a ⟶ x} {f : a ⟶ a'} {f' : x ⟶ x'} {j' : a' ⟶ x'} (po : Is_pushout j f f' j') (po' : Is_pushout (I &> j) (I &> f) (I &> f') (I &> j')) : is_sdr_inclusion j → is_sdr_inclusion j' := assume ⟨⟨r, h, ⟨H, Hrel⟩⟩⟩, begin refine ⟨⟨po.induced (f ∘ r) (𝟙 a') (by rw [←assoc, h]; simp), by simp, _⟩⟩, -- Now need to give a homotopy from j' ∘ r' (r' = the above induced -- map) to 𝟙 x', rel j'. We define the homotopy using H on I +> x, -- and the constant homotopy at the identity on I +> a'. refine ⟨⟨po'.induced (f' ∘ H.H) (j' ∘ p @> a') _, _, _⟩, _⟩, -- The above maps agree on I +> a, so we can form the induced map: { unfold homotopy.is_rel at Hrel, rw [←assoc, Hrel, p_nat_assoc], have : f' ∘ (j ∘ r ∘ j ∘ p @> a) = (f' ∘ j) ∘ (r ∘ j) ∘ p @> a, by simp, rw [this, po.commutes, h], dsimp, simp }, -- The homotopy defined in this way starts at j' ∘ r' : x' → x': { apply po.uniqueness; rw i_nat_assoc; conv { to_rhs, rw ←assoc }; simp; rw ←assoc, { erw [H.Hi₀, assoc, po.commutes] }, { rw [pi_components], simp } }, -- ... and ends at 𝟙 x': { apply po.uniqueness; rw i_nat_assoc; simp; rw [←assoc], { erw H.Hi₁; simp }, { rw [pi_components], simp } }, -- ... and is rel j: { unfold homotopy.is_rel, simp, congr, rw [←assoc], dsimp, simp } end end homotopy_theory.cylinder
0fef2f7de86905ef48ebfcafd8380685cc7213f7
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/exercises_sources/wednesday/afternoon/topological_spaces.lean
f8ccd205ee878175356003680f3d29471372d785
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
14,934
lean
import tactic import data.set.finite import data.real.basic -- for metrics /- # (Re)-Building topological spaces in Lean Mathlib has a large library of results on topological spaces, including various constructions, separation axioms, Tychonoff's theorem, sheaves, Stone-Čech compactification, Heine-Cantor, to name but a few. See https://leanprover-community.github.io/theories/topology.html which for a (subset) of what's in library. But today we will ignore all that, and build our own version of topological spaces from scratch! (On Friday morning Patrick Massot will lead a session exploring the existing mathlib library in more detail) To get this file run either `leanproject get lftcm2020`, if you didn't already or cd to that folder and run `git pull; leanproject get-mathlib-cache`, this is `src/exercise_sources/wednesday/afternoon/topological_spaces.lean`. The exercises are spread throughout, you needn't do them in order! They are marked as short, medium and long, so I suggest you try some short ones first. First a little setup, we will be making definitions involving the real numbers, the theory of which is not computable, and we'll use sets. -/ noncomputable theory open set /-! ## What is a topological space: There are many definitions: one from Wikipedia: A topological space is an ordered pair (X, τ), where X is a set and τ is a collection of subsets of X, satisfying the following axioms: - The empty set and X itself belong to τ. - Any arbitrary (finite or infinite) union of members of τ still belongs to τ. - The intersection of any finite number of members of τ still belongs to τ. We can formalize this as follows: -/ class topological_space_wiki := (X : Type) -- the underlying Type that the topology will be on (τ : set (set X)) -- the set of open subsets of X (empty_mem : ∅ ∈ τ) -- empty set is open (univ_mem : univ ∈ τ) -- whole space is open (union : ∀ B ⊆ τ, ⋃₀ B ∈ τ) -- arbitrary unions (sUnions) of members of τ are open (inter : ∀ (B ⊆ τ) (h : finite B), ⋂₀ B ∈ τ) -- finite intersections of -- members of τ are open /- Before we go on we should be sure we want to use this as our definition. -/ @[ext] class topological_space (X : Type) := (is_open : set X → Prop) -- why set X → Prop not set (set X)? former plays -- nicer with typeclasses later (empty_mem : is_open ∅) (univ_mem : is_open univ) (union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B)) (inter : ∀ (A B : set X) (hA : is_open A) (hB : is_open B), is_open (A ∩ B)) namespace topological_space /- We can now work with topological spaces like this. -/ example (X : Type) [topological_space X] (U V W : set X) (hU : is_open U) (hV : is_open V) (hW : is_open W) : is_open (U ∩ V ∩ W) := begin apply inter _ _ _ hW, exact inter _ _ hU hV, end /- ## Exercise 0 [short]: One of the axioms of a topological space we have here is unnecessary, it follows from the others. If we remove it we'll have less work to do each time we want to create a new topological space so: 1. Identify and remove the unneeded axiom, make sure to remove it throughout the file. 2. Add the axiom back as a lemma with the same name and prove it based on the others, so that the _interface_ is the same. -/ /- Defining a basic topology now works like so: -/ def discrete (X : Type) : topological_space X := { is_open := λ U, true, -- everything is open empty_mem := trivial, univ_mem := trivial, union := begin intros B h, trivial, end, inter := begin intros A hA B hB, trivial, end } /- ## Exercise 1 [medium]: One way me might want to create topological spaces in practice is to take the coarsest possible topological space containing a given set of is_open. To define this we might say we want to define what `is_open` is given the set of generators. So we want to define the predicate `is_open` by declaring that each generator will be open, the intersection of two opens will be open, and each union of a set of opens will be open, and finally the empty and whole space (`univ`) must be open. The cleanest way to do this is as an inductive definition. The exercise is to make this definition of the topological space generated by a given set in Lean. ### Hint: As a hint for this exercise take a look at the following definition of a constructible set of a topological space, defined by saying that an intersection of an open and a closed set is constructible and that the union of any pair of constructible sets is constructible. (Bonus exercise: mathlib doesn't have any theory of constructible sets, make one and PR it! [arbitrarily long!], or just prove that open and closed sets are constructible for now) -/ inductive is_constructible {X : Type} (T : topological_space X) : set X → Prop /- Given two open sets in `T`, the intersection of one with the complement of the other open is locally closed, hence constructible: -/ | locally_closed : ∀ (A B : set X), is_open A → is_open B → is_constructible (A ∩ Bᶜ) -- Given two constructible sets their union is constructible: | union : ∀ A B, is_constructible A → is_constructible B → is_constructible (A ∪ B) -- For example we can now use this definition to prove the empty set is constructible example {X : Type} (T : topological_space X) : is_constructible T ∅ := begin -- The intersection of the whole space (open) with the empty set (closed) is -- locally closed, hence constructible have := is_constructible.locally_closed univ univ T.univ_mem T.univ_mem, -- but simp knows that's just the empty set (`simp` uses `this` automatically) simpa, end /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generated_open (X : Type) (g : set (set X)) : set X → Prop -- The exercise: Add a definition here defining which sets are generated by `g` like the -- `is_constructible` definition above. /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (X : Type) (g : set (set X)) : topological_space X := { is_open := generated_open X g, empty_mem := sorry, univ_mem := sorry, inter := sorry, union := sorry } /- ## Exercise 2 [short]: Define the indiscrete topology on any type using this. (To do it without this it is surprisingly fiddly to prove that the set `{∅, univ}` actually forms a topology) -/ def indiscrete (X : Type) : topological_space X := sorry end topological_space open topological_space /- Now it is quite easy to give a topology on the product of a pair of topological spaces. -/ instance prod.topological_space (X Y : Type) [topological_space X] [topological_space Y] : topological_space (X × Y) := topological_space.generate_from (X × Y) {U | ∃ (Ux : set X) (Uy : set Y) (hx : is_open Ux) (hy : is_open Uy), U = set.prod Ux Uy} -- the proof of this is bit long so I've left it out for the purpose of this file! lemma is_open_prod_iff (X Y : Type) [topological_space X] [topological_space Y] {s : set (X × Y)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := sorry /- # Metric spaces -/ open_locale big_operators class metric_space_basic (X : Type) := (dist : X → X → ℝ) (dist_eq_zero_iff : ∀ x y, dist x y = 0 ↔ x = y) (dist_symm : ∀ x y, dist x y = dist y x) (triangle : ∀ x y z, dist x z ≤ dist x y + dist y z) namespace metric_space_basic open topological_space /- ## Exercise 3 [short]: We have defined a metric space with a metric landing in ℝ, and made no mention of nonnegativity, (this is in line with the philosophy of using the easiest axioms for our definitions as possible, to make it easier to define individual metrics). Show that we really did define the usual notion of metric space. -/ lemma dist_nonneg {X : Type} [metric_space_basic X] (x y : X) : 0 ≤ dist x y := sorry /- From a metric space we get an induced topological space structure like so: -/ instance {X : Type} [metric_space_basic X] : topological_space X := generate_from X { B | ∃ (x : X) r, B = {y | dist x y < r} } end metric_space_basic open metric_space_basic /- So far so good, now lets define the product of two metric spaces: ## Exercise 4 [medium]: Fill in the proofs here. Hint: the computer can do boring casework you would never dream of in real life. `max` is defined as `if x < y then y else x` and the `split_ifs` tactic will break apart if statements. -/ instance prod.metric_space_basic (X Y : Type) [metric_space_basic X] [metric_space_basic Y] : metric_space_basic (X × Y) := { dist := λ u v, max (dist u.fst v.fst) (dist u.snd v.snd), dist_eq_zero_iff := sorry , dist_symm := sorry, triangle := sorry } /- ☡ Let's try to prove a simple lemma involving the product topology: ☡ -/ set_option trace.type_context.is_def_eq false example (X : Type) [metric_space_basic X] : is_open {xy : X × X | dist xy.fst xy.snd < 100 } := begin rw is_open_prod_iff X X, -- this fails, why? Because we have two subtly different topologies on the product -- they are equal but the proof that they are equal is nontrivial and the -- typeclass mechanism can't see that they automatically to apply. We need to change -- our set-up. sorry, end /- Note that lemma works fine when there is only one topology involved. -/ lemma diag_closed (X : Type) [topological_space X] : is_open {xy : X × X | xy.fst ≠ xy.snd } := begin rw is_open_prod_iff X X, sorry, -- Don't try and fill this in: see below! end /- ## Exercise 5 [short]: The previous lemma isn't true! It requires a separation axiom. Define a `class` that posits that the topology on a type `X` satisfies this axiom. Mathlib uses `T_i` naming scheme for these axioms. -/ class t2_space (X : Type) [topological_space X] := (t2 : sorry) /- (Bonus exercises [medium], the world is your oyster: prove the correct version of the above lemma `diag_closed`, prove that the discrete topology is t2, or that any metric topology is t2, ). -/ /- Let's fix the broken example from earlier, by redefining the topology on a metric space. We have unfortunately created two topologies on `X × Y`, one via `prod.topology` that we defined earlier as the product of the two topologies coming from the respective metric space structures. And one coming from the metric on the product. These are equal, i.e. the same topology (otherwise mathematically the product would not be a good definition). However they are not definitionally equal, there is as nontrivial proof to show they are the same. The typeclass system (which finds the relevant topological space instance when we use lemmas involving topological spaces) isn't able to check that topological space structures which are equal for some nontrivial reason are equal on the fly so it gets stuck. We can use `extends` to say that a metric space is an extra structure on top of being a topological space so we are making a choice of topology for each metric space. This may not be *definitionally* equal to the induced topology, but we should add the axiom that the metric and the topology are equal to stop us from creating a metric inducing a different topology to the topological structure we chose. -/ class metric_space (X : Type) extends topological_space X, metric_space_basic X := (compatible : ∀ U, is_open U ↔ generated_open X { B | ∃ (x : X) r, B = {y | dist x y < r}} U) namespace metric_space open topological_space /- This might seem a bit inconvenient to have to define a topological space each time we want a metric space. We would still like a way of making a `metric_space` just given a metric and some properties it satisfies, i.e. a `metric_space_basic`, so we should setup a metric space constructor from a `metric_space_basic` by setting the topology to be the induced one. -/ def of_basic {X : Type} (m : metric_space_basic X) : metric_space X := { compatible := begin intros, refl, /- this should when the above parts are complete -/ end, ..m, ..@metric_space_basic.topological_space X m } /- Now lets define the product of two metric spaces properly -/ instance {X Y : Type} [metric_space X] [metric_space Y] : metric_space (X × Y) := { compatible := begin -- Let's not fill this in for the demo, let me know if you do it! sorry end, ..prod.topological_space X Y, ..prod.metric_space_basic X Y, } /- Now this will work, there is only one topological space on the product, we can rewrite like we tried to before a lemma about topologies our result on metric spaces, as there is only one topology here. ## Exercise 6 [long?]: Complete the proof of the example (you can generalise the 100 too if it makes it feel less silly). -/ example (X : Type) [metric_space X] : is_open {xy : X × X | dist xy.fst xy.snd < 100 } := begin rw is_open_prod_iff X X, sorry end end metric_space namespace topological_space /- As mentioned, there are many definitions of a topological space, for instance one can define them via specifying a set of closed sets satisfying various axioms, this is equivalent and sometimes more convenient. We _could_ create two distinct Types defined by different data and provide an equivalence between theses types, e.g. `topological_space_via_open_sets` and `topological_space_via_closed_sets`, but this would quickly get unwieldy. What's better is to make an alternative _constructor_ for our original topological space. This is a function takes a set of subsets satisfying the axioms to be the closed sets of a topological space and creates the topological space defined by the corresponding set of open sets. ## Exercise 7 [medium]: Complete the following constructor of a topological space from a set of subsets of a given type `X` satisfying the axioms for the closed sets of a topology. Hint: there are many useful lemmas about complements in mathlib, with names involving `compl`, like `compl_empty`, `compl_univ`, `compl_compl`, `compl_sUnion`, `mem_compl_image`, `compl_inter`, `compl_compl'`, `you can #check them to see what they say. -/ def mk_closed_sets (X : Type) (σ : set (set X)) (empty_mem : ∅ ∈ σ) (univ_mem : univ ∈ σ) (inter : ∀ B ⊆ σ, ⋂₀ B ∈ σ) (union : ∀ (A ∈ σ) (B ∈ σ), A ∪ B ∈ σ) : topological_space X := { is_open := λ U, U ∈ compl '' σ, -- the corresponding `is_open` empty_mem := sorry , univ_mem := sorry , union := sorry , inter := sorry } /- Here are some more exercises: ## Exercise 8 [medium/long]: Define the cofinite topology on any type (PR it to mathlib?). ## Exercise 9 [medium/long]: Define a normed space? ## Exercise 10 [medium/long]: Define more separation axioms? -/ end topological_space
10776bcda1942053e524e51b682f24d776eb9675
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Lean/Meta/Tactic/Assert.lean
7ae0f44e903405a4563fb8eded2d39b7a460aca9
[ "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
4,045
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.Tactic.Util import Lean.Meta.Tactic.FVarSubst import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Revert namespace Lean.Meta /-- Convert the given goal `Ctx |- target` into `Ctx |- type -> target`. It assumes `val` has type `type` -/ def assert (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `assert let tag ← getMVarTag mvarId let target ← getMVarType mvarId let newType := Lean.mkForall name BinderInfo.default type target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag assignExprMVar mvarId (mkApp newMVar val) pure newMVar.mvarId! /-- Convert the given goal `Ctx |- target` into `Ctx |- let name : type := val; target`. It assumes `val` has type `type` -/ def define (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := do withMVarContext mvarId do checkNotAssigned mvarId `define let tag ← getMVarTag mvarId let target ← getMVarType mvarId let newType := Lean.mkLet name type val target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag assignExprMVar mvarId newMVar pure newMVar.mvarId! /-- Convert the given goal `Ctx |- target` into `Ctx |- (hName : type) -> hName = val -> target`. It assumes `val` has type `type` -/ def assertExt (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) (hName : Name := `h) : MetaM MVarId := do withMVarContext mvarId do checkNotAssigned mvarId `assert let tag ← getMVarTag mvarId let target ← getMVarType mvarId let u ← getLevel type let hType := mkApp3 (mkConst `Eq [u]) type (mkBVar 0) val let newType := Lean.mkForall name BinderInfo.default type $ Lean.mkForall hName BinderInfo.default hType target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let rflPrf ← mkEqRefl val assignExprMVar mvarId (mkApp2 newMVar val rflPrf) pure newMVar.mvarId! structure AssertAfterResult where fvarId : FVarId mvarId : MVarId subst : FVarSubst /-- Convert the given goal `Ctx |- target` into a goal containing `(userName : type)` after the local declaration with if `fvarId`. It assumes `val` has type `type`, and that `type` is well-formed after `fvarId`. Note that `val` does not need to be well-formed after `fvarId`. That is, it may contain variables that are defined after `fvarId`. -/ def assertAfter (mvarId : MVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : MetaM AssertAfterResult := do withMVarContext mvarId do checkNotAssigned mvarId `assertAfter let tag ← getMVarTag mvarId let target ← getMVarType mvarId let localDecl ← getLocalDecl fvarId let lctx ← getLCtx let localInsts ← getLocalInstances let fvarIds := lctx.foldl (init := #[]) (start := localDecl.index+1) fun fvarIds decl => fvarIds.push decl.fvarId let xs := fvarIds.map mkFVar let targetNew ← mkForallFVars xs target let targetNew := Lean.mkForall userName BinderInfo.default type targetNew let lctxNew := fvarIds.foldl (init := lctx) fun lctxNew fvarId => lctxNew.erase fvarId let localInstsNew := localInsts.filter fun inst => fvarIds.contains inst.fvar.fvarId! let mvarNew ← mkFreshExprMVarAt lctxNew localInstsNew targetNew MetavarKind.syntheticOpaque tag let args := (fvarIds.filter fun fvarId => !(lctx.get! fvarId).isLet).map mkFVar let args := #[val] ++ args assignExprMVar mvarId (mkAppN mvarNew args) let (fvarIdNew, mvarIdNew) ← intro1P mvarNew.mvarId! let (fvarIdsNew, mvarIdNew) ← introNP mvarIdNew fvarIds.size let subst := fvarIds.size.fold (init := {}) fun i subst => subst.insert fvarIds[i] (mkFVar fvarIdsNew[i]) pure { fvarId := fvarIdNew, mvarId := mvarIdNew, subst := subst } end Lean.Meta
df3c8984d5b859c73049db80d21eff2de9187656
ae9f8bf05de0928a4374adc7d6b36af3411d3400
/src/formal_ml/nat.lean
5cd5cd9e1923a06d6cb713eaa391972cc83a2c29
[ "Apache-2.0" ]
permissive
NeoTim/formal-ml
bc42cf6beba9cd2ed56c1cd054ab4eb5402ed445
c9cbad2837104160a9832a29245471468748bb8d
refs/heads/master
1,671,549,160,900
1,601,362,989,000
1,601,362,989,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,264
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import algebra.ordered_ring import data.nat.basic import formal_ml.core /- In order to understand all of the results about natural numbers, it is helpful to look at the instances for nat that are defined. Specifically, the naturals are: 1. a canonically ordered commutative semiring 2. a decidable linear ordered semiring. -/ lemma lt_antirefl (n:ℕ):(n < n)→ false := begin apply nat.lt_irrefl, end --While this does solve the problem, it is not identical. lemma lt_succ (n:ℕ):(n < nat.succ n) := begin apply nat.le_refl, end lemma lt_succ_of_lt (m n:ℕ):(m < n) → (m < nat.succ n) := begin intros, apply nat.lt_succ_of_le, apply ((@nat.lt_iff_le_not_le m n).mp a).left, end lemma nat_lt_def (n m:ℕ): n < m ↔ (nat.succ n) ≤ m := begin refl, end lemma lt_succ_imp_le (a b:ℕ):a < nat.succ b → a ≤ b := begin intros, rw nat_lt_def at a_1, apply nat.le_of_succ_le_succ, assumption, end lemma nat_fact_pos {n:ℕ}:0 < nat.fact n := begin induction n, { simp, }, { simp, apply n_ih, } end lemma nat_minus_cancel_of_le {k n:ℕ}:k≤ n → (n - k) + k = n := begin rw add_comm, apply nat.add_sub_cancel', end lemma nat_lt_of_add_lt {a b c:ℕ}:a + b < c → b < c := begin induction a, { simp, }, { rw nat.succ_add, intro A1, apply a_ih, apply nat.lt_of_succ_lt, apply A1, } end lemma nat_fact_nonzero {n:ℕ}:nat.fact n ≠ 0 := begin intro A1, have A2:0 < nat.fact n := nat_fact_pos, rw A1 at A2, apply lt_irrefl 0 A2, end lemma nat_lt_sub_of_add_lt {k n n':ℕ}:n + k < n' → n < n' - k := begin revert n', revert n, induction k, { intros n n' A1, rw add_zero at A1, simp, apply A1, }, { intros n n' A1, cases n', { exfalso, apply nat.not_lt_zero, apply A1, }, { rw nat.succ_sub_succ_eq_sub, apply k_ih, rw nat.add_succ at A1, apply nat.lt_of_succ_lt_succ, apply A1, } } end lemma nat_zero_lt_of_nonzero {n:ℕ}:(n≠ 0)→ (0 < n) := begin intro A1, cases n, { exfalso, apply A1, refl, }, { apply nat.zero_lt_succ, } end --In an earlier version, this was solvable via simp. lemma nat_succ_one_add {n:ℕ}:nat.succ n = 1 + n := begin rw add_comm, end lemma nat.le_add {a b:ℕ}:a ≤ a + b := begin simp, end -- mul_left_cancel' is the inspiration here. -- However, it doesn't exist for nat. lemma nat.mul_left_cancel_trichotomy {x : ℕ}:x ≠ 0 → ∀ {y z : ℕ}, (x * y = x * z ↔ y = z) ∧ (x * y < x * z ↔ y < z) := begin induction x, { intros A1 y z, exfalso, apply A1, refl, }, { intros A1 y z, rw nat_succ_one_add, rw right_distrib, rw one_mul, rw right_distrib, rw one_mul, cases x_n, { rw zero_mul, rw zero_mul, rw add_zero, rw add_zero, simp, }, { have B1:nat.succ x_n ≠ 0, { have A2A:0 < nat.succ x_n, { apply nat.zero_lt_succ, }, intro A2B, rw A2B at A2A, apply lt_irrefl 0 A2A, }, have A2 := @x_ih B1 y z, have B2 := @x_ih B1 z y, cases A2 with A3 A4, cases B2 with B3 B4, have A5:y < z ∨ y = z ∨ z < y := lt_trichotomy y z, split;split;intros A6, { cases A5, { exfalso, have A7:y + nat.succ x_n * y < z + nat.succ x_n * z, { apply add_lt_add A5 (A4.mpr A5), }, rw A6 at A7, apply lt_irrefl _ A7, }, cases A5, { exact A5, }, { exfalso, have A7:z + nat.succ x_n * z < y + nat.succ x_n * y, { apply add_lt_add A5 (B4.mpr A5), }, rw A6 at A7, apply lt_irrefl _ A7, }, }, { rw A6, }, { cases A5, { apply A5, }, cases A5, { rw A5 at A6, exfalso, apply lt_irrefl _ A6, }, { exfalso, apply not_lt_of_lt A6, apply add_lt_add A5 (B4.mpr A5), }, }, { apply add_lt_add A6, apply A4.mpr A6, } } } end lemma nat.mul_left_cancel' {x : ℕ}:x ≠ 0 → ∀ {y z : ℕ}, (x * y = x * z → y = z) := begin intros A1 y z A2, apply (@nat.mul_left_cancel_trichotomy x A1 y z).left.mp A2, end lemma nat.mul_eq_zero_iff_eq_zero_or_eq_zero {a b:ℕ}: a * b = 0 ↔ (a = 0 ∨ b = 0) := begin split;intros A1, { have A2:(a=0) ∨ (a ≠ (0:ℕ)) := eq_or_ne, cases A2, { left, apply A2, }, { have A1:a * b = a * 0, { rw mul_zero, apply A1, }, right, apply nat.mul_left_cancel' A2 A1, } }, { cases A1;rw A1, { rw zero_mul, }, { rw mul_zero, } } end lemma double_ne {m n:ℕ}:2 * m ≠ 1 + 2 * n := begin intro A1, have A2:=lt_trichotomy m n, cases A2, { have A3:0 + 2 * m < 1 + 2 * n, { apply add_lt_add, apply zero_lt_one, apply mul_lt_mul_of_pos_left A2 zero_lt_two, }, rw zero_add at A3, rw A1 at A3, apply lt_irrefl _ A3, }, cases A2, { rw A2 at A1, have A3:0 + 2 * n < 1 + 2 * n, { rw add_comm 0 _, rw add_comm 1 _, apply add_lt_add_left, apply zero_lt_one, }, rw zero_add at A3, rw ← A1 at A3, apply lt_irrefl _ A3, }, { have A4:nat.succ n ≤ m, { apply nat.succ_le_of_lt A2, }, have A5 := lt_or_eq_of_le A4, cases A5, { have A6:2 * nat.succ n < 2 * m, { apply mul_lt_mul_of_pos_left A5 zero_lt_two, }, rw nat_succ_one_add at A6, rw left_distrib at A6, rw mul_one at A6, have A7:1 + 2 * n < 2 * m, { apply lt_trans _ A6, apply add_lt_add_right, apply one_lt_two, }, rw A1 at A7, apply lt_irrefl _ A7, }, { subst m, rw nat_succ_one_add at A1, rw left_distrib at A1, rw mul_one at A1, simp at A1, have A2:1 < 2 := one_lt_two, rw A1 at A2, apply lt_irrefl _ A2, } }, end lemma nat.one_le_of_zero_lt {x:ℕ}:0 < x → 1 ≤ x := begin intro A1, apply nat.succ_le_of_lt, apply A1, end lemma nat.succ_le_iff_lt {m n:ℕ}:m.succ ≤ n ↔ m < n := begin apply nat.succ_le_iff, end lemma nat.zero_of_lt_one {x:ℕ}:x < 1 → x = 0 := begin intro A1, have B1 := nat.le_pred_of_lt A1, simp at B1, apply B1, end -------------------------------------- Move these to some pow.lean file, or into mathlib --------------- lemma linear_ordered_semiring.one_le_pow {α:Type*} [linear_ordered_semiring α] {a:α} {b:ℕ}:1 ≤ a → 1≤ a^b := begin induction b, { simp, intro A1, apply le_refl _, }, { rw pow_succ, intro A1, have A2 := b_ih A1, have A3:1 * a^b_n ≤ a * (a^b_n), { apply mul_le_mul_of_nonneg_right, apply A1, apply le_of_lt, apply lt_of_lt_of_le zero_lt_one A2, }, apply le_trans _ A3, simp [A2], }, end lemma linear_ordered_semiring.pow_monotone {α:Type*} [linear_ordered_semiring α] {a:α} {b c:ℕ}:1 ≤ a → b ≤ c → a^b ≤ a^c := begin intros A1 A2, rw le_iff_exists_add at A2, cases A2 with d A2, rw A2, rw pow_add, rw le_mul_iff_one_le_right, apply linear_ordered_semiring.one_le_pow A1, apply lt_of_lt_of_le zero_lt_one, apply linear_ordered_semiring.one_le_pow A1, end
69fffee766ac1d16ea8b4f5310abb585082fbfa3
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Meta/Tactic/Simp/Main.lean
eea0f93279ca3647bedb11394367f29525d85672
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,457
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.Transform import Lean.Meta.Tactic.Replace import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Simp.Types import Lean.Meta.Tactic.Simp.Rewrite namespace Lean.Meta namespace Simp builtin_initialize congrHypothesisExceptionId : InternalExceptionId ← registerInternalExceptionId `congrHypothesisFailed def throwCongrHypothesisFailed : MetaM α := throw <| Exception.internal congrHypothesisExceptionId def Result.getProof (r : Result) : MetaM Expr := do match r.proof? with | some p => return p | none => mkEqRefl r.expr private def mkEqTrans (r₁ r₂ : Result) : MetaM Result := do match r₁.proof? with | none => return r₂ | some p₁ => match r₂.proof? with | none => return { r₂ with proof? := r₁.proof? } | some p₂ => return { r₂ with proof? := (← Meta.mkEqTrans p₁ p₂) } private def mkCongrFun (r : Result) (a : Expr) : MetaM Result := match r.proof? with | none => return { expr := mkApp r.expr a, proof? := none } | some h => return { expr := mkApp r.expr a, proof? := (← Meta.mkCongrFun h a) } private def mkCongr (r₁ r₂ : Result) : MetaM Result := let e := mkApp r₁.expr r₂.expr match r₁.proof?, r₂.proof? with | none, none => return { expr := e, proof? := none } | some h, none => return { expr := e, proof? := (← Meta.mkCongrFun h r₂.expr) } | none, some h => return { expr := e, proof? := (← Meta.mkCongrArg r₁.expr h) } | some h₁, some h₂ => return { expr := e, proof? := (← Meta.mkCongr h₁ h₂) } private def mkImpCongr (r₁ r₂ : Result) : MetaM Result := do let e ← mkArrow r₁.expr r₂.expr match r₁.proof?, r₂.proof? with | none, none => return { expr := e, proof? := none } | _, _ => return { expr := e, proof? := (← Meta.mkImpCongr (← r₁.getProof) (← r₂.getProof)) } -- TODO specialize if bootleneck private def reduceProj (e : Expr) : MetaM Expr := do match (← reduceProj? e) with | some e => return e | _ => return e private def reduceProjFn? (e : Expr) : SimpM (Option Expr) := do matchConst e.getAppFn (fun _ => pure none) fun cinfo _ => do match (← getProjectionFnInfo? cinfo.name) with | none => return none | some projInfo => if projInfo.fromClass then if (← read).simpLemmas.isDeclToUnfold cinfo.name then -- We only unfold class projections when the user explicitly requested them to be unfolded. -- Recall that `unfoldDefinition?` has support for unfolding this kind of projection. withReducibleAndInstances <| unfoldDefinition? e else return none else -- `structure` projection match (← unfoldDefinition? e) with | none => pure none | some e => match (← reduceProj? e.getAppFn) with | some f => return some (mkAppN f e.getAppArgs) | none => return none private def reduceFVar (cfg : Config) (e : Expr) : MetaM Expr := do if cfg.zeta then match (← getFVarLocalDecl e).value? with | some v => return v | none => return e else return e private def unfold? (e : Expr) : SimpM (Option Expr) := do let f := e.getAppFn if !f.isConst then return none let fName := f.constName! if (← isProjectionFn fName) then return none -- should be reduced by `reduceProjFn?` if (← read).simpLemmas.isDeclToUnfold e.getAppFn.constName! then withDefault <| unfoldDefinition? e else return none private partial def reduce (e : Expr) : SimpM Expr := withIncRecDepth do let cfg := (← read).config if cfg.beta then let e' := e.headBeta if e' != e then return (← reduce e') -- TODO: eta reduction if cfg.proj then match (← reduceProjFn? e) with | some e => return (← reduce e) | none => pure () if cfg.iota then match (← reduceRecMatcher? e) with | some e => return (← reduce e) | none => pure () match (← unfold? e) with | some e => reduce e | none => return e private partial def dsimp (e : Expr) : M Expr := do transform e (post := fun e => return TransformStep.done (← reduce e)) partial def simp (e : Expr) : M Result := withIncRecDepth do let cfg ← getConfig if (← isProof e) then return { expr := e } if cfg.memoize then if let some result := (← get).cache.find? e then return result simpLoop { expr := e } where simpLoop (r : Result) : M Result := do let cfg ← getConfig if (← get).numSteps > cfg.maxSteps then throwError "simp failed, maximum number of steps exceeded" else let init := r.expr modify fun s => { s with numSteps := s.numSteps + 1 } match (← pre r.expr) with | Step.done r => cacheResult cfg r | Step.visit r' => let r ← mkEqTrans r r' let r ← mkEqTrans r (← simpStep r.expr) match (← post r.expr) with | Step.done r' => cacheResult cfg (← mkEqTrans r r') | Step.visit r' => let r ← mkEqTrans r r' if cfg.singlePass || init == r.expr then cacheResult cfg r else simpLoop r simpStep (e : Expr) : M Result := do match e with | Expr.mdata _ e _ => simp e | Expr.proj .. => pure { expr := (← reduceProj e) } | Expr.app .. => simpApp e | Expr.lam .. => simpLambda e | Expr.forallE .. => simpForall e | Expr.letE .. => simpLet e | Expr.const .. => simpConst e | Expr.bvar .. => unreachable! | Expr.sort .. => pure { expr := e } | Expr.lit .. => pure { expr := e } | Expr.mvar .. => pure { expr := (← instantiateMVars e) } | Expr.fvar .. => pure { expr := (← reduceFVar (← getConfig) e) } congrDefault (e : Expr) : M Result := withParent e <| e.withApp fun f args => do let infos := (← getFunInfoNArgs f args.size).paramInfo let mut r ← simp f let mut i := 0 for arg in args do trace[Debug.Meta.Tactic.simp] "app [{i}] {infos.size} {arg} hasFwdDeps: {infos[i].hasFwdDeps}" if i < infos.size && !infos[i].hasFwdDeps then r ← mkCongr r (← simp arg) else if (← whnfD (← inferType r.expr)).isArrow then r ← mkCongr r (← simp arg) else r ← mkCongrFun r (← dsimp arg) i := i + 1 return r /- Return true iff processing the given congruence lemma hypothesis produced a non-refl proof. -/ processCongrHypothesis (h : Expr) : M Bool := do forallTelescopeReducing (← inferType h) fun xs hType => withNewLemmas xs do let lhs ← instantiateMVars hType.appFn!.appArg! let r ← simp lhs let rhs := hType.appArg! rhs.withApp fun m zs => do let val ← mkLambdaFVars zs r.expr unless (← isDefEq m val) do throwCongrHypothesisFailed unless (← isDefEq h (← mkLambdaFVars xs (← r.getProof))) do throwCongrHypothesisFailed return r.proof?.isSome /- Try to rewrite `e` children using the given congruence lemma -/ tryCongrLemma? (c : CongrLemma) (e : Expr) : M (Option Result) := withNewMCtxDepth do trace[Debug.Meta.Tactic.simp.congr] "{c.theoremName}, {e}" let lemma ← mkConstWithFreshMVarLevels c.theoremName let (xs, bis, type) ← forallMetaTelescopeReducing (← inferType lemma) if c.hypothesesPos.any (· ≥ xs.size) then return none let lhs := type.appFn!.appArg! let rhs := type.appArg! if (← isDefEq lhs e) then let mut modified := false for i in c.hypothesesPos do let x := xs[i] try if (← processCongrHypothesis x) then modified := true catch _ => trace[Meta.Tactic.simp.congr] "processCongrHypothesis {c.theoremName} failed {← inferType x}" return none unless modified do trace[Meta.Tactic.simp.congr] "{c.theoremName} not modified" return none unless (← synthesizeArgs c.theoremName xs bis (← read).discharge?) do trace[Meta.Tactic.simp.congr] "{c.theoremName} synthesizeArgs failed" return none let eNew ← instantiateMVars rhs let proof ← instantiateMVars (mkAppN lemma xs) return some { expr := eNew, proof? := proof } else return none congr (e : Expr) : M Result := do let f := e.getAppFn if f.isConst then let congrLemmas ← getCongrLemmas let cs := congrLemmas.get f.constName! for c in cs do match (← tryCongrLemma? c e) with | none => pure () | some r => return r congrDefault e else congrDefault e simpApp (e : Expr) : M Result := do let e ← reduce e if !e.isApp then simp e else congr e simpConst (e : Expr) : M Result := return { expr := (← reduce e) } withNewLemmas {α} (xs : Array Expr) (f : M α) : M α := do if (← getConfig).contextual then let mut s ← getSimpLemmas let mut updated := false for x in xs do if (← isProof x) then s ← s.add #[] x updated := true if updated then withSimpLemmas s f else f else f simpLambda (e : Expr) : M Result := withParent e <| lambdaTelescope e fun xs e => withNewLemmas xs do let r ← simp e let eNew ← mkLambdaFVars xs r.expr match r.proof? with | none => return { expr := eNew } | some h => let p ← xs.foldrM (init := h) fun x h => do mkFunExt (← mkLambdaFVars #[x] h) return { expr := eNew, proof? := p } simpArrow (e : Expr) : M Result := do trace[Debug.Meta.Tactic.simp] "arrow {e}" let p := e.bindingDomain! let q := e.bindingBody! let rp ← simp p trace[Debug.Meta.Tactic.simp] "arrow [{(← getConfig).contextual}] {p} [{← isProp p}] -> {q} [{← isProp q}]" if (← (← getConfig).contextual <&&> isProp p <&&> isProp q) then trace[Debug.Meta.Tactic.simp] "ctx arrow {rp.expr} -> {q}" withLocalDeclD e.bindingName! rp.expr fun h => do let s ← getSimpLemmas let s ← s.add #[] h withSimpLemmas s do let rq ← simp q match rq.proof? with | none => mkImpCongr rp rq | some hq => let hq ← mkLambdaFVars #[h] hq return { expr := (← mkArrow rp.expr rq.expr), proof? := (← mkImpCongrCtx (← rp.getProof) hq) } else mkImpCongr rp (← simp q) simpForall (e : Expr) : M Result := withParent e do trace[Debug.Meta.Tactic.simp] "forall {e}" if e.isArrow then simpArrow e else if (← isProp e) then withLocalDecl e.bindingName! e.bindingInfo! e.bindingDomain! fun x => withNewLemmas #[x] do let b := e.bindingBody!.instantiate1 x let rb ← simp b let eNew ← mkForallFVars #[x] rb.expr match rb.proof? with | none => return { expr := eNew } | some h => return { expr := eNew, proof? := (← mkForallCongr (← mkLambdaFVars #[x] h)) } else return { expr := (← dsimp e) } simpLet (e : Expr) : M Result := do if (← getConfig).zeta then match e with | Expr.letE _ _ v b _ => return { expr := b.instantiate1 v } | _ => unreachable! else -- TODO: simplify nondependent let-decls return { expr := (← dsimp e) } cacheResult (cfg : Config) (r : Result) : M Result := do if cfg.memoize then modify fun s => { s with cache := s.cache.insert e r } return r def main (e : Expr) (ctx : Context) (methods : Methods := {}) : MetaM Result := do withReducible do simp e methods ctx |>.run' {} abbrev Discharge := Expr → SimpM (Option Expr) namespace DefaultMethods mutual partial def discharge? (e : Expr) : SimpM (Option Expr) := do let ctx ← read if ctx.dischargeDepth >= ctx.config.maxDischargeDepth then trace[Meta.Tactic.simp.discharge] "maximum discharge depth has been reached" return none else withReader (fun ctx => { ctx with dischargeDepth := ctx.dischargeDepth + 1 }) do let r ← simp e methods if r.expr.isConstOf ``True then try return some (← mkOfEqTrue (← r.getProof)) catch _ => return none else return none partial def pre (e : Expr) : SimpM Step := preDefault e discharge? partial def post (e : Expr) : SimpM Step := postDefault e discharge? partial def methods : Methods := { pre := pre, post := post, discharge? := discharge? } end end DefaultMethods end Simp def simp (e : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM Simp.Result := do profileitM Exception "simp" (← getOptions) do match discharge? with | none => Simp.main e ctx (methods := Simp.DefaultMethods.methods) | some d => Simp.main e ctx (methods := { pre := (Simp.preDefault . d), post := (Simp.postDefault . d), discharge? := d }) /-- See `simpTarget`. This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/ def simpTargetCore (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option MVarId) := do let target ← instantiateMVars (← getMVarType mvarId) let r ← simp target ctx discharge? if r.expr.isConstOf ``True then match r.proof? with | some proof => assignExprMVar mvarId (← mkOfEqTrue proof) | none => assignExprMVar mvarId (mkConst ``True.intro) return none else match r.proof? with | some proof => replaceTargetEq mvarId r.expr proof | none => if target != r.expr then replaceTargetDefEq mvarId r.expr else return mvarId /-- Simplify the given goal target (aka type). Return `none` if the goal was closed. Return `some mvarId'` otherwise, where `mvarId'` is the simplified new goal. -/ def simpTarget (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option MVarId) := withMVarContext mvarId do checkNotAssigned mvarId `simp simpTargetCore mvarId ctx discharge? /-- Simplify `prop` (which is inhabited by `proof`). Return `none` if the goal was closed. Return `some (proof', prop')` otherwise, where `proof' : prop'` and `prop'` is the simplified `prop`. This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/ def simpStep (mvarId : MVarId) (proof : Expr) (prop : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option (Expr × Expr)) := do let r ← simp prop ctx discharge? if r.expr.isConstOf ``False then match r.proof? with | some eqProof => assignExprMVar mvarId (← mkFalseElim (← getMVarType mvarId) (← mkEqMP eqProof proof)) | none => assignExprMVar mvarId (← mkFalseElim (← getMVarType mvarId) proof) return none else match r.proof? with | some eqProof => return some ((← mkEqMP eqProof proof), r.expr) | none => if r.expr != prop then return some ((← mkExpectedTypeHint proof r.expr), r.expr) else return some (proof, r.expr) def simpLocalDecl (mvarId : MVarId) (fvarId : FVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option (FVarId × MVarId)) := do withMVarContext mvarId do checkNotAssigned mvarId `simp let localDecl ← getLocalDecl fvarId let type ← instantiateMVars localDecl.type match (← simpStep mvarId (mkFVar fvarId) type ctx discharge?) with | none => return none | some (value, type') => if type != type' then let mvarId ← assert mvarId localDecl.userName type' value let mvarId ← tryClear mvarId localDecl.fvarId return some (fvarId, mvarId) else return some (fvarId, mvarId) abbrev FVarIdToLemmaId := NameMap Name def simpGoal (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[]) (fvarIdToLemmaId : FVarIdToLemmaId := {}) : MetaM (Option (Array FVarId × MVarId)) := do withMVarContext mvarId do checkNotAssigned mvarId `simp let mut mvarId := mvarId let mut toAssert : Array Hypothesis := #[] for fvarId in fvarIdsToSimp do let localDecl ← getLocalDecl fvarId let type ← instantiateMVars localDecl.type let ctx ← match fvarIdToLemmaId.find? localDecl.fvarId with | none => pure ctx | some lemmaId => pure { ctx with simpLemmas := (← ctx.simpLemmas.eraseCore lemmaId) } match (← simpStep mvarId (mkFVar fvarId) type ctx discharge?) with | none => return none | some (value, type) => toAssert := toAssert.push { userName := localDecl.userName, type := type, value := value } if simplifyTarget then match (← simpTarget mvarId ctx discharge?) with | none => return none | some mvarIdNew => mvarId := mvarIdNew let (fvarIdsNew, mvarIdNew) ← assertHypotheses mvarId toAssert let mvarIdNew ← tryClearMany mvarIdNew fvarIdsToSimp return (fvarIdsNew, mvarIdNew) end Lean.Meta
e1fc5d4da5bb2b0cad6b07f0d4c109ff97b111f3
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/function.hlean
25c569ca813364462c4f2280691b691a4ffffb15
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
9,368
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about embeddings and surjections -/ import hit.trunc types.equiv cubical.square open equiv sigma sigma.ops eq trunc is_trunc pi is_equiv fiber prod variables {A B : Type} (f : A → B) {b : B} definition is_embedding [class] (f : A → B) := Π(a a' : A), is_equiv (ap f : a = a' → f a = f a') definition is_surjective [class] (f : A → B) := Π(b : B), ∥ fiber f b ∥ definition is_split_surjective [class] (f : A → B) := Π(b : B), fiber f b structure is_retraction [class] (f : A → B) := (sect : B → A) (right_inverse : Π(b : B), f (sect b) = b) structure is_section [class] (f : A → B) := (retr : B → A) (left_inverse : Π(a : A), retr (f a) = a) definition is_weakly_constant [class] (f : A → B) := Π(a a' : A), f a = f a' structure is_constant [class] (f : A → B) := (pt : B) (eq : Π(a : A), f a = pt) structure is_conditionally_constant [class] (f : A → B) := (g : ∥A∥ → B) (eq : Π(a : A), f a = g (tr a)) namespace function abbreviation sect [unfold 4] := @is_retraction.sect abbreviation right_inverse [unfold 4] := @is_retraction.right_inverse abbreviation retr [unfold 4] := @is_section.retr abbreviation left_inverse [unfold 4] := @is_section.left_inverse definition is_equiv_ap_of_embedding [instance] [H : is_embedding f] (a a' : A) : is_equiv (ap f : a = a' → f a = f a') := H a a' definition ap_inv_idp {a : A} {H : is_equiv (ap f : a = a → f a = f a)} : (ap f)⁻¹ᶠ idp = idp :> a = a := !left_inv variable {f} definition is_injective_of_is_embedding [reducible] [H : is_embedding f] {a a' : A} : f a = f a' → a = a' := (ap f)⁻¹ definition is_embedding_of_is_injective [HA : is_set A] [HB : is_set B] (H : Π(a a' : A), f a = f a' → a = a') : is_embedding f := begin intro a a', fapply adjointify, {exact (H a a')}, {intro p, apply is_set.elim}, {intro p, apply is_set.elim} end variable (f) definition is_prop_is_embedding [instance] : is_prop (is_embedding f) := by unfold is_embedding; exact _ definition is_embedding_equiv_is_injective [HA : is_set A] [HB : is_set B] : is_embedding f ≃ (Π(a a' : A), f a = f a' → a = a') := begin fapply equiv.MK, { apply @is_injective_of_is_embedding}, { apply is_embedding_of_is_injective}, { intro H, apply is_prop.elim}, { intro H, apply is_prop.elim, } end definition is_prop_fiber_of_is_embedding [H : is_embedding f] (b : B) : is_prop (fiber f b) := begin apply is_prop.mk, intro v w, induction v with a p, induction w with a' q, induction q, fapply fiber_eq, { esimp, apply is_injective_of_is_embedding p}, { esimp [is_injective_of_is_embedding], symmetry, apply right_inv} end definition is_prop_fun_of_is_embedding [H : is_embedding f] : is_trunc_fun -1 f := is_prop_fiber_of_is_embedding f definition is_embedding_of_is_prop_fun [constructor] [H : is_trunc_fun -1 f] : is_embedding f := begin intro a a', fapply adjointify, { intro p, exact ap point (@is_prop.elim (fiber f (f a')) _ (fiber.mk a p) (fiber.mk a' idp))}, { intro p, rewrite [-ap_compose], esimp, apply ap_con_eq (@point_eq _ _ f (f a'))}, { intro p, induction p, apply ap (ap point), apply is_prop_elim_self} end variable {f} definition is_surjective_rec_on {P : Type} (H : is_surjective f) (b : B) [Pt : is_prop P] (IH : fiber f b → P) : P := trunc.rec_on (H b) IH variable (f) definition is_surjective_of_is_split_surjective [instance] [H : is_split_surjective f] : is_surjective f := λb, tr (H b) definition is_prop_is_surjective [instance] : is_prop (is_surjective f) := by unfold is_surjective; exact _ definition is_weakly_constant_ap [instance] [H : is_weakly_constant f] (a a' : A) : is_weakly_constant (ap f : a = a' → f a = f a') := take p q : a = a', have Π{b c : A} {r : b = c}, (H a b)⁻¹ ⬝ H a c = ap f r, from (λb c r, eq.rec_on r !con.left_inv), this⁻¹ ⬝ this definition is_constant_ap [unfold 4] [instance] [H : is_constant f] (a a' : A) : is_constant (ap f : a = a' → f a = f a') := begin induction H with b q, fapply is_constant.mk, { exact q a ⬝ (q a')⁻¹}, { intro p, induction p, exact !con.right_inv⁻¹} end definition is_contr_is_retraction [instance] [H : is_equiv f] : is_contr (is_retraction f) := begin have H2 : (Σ(g : B → A), Πb, f (g b) = b) ≃ is_retraction f, begin fapply equiv.MK, {intro x, induction x with g p, constructor, exact p}, {intro h, induction h, apply sigma.mk, assumption}, {intro h, induction h, reflexivity}, {intro x, induction x, reflexivity}, end, apply is_trunc_equiv_closed, exact H2, apply is_equiv.is_contr_right_inverse end definition is_contr_is_section [instance] [H : is_equiv f] : is_contr (is_section f) := begin have H2 : (Σ(g : B → A), Πa, g (f a) = a) ≃ is_section f, begin fapply equiv.MK, {intro x, induction x with g p, constructor, exact p}, {intro h, induction h, apply sigma.mk, assumption}, {intro h, induction h, reflexivity}, {intro x, induction x, reflexivity}, end, apply is_trunc_equiv_closed, exact H2, fapply is_trunc_equiv_closed, {apply sigma_equiv_sigma_right, intro g, apply eq_equiv_homotopy}, fapply is_trunc_equiv_closed, {apply fiber.sigma_char}, fapply is_contr_fiber_of_is_equiv, exact to_is_equiv (arrow_equiv_arrow_left_rev A (equiv.mk f H)), end definition is_embedding_of_is_equiv [instance] [H : is_equiv f] : is_embedding f := λa a', _ definition is_equiv_of_is_surjective_of_is_embedding [H : is_embedding f] [H' : is_surjective f] : is_equiv f := @is_equiv_of_is_contr_fun _ _ _ (λb, is_surjective_rec_on H' b (λa, is_contr.mk a (λa', fiber_eq ((ap f)⁻¹ ((point_eq a) ⬝ (point_eq a')⁻¹)) (by rewrite (right_inv (ap f)); rewrite inv_con_cancel_right)))) definition is_split_surjective_of_is_retraction [H : is_retraction f] : is_split_surjective f := λb, fiber.mk (sect f b) (right_inverse f b) definition is_constant_compose_point [constructor] [instance] (b : B) : is_constant (f ∘ point : fiber f b → B) := is_constant.mk b (λv, by induction v with a p;exact p) definition is_embedding_of_is_prop_fiber [H : Π(b : B), is_prop (fiber f b)] : is_embedding f := is_embedding_of_is_prop_fun _ definition is_retraction_of_is_equiv [instance] [H : is_equiv f] : is_retraction f := is_retraction.mk f⁻¹ (right_inv f) definition is_section_of_is_equiv [instance] [H : is_equiv f] : is_section f := is_section.mk f⁻¹ (left_inv f) definition is_equiv_of_is_section_of_is_retraction [H1 : is_retraction f] [H2 : is_section f] : is_equiv f := let g := sect f in let h := retr f in adjointify f g (right_inverse f) (λa, calc g (f a) = h (f (g (f a))) : left_inverse ... = h (f a) : right_inverse f ... = a : left_inverse) section local attribute is_equiv_of_is_section_of_is_retraction [instance] [priority 10000] local attribute trunctype.struct [instance] [priority 1] -- remove after #842 is closed variable (f) definition is_prop_is_retraction_prod_is_section : is_prop (is_retraction f × is_section f) := begin apply is_prop_of_imp_is_contr, intro H, induction H with H1 H2, exact _, end end definition is_retraction_trunc_functor [instance] (r : A → B) [H : is_retraction r] (n : trunc_index) : is_retraction (trunc_functor n r) := is_retraction.mk (trunc_functor n (sect r)) (λb, ((trunc_functor_compose n (sect r) r) b)⁻¹ ⬝ trunc_homotopy n (right_inverse r) b ⬝ trunc_functor_id B n b) -- Lemma 3.11.7 definition is_contr_retract (r : A → B) [H : is_retraction r] : is_contr A → is_contr B := begin intro CA, apply is_contr.mk (r (center A)), intro b, exact ap r (center_eq (is_retraction.sect r b)) ⬝ (is_retraction.right_inverse r b) end local attribute is_prop_is_retraction_prod_is_section [instance] definition is_retraction_prod_is_section_equiv_is_equiv [constructor] : (is_retraction f × is_section f) ≃ is_equiv f := begin apply equiv_of_is_prop, intro H, induction H, apply is_equiv_of_is_section_of_is_retraction, intro H, split, repeat exact _ end definition is_retraction_equiv_is_split_surjective : is_retraction f ≃ is_split_surjective f := begin fapply equiv.MK, { intro H, induction H with g p, intro b, constructor, exact p b}, { intro H, constructor, intro b, exact point_eq (H b)}, { intro H, esimp, apply eq_of_homotopy, intro b, esimp, induction H b, reflexivity}, { intro H, induction H with g p, reflexivity}, end /- The definitions is_surjective_of_is_equiv is_equiv_equiv_is_embedding_times_is_surjective are in types.trunc See types.arrow_2 for retractions -/ end function
20b8eea1e9ba0b1061c1263b58967ebd8c6dde95
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/limits/shapes/constructions/binary_products.lean
20a74ad261f272cc3251657a956109b154b85833
[ "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
1,641
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.binary_products universes v u /-! # Constructing binary product from pullbacks and terminal object. If a category has pullbacks and a terminal object, then it has binary products. TODO: provide the dual result. -/ open category_theory category_theory.category category_theory.limits /-- Any category with pullbacks and terminal object has binary products. -/ -- This is not an instance, as it is not always how one wants to construct binary products! def has_binary_products_of_terminal_and_pullbacks (C : Type u) [𝒞 : category.{v} C] [has_terminal.{v} C] [has_pullbacks.{v} C] : has_binary_products.{v} C := { has_limits_of_shape := { has_limit := λ F, { cone := { X := pullback (terminal.from (F.obj walking_pair.left)) (terminal.from (F.obj walking_pair.right)), π := nat_trans.of_homs (λ x, walking_pair.cases_on x pullback.fst pullback.snd)}, is_limit := { lift := λ c, pullback.lift ((c.π).app walking_pair.left) ((c.π).app walking_pair.right) (subsingleton.elim _ _), fac' := λ s c, walking_pair.cases_on c (limit.lift_π _ _) (limit.lift_π _ _), uniq' := λ s m J, begin rw [←J, ←J], ext; rw limit.lift_π; refl end } } } }
17f94d88228ed5a19e4e667451b88c9601617b89
dc253be9829b840f15d96d986e0c13520b085033
/pointed_pi.hlean
c8d8b8338ca09ea9b6c5e48c768fd3b45c310053
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
50,157
hlean
/- Copyright (c) 2016 Ulrik Buchholtz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ulrik Buchholtz, Floris van Doorn -/ import homotopy.connectedness types.pointed2 .move_to_lib .pointed open eq pointed equiv sigma is_equiv trunc option pi function fiber /- In this file we define dependent pointed maps and properties of them. Using this, we give the truncation level of the type of pointed maps, giving the connectivity of the domain and the truncation level of the codomain. This is is_trunc_pmap_of_is_conn at the end. We also prove other properties about pointed (dependent maps), like the fact that (Π*a, F a) → (Π*a, X a) → (Π*a, B a) is a fibration sequence if (F a) → (X a) → B a) is. -/ namespace pointed /- the pointed type of unpointed (nondependent) maps -/ definition pumap [constructor] (A : Type) (B : Type*) : Type* := pointed.MK (A → B) (const A pt) /- the pointed type of unpointed dependent maps -/ definition pupi [constructor] {A : Type} (B : A → Type*) : Type* := pointed.MK (Πa, B a) (λa, pt) notation `Πᵘ*` binders `, ` r:(scoped P, pupi P) := r infix ` →ᵘ* `:30 := pumap /- stuff about the pointed type of unpointed maps (dependent and non-dependent) -/ definition sigma_pumap {A : Type} (B : A → Type) (C : Type*) : ((Σa, B a) →ᵘ* C) ≃* Πᵘ*a, B a →ᵘ* C := pequiv_of_equiv (equiv_sigma_rec _)⁻¹ᵉ idp definition phomotopy_mk_pupi [constructor] {A : Type*} {B : Type} {C : B → Type*} {f g : A →* (Πᵘ*b, C b)} (p : f ~2 g) (q : p pt ⬝hty apd10 (respect_pt g) ~ apd10 (respect_pt f)) : f ~* g := begin apply phomotopy.mk (λa, eq_of_homotopy (p a)), apply inj !eq_equiv_homotopy, apply eq_of_homotopy, intro b, refine !apd10_con ⬝ _, refine whisker_right _ !apd10_eq_of_homotopy ⬝ q b end definition pupi_functor [constructor] {A A' : Type} {B : A → Type*} {B' : A' → Type*} (f : A' → A) (g : Πa, B (f a) →* B' a) : (Πᵘ*a, B a) →* (Πᵘ*a', B' a') := pmap.mk (pi_functor f g) (eq_of_homotopy (λa, respect_pt (g a))) definition pupi_functor_right [constructor] {A : Type} {B B' : A → Type*} (g : Πa, B a →* B' a) : (Πᵘ*a, B a) →* (Πᵘ*a, B' a) := pupi_functor id g definition pupi_functor_compose {A A' A'' : Type} {B : A → Type*} {B' : A' → Type*} {B'' : A'' → Type*} (f : A'' → A') (f' : A' → A) (g' : Πa, B' (f a) →* B'' a) (g : Πa, B (f' a) →* B' a) : pupi_functor (f' ∘ f) (λa, g' a ∘* g (f a)) ~* pupi_functor f g' ∘* pupi_functor f' g := begin fapply phomotopy_mk_pupi, { intro h a, reflexivity }, { intro a, refine !idp_con ⬝ _, refine !apd10_con ⬝ _ ⬝ !apd10_eq_of_homotopy⁻¹, esimp, refine (!apd10_prepostcompose ⬝ ap02 (g' a) !apd10_eq_of_homotopy) ◾ !apd10_eq_of_homotopy } end definition pupi_functor_pid (A : Type) (B : A → Type*) : pupi_functor id (λa, pid (B a)) ~* pid (Πᵘ*a, B a) := begin fapply phomotopy_mk_pupi, { intro h a, reflexivity }, { intro a, refine !idp_con ⬝ !apd10_eq_of_homotopy⁻¹ } end definition pupi_functor_phomotopy {A A' : Type} {B : A → Type*} {B' : A' → Type*} {f f' : A' → A} {g : Πa, B (f a) →* B' a} {g' : Πa, B (f' a) →* B' a} (p : f ~ f') (q : Πa, g a ~* g' a ∘* ptransport B (p a)) : pupi_functor f g ~* pupi_functor f' g' := begin fapply phomotopy_mk_pupi, { intro h a, exact q a (h (f a)) ⬝ ap (g' a) (apdt h (p a)) }, { intro a, esimp, exact whisker_left _ !apd10_eq_of_homotopy ⬝ !con.assoc ⬝ to_homotopy_pt (q a) ⬝ !apd10_eq_of_homotopy⁻¹ } end definition pupi_pequiv [constructor] {A A' : Type} {B : A → Type*} {B' : A' → Type*} (e : A' ≃ A) (f : Πa, B (e a) ≃* B' a) : (Πᵘ*a, B a) ≃* (Πᵘ*a', B' a') := pequiv.MK (pupi_functor e f) (pupi_functor e⁻¹ᵉ (λa, ptransport B (right_inv e a) ∘* (f (e⁻¹ᵉ a))⁻¹ᵉ*)) abstract begin refine !pupi_functor_compose⁻¹* ⬝* pupi_functor_phomotopy (to_right_inv e) _ ⬝* !pupi_functor_pid, intro a, exact !pinv_pcompose_cancel_right ⬝* !pid_pcompose⁻¹* end end abstract begin refine !pupi_functor_compose⁻¹* ⬝* pupi_functor_phomotopy (to_left_inv e) _ ⬝* !pupi_functor_pid, intro a, refine !passoc⁻¹* ⬝* pinv_right_phomotopy_of_phomotopy _ ⬝* !pid_pcompose⁻¹*, refine pwhisker_left _ _ ⬝* !ptransport_natural, exact ptransport_change_eq _ (adj e a) ⬝* ptransport_ap B e (to_left_inv e a) end end definition pupi_pequiv_right [constructor] {A : Type} {B B' : A → Type*} (f : Πa, B a ≃* B' a) : (Πᵘ*a, B a) ≃* (Πᵘ*a, B' a) := pupi_pequiv erfl f definition loop_pupi [constructor] {A : Type} (B : A → Type*) : Ω (Πᵘ*a, B a) ≃* Πᵘ*a, Ω (B a) := pequiv_of_equiv !eq_equiv_homotopy idp -- definition loop_pupi_natural [constructor] {A : Type} {B B' : A → Type*} (f : Πa, B a →* B' a) : -- psquare (Ω→ (pupi_functor_right f)) (pupi_functor_right (λa, Ω→ (f a))) -- (loop_pupi B) (loop_pupi B') := definition ap1_gen_pi {A A' : Type} {B : A → Type} {B' : A' → Type} {h₀ h₁ : Πa, B a} {h₀' h₁' : Πa', B' a'} (f : A' → A) (g : Πa, B (f a) → B' a) (p₀ : pi_functor f g h₀ ~ h₀') (p₁ : pi_functor f g h₁ ~ h₁') (r : h₀ = h₁) (a' : A') : apd10 (ap1_gen (pi_functor f g) (eq_of_homotopy p₀) (eq_of_homotopy p₁) r) a' = ap1_gen (g a') (p₀ a') (p₁ a') (apd10 r (f a')) := begin induction r, induction p₀ using homotopy.rec_idp, induction p₁ using homotopy.rec_idp, esimp, exact apd10 (ap apd10 !ap1_gen_idp) a', -- exact ap (λx, apd10 (ap1_gen _ x x _) _) !eq_of_homotopy_idp end definition ap1_gen_pi_idp {A A' : Type} {B : A → Type} {B' : A' → Type} {h₀ : Πa, B a} (f : A' → A) (g : Πa, B (f a) → B' a) (a' : A') : ap1_gen_pi f g (homotopy.refl (pi_functor f g h₀)) (homotopy.refl (pi_functor f g h₀)) idp a' = apd10 (ap apd10 !ap1_gen_idp) a' := -- apd10 (ap apd10 (ap1_gen_idp (pi_functor id f) (eq_of_homotopy (λ a, idp)))) a' := -- ap (λp, apd10 p a') (ap1_gen_idp (pi_functor f g) (eq_of_homotopy homotopy.rfl)) := begin esimp [ap1_gen_pi], refine !homotopy_rec_idp_refl ⬝ !homotopy_rec_idp_refl, end -- print homotopy.rec_ -- print apd10_ap_postcompose -- print pi_functor -- print ap1_gen_idp -- print ap1_gen_pi definition loop_pupi_natural [constructor] {A : Type} {B B' : A → Type*} (f : Πa, B a →* B' a) : psquare (Ω→ (pupi_functor_right f)) (pupi_functor_right (λa, Ω→ (f a))) (loop_pupi B) (loop_pupi B') := begin fapply phomotopy_mk_pupi, { intro p a, exact ap1_gen_pi id f (λa, respect_pt (f a)) (λa, respect_pt (f a)) p a }, { intro a, revert B' f, refine fiberwise_pointed_map_rec _ _, intro B' f, refine !ap1_gen_pi_idp ◾ (ap (λx, apd10 x _) !idp_con ⬝ !apd10_eq_of_homotopy) } end definition phomotopy_mk_pumap [constructor] {A C : Type*} {B : Type} {f g : A →* (B →ᵘ* C)} (p : f ~2 g) (q : p pt ⬝hty apd10 (respect_pt g) ~ apd10 (respect_pt f)) : f ~* g := phomotopy_mk_pupi p q definition pumap_functor [constructor] {A A' : Type} {B B' : Type*} (f : A' → A) (g : B →* B') : (A →ᵘ* B) →* (A' →ᵘ* B') := pupi_functor f (λa, g) definition pumap_functor_compose {A A' A'' : Type} {B B' B'' : Type*} (f : A'' → A') (f' : A' → A) (g' : B' →* B'') (g : B →* B') : pumap_functor (f' ∘ f) (g' ∘* g) ~* pumap_functor f g' ∘* pumap_functor f' g := pupi_functor_compose f f' (λa, g') (λa, g) definition pumap_functor_pid (A : Type) (B : Type*) : pumap_functor id (pid B) ~* pid (A →ᵘ* B) := pupi_functor_pid A (λa, B) definition pumap_functor_phomotopy {A A' : Type} {B B' : Type*} {f f' : A' → A} {g g' : B →* B'} (p : f ~ f') (q : g ~* g') : pumap_functor f g ~* pumap_functor f' g' := pupi_functor_phomotopy p (λa, q ⬝* !pcompose_pid⁻¹* ⬝* pwhisker_left _ !ptransport_constant⁻¹*) definition pumap_pequiv [constructor] {A A' : Type} {B B' : Type*} (e : A ≃ A') (f : B ≃* B') : (A →ᵘ* B) ≃* (A' →ᵘ* B') := pupi_pequiv e⁻¹ᵉ (λa, f) definition pumap_pequiv_right [constructor] (A : Type) {B B' : Type*} (f : B ≃* B') : (A →ᵘ* B) ≃* (A →ᵘ* B') := pumap_pequiv erfl f definition pumap_pequiv_left [constructor] {A A' : Type} (B : Type*) (f : A ≃ A') : (A →ᵘ* B) ≃* (A' →ᵘ* B) := pumap_pequiv f pequiv.rfl definition loop_pumap [constructor] (A : Type) (B : Type*) : Ω (A →ᵘ* B) ≃* A →ᵘ* Ω B := loop_pupi (λa, B) /- the pointed sigma type -/ definition psigma_gen [constructor] {A : Type*} (P : A → Type) (x : P pt) : Type* := pointed.MK (Σa, P a) ⟨pt, x⟩ definition psigma_gen_functor [constructor] {A A' : Type*} {B : A → Type} {B' : A' → Type} {b : B pt} {b' : B' pt} (f : A →* A') (g : Πa, B a → B' (f a)) (p : g pt b =[respect_pt f] b') : psigma_gen B b →* psigma_gen B' b' := pmap.mk (sigma_functor f g) (sigma_eq (respect_pt f) p) definition psigma_gen_functor_right [constructor] {A : Type*} {B B' : A → Type} {b : B pt} {b' : B' pt} (f : Πa, B a → B' a) (p : f pt b = b') : psigma_gen B b →* psigma_gen B' b' := proof pmap.mk (sigma_functor id f) (sigma_eq_right p) qed definition psigma_gen_pequiv_psigma_gen [constructor] {A A' : Type*} {B : A → Type} {B' : A' → Type} {b : B pt} {b' : B' pt} (f : A ≃* A') (g : Πa, B a ≃ B' (f a)) (p : g pt b =[respect_pt f] b') : psigma_gen B b ≃* psigma_gen B' b' := pequiv_of_equiv (sigma_equiv_sigma f g) (sigma_eq (respect_pt f) p) definition psigma_gen_pequiv_psigma_gen_left [constructor] {A A' : Type*} {B : A' → Type} {b : B pt} (f : A ≃* A') {b' : B (f pt)} (q : b' =[respect_pt f] b) : psigma_gen (B ∘ f) b' ≃* psigma_gen B b := psigma_gen_pequiv_psigma_gen f (λa, erfl) q definition psigma_gen_pequiv_psigma_gen_right [constructor] {A : Type*} {B B' : A → Type} {b : B pt} {b' : B' pt} (f : Πa, B a ≃ B' a) (p : f pt b = b') : psigma_gen B b ≃* psigma_gen B' b' := psigma_gen_pequiv_psigma_gen pequiv.rfl f (pathover_idp_of_eq p) definition psigma_gen_pequiv_psigma_gen_basepoint [constructor] {A : Type*} {B : A → Type} {b b' : B pt} (p : b = b') : psigma_gen B b ≃* psigma_gen B b' := psigma_gen_pequiv_psigma_gen_right (λa, erfl) p definition loop_psigma_gen [constructor] {A : Type*} (B : A → Type) (b₀ : B pt) : Ω (psigma_gen B b₀) ≃* @psigma_gen (Ω A) (λp, pathover B b₀ p b₀) idpo := pequiv_of_equiv (sigma_eq_equiv pt pt) idp open sigma.ops definition ap1_gen_sigma {A A' : Type} {B : A → Type} {B' : A' → Type} {x₀ x₁ : Σa, B a} {a₀' a₁' : A'} {b₀' : B' a₀'} {b₁' : B' a₁'} (f : A → A') (p₀ : f x₀.1 = a₀') (p₁ : f x₁.1 = a₁') (g : Πa, B a → B' (f a)) (q₀ : g x₀.1 x₀.2 =[p₀] b₀') (q₁ : g x₁.1 x₁.2 =[p₁] b₁') (r : x₀ = x₁) : (λx, ⟨x..1, x..2⟩) (ap1_gen (sigma_functor f g) (sigma_eq p₀ q₀) (sigma_eq p₁ q₁) r) = ⟨ap1_gen f p₀ p₁ r..1, q₀⁻¹ᵒ ⬝o pathover_ap B' f (apo g r..2) ⬝o q₁⟩ := begin induction r, induction q₀, induction q₁, reflexivity end definition loop_psigma_gen_natural {A A' : Type*} {B : A → Type} {B' : A' → Type} {b : B pt} {b' : B' pt} (f : A →* A') (g : Πa, B a → B' (f a)) (p : g pt b =[respect_pt f] b') : psquare (Ω→ (psigma_gen_functor f g p)) (psigma_gen_functor (Ω→ f) (λq r, p⁻¹ᵒ ⬝o pathover_ap _ _ (apo g r) ⬝o p) !cono.left_inv) (loop_psigma_gen B b) (loop_psigma_gen B' b') := begin fapply phomotopy.mk, { exact ap1_gen_sigma f (respect_pt f) (respect_pt f) g p p }, { induction f with f f₀, induction A' with A' a₀', esimp at * ⊢, induction p, reflexivity } end definition psigma_gen_functor_pcompose [constructor] {A₁ A₂ A₃ : Type*} {B₁ : A₁ → Type} {B₂ : A₂ → Type} {B₃ : A₃ → Type} {b₁ : B₁ pt} {b₂ : B₂ pt} {b₃ : B₃ pt} {f₁ : A₁ →* A₂} {f₂ : A₂ →* A₃} (g₁ : Π⦃a⦄, B₁ a → B₂ (f₁ a)) (g₂ : Π⦃a⦄, B₂ a → B₃ (f₂ a)) (p₁ : pathover B₂ (g₁ b₁) (respect_pt f₁) b₂) (p₂ : pathover B₃ (g₂ b₂) (respect_pt f₂) b₃) : psigma_gen_functor (f₂ ∘* f₁) (λa, @g₂ (f₁ a) ∘ @g₁ a) (pathover_ap B₃ f₂ (apo g₂ p₁) ⬝o p₂) ~* psigma_gen_functor f₂ g₂ p₂ ∘* psigma_gen_functor f₁ g₁ p₁ := begin fapply phomotopy.mk, { intro x, reflexivity }, { refine !idp_con ⬝ _, esimp, refine whisker_right _ !ap_sigma_functor_sigma_eq ⬝ _, induction f₁ with f₁ f₁₀, induction f₂ with f₂ f₂₀, induction A₂ with A₂ a₂₀, induction A₃ with A₃ a₃₀, esimp at * ⊢, induction p₁, induction p₂, reflexivity } end definition psigma_gen_functor_phomotopy [constructor] {A₁ A₂ : Type*} {B₁ : A₁ → Type} {B₂ : A₂ → Type} {b₁ : B₁ pt} {b₂ : B₂ pt} {f₁ f₂ : A₁ →* A₂} {g₁ : Π⦃a⦄, B₁ a → B₂ (f₁ a)} {g₂ : Π⦃a⦄, B₁ a → B₂ (f₂ a)} {p₁ : pathover B₂ (g₁ b₁) (respect_pt f₁) b₂} {p₂ : pathover B₂ (g₂ b₁) (respect_pt f₂) b₂} (h₁ : f₁ ~* f₂) (h₂ : Π⦃a⦄ (b : B₁ a), pathover B₂ (g₁ b) (h₁ a) (g₂ b)) (h₃ : squareover B₂ (square_of_eq (to_homotopy_pt h₁)⁻¹) p₁ p₂ (h₂ b₁) idpo) : psigma_gen_functor f₁ g₁ p₁ ~* psigma_gen_functor f₂ g₂ p₂ := begin induction h₁ using phomotopy_rec_idp, fapply phomotopy.mk, { intro x, induction x with a b, exact ap (dpair (f₁ a)) (eq_of_pathover_idp (h₂ b)) }, { induction f₁ with f f₀, induction A₂ with A₂ a₂₀, esimp at * ⊢, induction f₀, esimp, induction p₂ using idp_rec_on, rewrite [to_right_inv !eq_con_inv_equiv_con_eq at h₃], have h₂ b₁ = p₁, from (eq_top_of_squareover h₃)⁻¹, induction this, refine !ap_dpair ⬝ ap (sigma_eq _) _, exact to_left_inv !pathover_idp (h₂ b₁) } end definition psigma_gen_functor_psquare [constructor] {A₀₀ A₀₂ A₂₀ A₂₂ : Type*} {B₀₀ : A₀₀ → Type} {B₀₂ : A₀₂ → Type} {B₂₀ : A₂₀ → Type} {B₂₂ : A₂₂ → Type} {b₀₀ : B₀₀ pt} {b₀₂ : B₀₂ pt} {b₂₀ : B₂₀ pt} {b₂₂ : B₂₂ pt} {f₀₁ : A₀₀ →* A₀₂} {f₁₀ : A₀₀ →* A₂₀} {f₂₁ : A₂₀ →* A₂₂} {f₁₂ : A₀₂ →* A₂₂} {g₀₁ : Π⦃a⦄, B₀₀ a → B₀₂ (f₀₁ a)} {g₁₀ : Π⦃a⦄, B₀₀ a → B₂₀ (f₁₀ a)} {g₂₁ : Π⦃a⦄, B₂₀ a → B₂₂ (f₂₁ a)} {g₁₂ : Π⦃a⦄, B₀₂ a → B₂₂ (f₁₂ a)} {p₀₁ : pathover B₀₂ (g₀₁ b₀₀) (respect_pt f₀₁) b₀₂} {p₁₀ : pathover B₂₀ (g₁₀ b₀₀) (respect_pt f₁₀) b₂₀} {p₂₁ : pathover B₂₂ (g₂₁ b₂₀) (respect_pt f₂₁) b₂₂} {p₁₂ : pathover B₂₂ (g₁₂ b₀₂) (respect_pt f₁₂) b₂₂} (h₁ : psquare f₁₀ f₁₂ f₀₁ f₂₁) (h₂ : Π⦃a⦄ (b : B₀₀ a), pathover B₂₂ (g₂₁ (g₁₀ b)) (h₁ a) (g₁₂ (g₀₁ b))) (h₃ : squareover B₂₂ (square_of_eq (to_homotopy_pt h₁)⁻¹) (pathover_ap B₂₂ f₂₁ (apo g₂₁ p₁₀) ⬝o p₂₁) (pathover_ap B₂₂ f₁₂ (apo g₁₂ p₀₁) ⬝o p₁₂) (h₂ b₀₀) idpo) : psquare (psigma_gen_functor f₁₀ g₁₀ p₁₀) (psigma_gen_functor f₁₂ g₁₂ p₁₂) (psigma_gen_functor f₀₁ g₀₁ p₀₁) (psigma_gen_functor f₂₁ g₂₁ p₂₁) := proof !psigma_gen_functor_pcompose⁻¹* ⬝* psigma_gen_functor_phomotopy h₁ h₂ h₃ ⬝* !psigma_gen_functor_pcompose qed end pointed open pointed namespace pointed definition pointed_respect_pt [instance] [constructor] {A B : Type*} (f : A →* B) : pointed (f pt = pt) := pointed.mk (respect_pt f) definition ppi_of_phomotopy [constructor] {A B : Type*} {f g : A →* B} (h : f ~* g) : ppi (λx, f x = g x) (respect_pt f ⬝ (respect_pt g)⁻¹) := h definition phomotopy {A : Type*} {P : A → Type} {x : P pt} (f g : ppi P x) : Type := ppi (λa, f a = g a) (respect_pt f ⬝ (respect_pt g)⁻¹) variables {A A' A'' : Type*} {P Q R : A → Type*} {P' : A' → Type*} {f g h : Π*a, P a} {B C D : A → Type} {b₀ : B pt} {c₀ : C pt} {d₀ : D pt} {k k' l m : ppi B b₀} definition pppi_equiv_pmap [constructor] (A B : Type*) : (Π*(a : A), B) ≃ (A →* B) := by reflexivity definition pppi_pequiv_ppmap [constructor] (A B : Type*) : (Π*(a : A), B) ≃* ppmap A B := by reflexivity definition apd10_to_fun_eq_of_phomotopy (h : f ~* g) : apd10 (ap (λ k, pppi.to_fun k) (eq_of_phomotopy h)) = h := begin induction h using phomotopy_rec_idp, xrewrite [eq_of_phomotopy_refl f] end -- definition phomotopy_of_eq_of_phomotopy definition phomotopy_mk_ppi [constructor] {A : Type*} {B : Type*} {C : B → Type*} {f g : A →* (Π*b, C b)} (p : Πa, f a ~* g a) (q : p pt ⬝* phomotopy_of_eq (respect_pt g) = phomotopy_of_eq (respect_pt f)) : f ~* g := begin apply phomotopy.mk (λa, eq_of_phomotopy (p a)), apply inj !ppi_eq_equiv, refine !phomotopy_of_eq_con ⬝ _, esimp, refine ap (λx, x ⬝* _) !phomotopy_of_eq_of_phomotopy ⬝ q end -- definition phomotopy_mk_ppmap [constructor] -- {A : Type*} {X : A → Type*} {Y : Π (a : A), X a → Type*} -- {f g : Π* (a : A), Π*(x : (X a)), (Y a x)} -- (p : Πa, f a ~* g a) -- (q : p pt ⬝* phomotopy_of_eq (ppi_resp_pt g) = phomotopy_of_eq (ppi_resp_pt f)) -- : f ~* g := -- begin -- apply phomotopy.mk (λa, eq_of_phomotopy (p a)), -- apply inj (ppi_eq_equiv _ _), -- refine !phomotopy_of_eq_con ⬝ _, -- -- refine !phomotopy_of_eq_of_phomotopy ◾** idp ⬝ q, -- end variable {k} variables (k l) definition ppi_loop_equiv : (k = k) ≃ Π*(a : A), Ω (pType.mk (B a) (k a)) := begin induction k with k p, induction p, exact ppi_eq_equiv (ppi.mk k idp) (ppi.mk k idp) end variables {k l} -- definition eq_of_phomotopy (h : k ~* l) : k = l := -- (ppi_eq_equiv k l)⁻¹ᵉ h definition ppi_functor_right [constructor] {A : Type*} {B B' : A → Type} {b : B pt} {b' : B' pt} (f : Πa, B a → B' a) (p : f pt b = b') (g : ppi B b) : ppi B' b' := ppi.mk (λa, f a (g a)) (ap (f pt) (respect_pt g) ⬝ p) definition ppi_functor_right_compose [constructor] {A : Type*} {B₁ B₂ B₃ : A → Type} {b₁ : B₁ pt} {b₂ : B₂ pt} {b₃ : B₃ pt} (f₂ : Πa, B₂ a → B₃ a) (p₂ : f₂ pt b₂ = b₃) (f₁ : Πa, B₁ a → B₂ a) (p₁ : f₁ pt b₁ = b₂) (g : ppi B₁ b₁) : ppi_functor_right (λa, f₂ a ∘ f₁ a) (ap (f₂ pt) p₁ ⬝ p₂) g ~* ppi_functor_right f₂ p₂ (ppi_functor_right f₁ p₁ g) := begin fapply phomotopy.mk, { reflexivity }, { induction p₁, induction p₂, exact !idp_con ⬝ !ap_compose⁻¹ } end definition ppi_functor_right_id [constructor] {A : Type*} {B : A → Type} {b : B pt} (g : ppi B b) : ppi_functor_right (λa, id) idp g ~* g := begin fapply phomotopy.mk, { reflexivity }, { reflexivity } end definition ppi_functor_right_phomotopy [constructor] {g g' : Π(a : A), B a → C a} {g₀ : g pt b₀ = c₀} {g₀' : g' pt b₀ = c₀} {f f' : ppi B b₀} (p : g ~2 g') (q : f ~* f') (r : p pt b₀ ⬝ g₀' = g₀) : ppi_functor_right g g₀ f ~* ppi_functor_right g' g₀' f' := phomotopy.mk (λa, p a (f a) ⬝ ap (g' a) (q a)) abstract begin induction q using phomotopy_rec_idp, induction r, revert g p, refine rec_idp_of_equiv _ homotopy2.rfl _ _ _, { intro h h', exact !eq_equiv_eq_symm ⬝e !eq_equiv_homotopy2 }, { reflexivity }, induction g₀', induction f with f f₀, induction f₀, reflexivity end end definition ppi_functor_right_phomotopy_refl [constructor] (g : Π(a : A), B a → C a) (g₀ : g pt b₀ = c₀) (f : ppi B b₀) : ppi_functor_right_phomotopy (homotopy2.refl g) (phomotopy.refl f) !idp_con = phomotopy.refl (ppi_functor_right g g₀ f) := begin induction g₀, apply ap (phomotopy.mk homotopy.rfl), refine !phomotopy_rec_idp_refl ⬝ _, esimp, refine !rec_idp_of_equiv_idp ⬝ _, induction f with f f₀, induction f₀, reflexivity end definition ppi_equiv_ppi_right [constructor] {A : Type*} {B B' : A → Type} {b : B pt} {b' : B' pt} (f : Πa, B a ≃ B' a) (p : f pt b = b') : ppi B b ≃ ppi B' b' := equiv.MK (ppi_functor_right f p) (ppi_functor_right (λa, (f a)⁻¹ᵉ) (inv_eq_of_eq p⁻¹)) abstract begin intro g, apply eq_of_phomotopy, refine !ppi_functor_right_compose⁻¹* ⬝* _, refine ppi_functor_right_phomotopy (λa, to_right_inv (f a)) (phomotopy.refl g) _ ⬝* !ppi_functor_right_id, induction p, exact adj (f pt) b ⬝ ap02 (f pt) !idp_con⁻¹ end end abstract begin intro g, apply eq_of_phomotopy, refine !ppi_functor_right_compose⁻¹* ⬝* _, refine ppi_functor_right_phomotopy (λa, to_left_inv (f a)) (phomotopy.refl g) _ ⬝* !ppi_functor_right_id, induction p, exact (!idp_con ⬝ !idp_con)⁻¹, end end definition ppi_equiv_ppi_basepoint [constructor] {A : Type*} {B : A → Type} {b b' : B pt} (p : b = b') : ppi B b ≃ ppi B b' := ppi_equiv_ppi_right (λa, erfl) p definition pmap_compose_ppi [constructor] (g : Π(a : A), ppmap (P a) (Q a)) (f : Π*(a : A), P a) : Π*(a : A), Q a := ppi_functor_right g (respect_pt (g pt)) f definition ppi_compose_pmap [constructor] (g : Π*(a : A), P a) (f : A' →* A) : Π*(a' : A'), P (f a') := ppi.mk (λa', g (f a')) (eq_of_pathover_idp (change_path !con.right_inv (apd g (respect_pt f) ⬝op respect_pt g ⬝o (apd (λx, Point (P x)) (respect_pt f))⁻¹ᵒ))) /- alternate proof for respecting the point -/ -- (eq_tr_of_pathover (apd g (respect_pt f)) ⬝ ap (transport _ _) (respect_pt g) ⬝ -- apdt (λx, Point (P x)) (respect_pt f)⁻¹) definition ppi_compose_pmap_phomotopy [constructor] (g : A →* A'') (f : A' →* A) : ppi_compose_pmap g f ~* g ∘* f := begin refine phomotopy.mk homotopy.rfl _, refine !idp_con ⬝ _, esimp, symmetry, refine !eq_of_pathover_idp_constant ⬝ _, refine !eq_of_pathover_change_path ⬝ !eq_of_pathover_cono ⬝ _, refine (!eq_of_pathover_concato_eq ⬝ !apd_eq_ap ◾ idp) ◾ (!eq_of_pathover_invo ⬝ (!apd_eq_ap ⬝ !ap_constant)⁻²) ⬝ _, reflexivity end definition pmap_compose_ppi_ppi_const [constructor] (g : Π(a : A), ppmap (P a) (Q a)) : pmap_compose_ppi g (ppi_const P) ~* ppi_const Q := proof phomotopy.mk (λa, respect_pt (g a)) !idp_con⁻¹ qed definition pmap_compose_ppi_pconst [constructor] (f : Π*(a : A), P a) : pmap_compose_ppi (λa, pconst (P a) (Q a)) f ~* ppi_const Q := phomotopy.mk homotopy.rfl !ap_constant⁻¹ definition ppi_compose_pmap_ppi_const [constructor] (f : A' →* A) : ppi_compose_pmap (ppi_const P) f ~* ppi_const (P ∘ f) := phomotopy.mk homotopy.rfl begin exact (ap eq_of_pathover_idp (change_path_of_pathover _ _ _ !cono.right_inv))⁻¹, end definition ppi_compose_pmap_pconst [constructor] (g : Π*(a : A), P a) : ppi_compose_pmap g (pconst A' A) ~* pconst A' (P pt) := phomotopy.mk (λa, respect_pt g) !idpo_concato_eq⁻¹ definition pmap_compose_ppi2 [constructor] {g g' : Π(a : A), ppmap (P a) (Q a)} {f f' : Π*(a : A), P a} (p : Πa, g a ~* g' a) (q : f ~* f') : pmap_compose_ppi g f ~* pmap_compose_ppi g' f' := ppi_functor_right_phomotopy p q (to_homotopy_pt (p pt)) definition pmap_compose_ppi2_refl [constructor] (g : Π(a : A), P a →* Q a) (f : Π*(a : A), P a) : pmap_compose_ppi2 (λa, phomotopy.refl (g a)) (phomotopy.refl f) = phomotopy.rfl := begin refine _ ⬝ ppi_functor_right_phomotopy_refl g (respect_pt (g pt)) f, exact ap (ppi_functor_right_phomotopy _ _) (to_right_inv !eq_con_inv_equiv_con_eq _) end definition pmap_compose_ppi_phomotopy_left [constructor] {g g' : Π(a : A), ppmap (P a) (Q a)} (f : Π*(a : A), P a) (p : Πa, g a ~* g' a) : pmap_compose_ppi g f ~* pmap_compose_ppi g' f := pmap_compose_ppi2 p phomotopy.rfl definition pmap_compose_ppi_phomotopy_right [constructor] (g : Π(a : A), ppmap (P a) (Q a)) {f f' : Π*(a : A), P a} (p : f ~* f') : pmap_compose_ppi g f ~* pmap_compose_ppi g f' := pmap_compose_ppi2 (λa, phomotopy.rfl) p definition pmap_compose_ppi_pid_left [constructor] (f : Π*(a : A), P a) : pmap_compose_ppi (λa, pid (P a)) f ~* f := phomotopy.mk homotopy.rfl idp definition pmap_compose_ppi_pcompose [constructor] (h : Π(a : A), ppmap (Q a) (R a)) (g : Π(a : A), ppmap (P a) (Q a)) : pmap_compose_ppi (λa, h a ∘* g a) f ~* pmap_compose_ppi h (pmap_compose_ppi g f) := phomotopy.mk homotopy.rfl abstract !idp_con ⬝ whisker_right _ (!ap_con ⬝ whisker_right _ !ap_compose') ⬝ !con.assoc end definition ppi_assoc [constructor] (h : Π (a : A), Q a →* R a) (g : Π (a : A), P a →* Q a) (f : Π*a, P a) : pmap_compose_ppi (λa, h a ∘* g a) f ~* pmap_compose_ppi h (pmap_compose_ppi g f) := begin fapply phomotopy.mk, { intro a, reflexivity }, exact !idp_con ⬝ whisker_right _ (!ap_con ⬝ whisker_right _ !ap_compose⁻¹) ⬝ !con.assoc end definition pmap_compose_ppi_eq_of_phomotopy (g : Πa, P a →* Q a) {f f' : Π*a, P a} (p : f ~* f') : ap (pmap_compose_ppi g) (eq_of_phomotopy p) = eq_of_phomotopy (pmap_compose_ppi_phomotopy_right g p) := begin induction p using phomotopy_rec_idp, refine ap02 _ !eq_of_phomotopy_refl ⬝ !eq_of_phomotopy_refl⁻¹ ⬝ ap eq_of_phomotopy _, exact !pmap_compose_ppi2_refl⁻¹ end definition ppi_assoc_ppi_const_right (g : Πa, Q a →* R a) (f : Πa, P a →* Q a) : ppi_assoc g f (ppi_const P) ⬝* (pmap_compose_ppi_phomotopy_right _ (pmap_compose_ppi_ppi_const f) ⬝* pmap_compose_ppi_ppi_const g) = pmap_compose_ppi_ppi_const (λa, g a ∘* f a) := begin revert R g, refine fiberwise_pointed_map_rec _ _, revert Q f, refine fiberwise_pointed_map_rec _ _, intro Q f R g, refine ap (λx, _ ⬝* (x ⬝* _)) !pmap_compose_ppi2_refl ⬝ _, reflexivity end definition pppi_compose_left [constructor] (g : Π(a : A), ppmap (P a) (Q a)) : (Π*(a : A), P a) →* Π*(a : A), Q a := pmap.mk (pmap_compose_ppi g) (eq_of_phomotopy (pmap_compose_ppi_ppi_const g)) definition pppi_compose_right [constructor] (f : A' →* A) : (Π*(a : A), P a) →* Π*(a' : A'), P (f a') := pmap.mk (λh, ppi_compose_pmap h f) (eq_of_phomotopy (ppi_compose_pmap_ppi_const f)) definition pppi_compose_right_phomotopy [constructor] (f : A' →* A) : pppi_compose_right f ~* @ppcompose_right _ _ A'' f := begin fapply phomotopy_mk_ppmap, { intro g, exact ppi_compose_pmap_phomotopy g f }, { exact sorry } end -- pppi_compose_left is a functor in the following sense definition pppi_compose_left_pcompose (g : Π (a : A), Q a →* R a) (f : Π (a : A), P a →* Q a) : pppi_compose_left (λ a, g a ∘* f a) ~* (pppi_compose_left g ∘* pppi_compose_left f) := begin fapply phomotopy_mk_ppi, { exact ppi_assoc g f }, { refine idp ◾** (!phomotopy_of_eq_con ⬝ (ap phomotopy_of_eq !pmap_compose_ppi_eq_of_phomotopy ⬝ !phomotopy_of_eq_of_phomotopy) ◾** !phomotopy_of_eq_of_phomotopy) ⬝ _ ⬝ !phomotopy_of_eq_of_phomotopy⁻¹, apply ppi_assoc_ppi_const_right }, end definition pppi_compose_left_phomotopy [constructor] {g g' : Π(a : A), ppmap (P a) (Q a)} (p : Πa, g a ~* g' a) : pppi_compose_left g ~* pppi_compose_left g' := begin apply phomotopy_of_eq, apply ap pppi_compose_left, apply eq_of_homotopy, intro a, apply eq_of_phomotopy, exact p a end definition psquare_pppi_compose_left {A : Type*} {B C D E : A → Type*} {ftop : Π (a : A), B a →* C a} {fbot : Π (a : A), D a →* E a} {fleft : Π (a : A), B a →* D a} {fright : Π (a : A), C a →* E a} (psq : Π (a :A), psquare (ftop a) (fbot a) (fleft a) (fright a)) : psquare (pppi_compose_left ftop) (pppi_compose_left fbot) (pppi_compose_left fleft) (pppi_compose_left fright) := begin refine (pppi_compose_left_pcompose fright ftop)⁻¹* ⬝* _ ⬝* (pppi_compose_left_pcompose fbot fleft), exact pppi_compose_left_phomotopy psq end definition ppi_pequiv_right [constructor] (g : Π(a : A), P a ≃* Q a) : (Π*(a : A), P a) ≃* Π*(a : A), Q a := begin apply pequiv_of_pmap (pppi_compose_left g), apply adjointify _ (pppi_compose_left (λa, (g a)⁻¹ᵉ*)), { intro f, apply eq_of_phomotopy, refine !pmap_compose_ppi_pcompose⁻¹* ⬝* _, refine pmap_compose_ppi_phomotopy_left _ (λa, !pright_inv) ⬝* _, apply pmap_compose_ppi_pid_left }, { intro f, apply eq_of_phomotopy, refine !pmap_compose_ppi_pcompose⁻¹* ⬝* _, refine pmap_compose_ppi_phomotopy_left _ (λa, !pleft_inv) ⬝* _, apply pmap_compose_ppi_pid_left } end end pointed namespace pointed variables {A B C : Type*} -- TODO: replace in types.fiber definition pfiber.sigma_char' (f : A →* B) : pfiber f ≃* psigma_gen (λa, f a = pt) (respect_pt f) := pequiv_of_equiv (fiber.sigma_char f pt) idp definition fiberpt [constructor] {A B : Type*} {f : A →* B} : fiber f pt := fiber.mk pt (respect_pt f) definition psigma_fiber_pequiv [constructor] {A B : Type*} (f : A →* B) : psigma_gen (fiber f) fiberpt ≃* A := pequiv_of_equiv (sigma_fiber_equiv f) idp definition ppmap.sigma_char [constructor] (A B : Type*) : ppmap A B ≃* @psigma_gen (A →ᵘ* B) (λf, f pt = pt) idp := pequiv_of_equiv !pmap.sigma_char idp definition pppi.sigma_char [constructor] (B : A → Type*) : (Π*(a : A), B a) ≃* @psigma_gen (Πᵘ*a, B a) (λf, f pt = pt) idp := proof pequiv_of_equiv !ppi.sigma_char idp qed definition pppi_sigma_char_natural_bottom [constructor] {B B' : A → Type*} (f : Πa, B a →* B' a) : @psigma_gen (Πᵘ*a, B a) (λg, g pt = pt) idp →* @psigma_gen (Πᵘ*a, B' a) (λg, g pt = pt) idp := psigma_gen_functor (pupi_functor_right f) (λg p, ap (f pt) p ⬝ respect_pt (f pt)) begin apply eq_pathover_constant_right, apply square_of_eq, esimp, exact !idp_con ⬝ !apd10_eq_of_homotopy⁻¹ ⬝ !ap_eq_apd10⁻¹, end definition pppi_sigma_char_natural {B B' : A → Type*} (f : Πa, B a →* B' a) : psquare (pppi_compose_left f) (pppi_sigma_char_natural_bottom f) (pppi.sigma_char B) (pppi.sigma_char B') := begin fapply phomotopy.mk, { intro g, reflexivity }, { refine !idp_con ⬝ !idp_con ⬝ _, fapply sigma_eq2, { refine !sigma_eq_pr1 ⬝ _ ⬝ !ap_sigma_pr1⁻¹, apply inj !eq_equiv_homotopy, refine !apd10_eq_of_homotopy_fn ⬝ _ ⬝ !apd10_to_fun_eq_of_phomotopy⁻¹, apply eq_of_homotopy, intro a, reflexivity }, { exact sorry } } end open sigma.ops definition psigma_gen_pi_pequiv_pupi_psigma_gen [constructor] {A : Type*} {B : A → Type*} (C : Πa, B a → Type) (c : Πa, C a pt) : @psigma_gen (Πᵘ*a, B a) (λf, Πa, C a (f a)) c ≃* Πᵘ*a, psigma_gen (C a) (c a) := pequiv_of_equiv sigma_pi_equiv_pi_sigma idp definition pupi_psigma_gen_pequiv_psigma_gen_pi [constructor] {A : Type*} {B : A → Type*} (C : Πa, B a → Type) (c : Πa, C a pt) : (Πᵘ*a, psigma_gen (C a) (c a)) ≃* @psigma_gen (Πᵘ*a, B a) (λf, Πa, C a (f a)) c := pequiv_of_equiv sigma_pi_equiv_pi_sigma⁻¹ᵉ idp definition psigma_gen_assoc [constructor] {A : Type*} {B : A → Type} (C : Πa, B a → Type) (b₀ : B pt) (c₀ : C pt b₀) : psigma_gen (λa, Σb, C a b) ⟨b₀, c₀⟩ ≃* @psigma_gen (psigma_gen B b₀) (λv, C v.1 v.2) c₀ := pequiv_of_equiv !sigma_assoc_equiv' idp definition psigma_gen_swap [constructor] {A : Type*} {B B' : A → Type} (C : Π⦃a⦄, B a → B' a → Type) (b₀ : B pt) (b₀' : B' pt) (c₀ : C b₀ b₀') : @psigma_gen (psigma_gen B b₀ ) (λv, Σb', C v.2 b') ⟨b₀', c₀⟩ ≃* @psigma_gen (psigma_gen B' b₀') (λv, Σb , C b v.2) ⟨b₀ , c₀⟩ := !psigma_gen_assoc⁻¹ᵉ* ⬝e* psigma_gen_pequiv_psigma_gen_right (λa, !sigma_comm_equiv) idp ⬝e* !psigma_gen_assoc definition ppi_psigma.{u v w} {A : pType.{u}} {B : A → pType.{v}} (C : Πa, B a → Type.{w}) (c : Πa, C a pt) : (Π*(a : A), (psigma_gen (C a) (c a))) ≃* psigma_gen (λ(f : Π*(a : A), B a), ppi (λa, C a (f a)) (transport (C pt) (respect_pt f)⁻¹ (c pt))) (ppi_const _) := proof calc (Π*(a : A), psigma_gen (C a) (c a)) ≃* @psigma_gen (Πᵘ*a, psigma_gen (C a) (c a)) (λf, f pt = pt) idp : pppi.sigma_char ... ≃* @psigma_gen (@psigma_gen (Πᵘ*a, B a) (λf, Πa, C a (f a)) c) (λv, Σ(p : v.1 pt = pt), v.2 pt =[p] c pt) ⟨idp, idpo⟩ : by exact psigma_gen_pequiv_psigma_gen (pupi_psigma_gen_pequiv_psigma_gen_pi C c) (λf, sigma_eq_equiv _ _) idpo ... ≃* @psigma_gen (@psigma_gen (Πᵘ*a, B a) (λf, f pt = pt) idp) (λv, Σ(g : Πa, C a (v.1 a)), g pt =[v.2] c pt) ⟨c, idpo⟩ : by apply psigma_gen_swap ... ≃* psigma_gen (λ(f : Π*(a : A), B a), ppi (λa, C a (f a)) (transport (C pt) (respect_pt f)⁻¹ (c pt))) (ppi_const _) : by exact (psigma_gen_pequiv_psigma_gen (pppi.sigma_char B) (λf, !ppi.sigma_char ⬝e sigma_equiv_sigma_right (λg, !pathover_equiv_eq_tr⁻¹ᵉ)) idpo)⁻¹ᵉ* qed definition ppmap_psigma {A B : Type*} (C : B → Type) (c : C pt) : ppmap A (psigma_gen C c) ≃* psigma_gen (λ(f : ppmap A B), ppi (C ∘ f) (transport C (respect_pt f)⁻¹ c)) (ppi_const _) := !pppi_pequiv_ppmap⁻¹ᵉ* ⬝e* !ppi_psigma ⬝e* sorry -- psigma_gen_pequiv_psigma_gen (pppi_pequiv_ppmap A B) (λf, begin esimp, exact ppi_equiv_ppi_right (λa, _) _ end) _ definition pfiber_pppi_compose_left {B C : A → Type*} (f : Πa, B a →* C a) : pfiber (pppi_compose_left f) ≃* Π*(a : A), pfiber (f a) := calc pfiber (pppi_compose_left f) ≃* psigma_gen (λ(g : Π*(a : A), B a), pmap_compose_ppi f g = ppi_const C) proof (eq_of_phomotopy (pmap_compose_ppi_ppi_const f)) qed : by exact !pfiber.sigma_char' ... ≃* psigma_gen (λ(g : Π*(a : A), B a), pmap_compose_ppi f g ~* ppi_const C) proof (pmap_compose_ppi_ppi_const f) qed : by exact psigma_gen_pequiv_psigma_gen_right (λa, !ppi_eq_equiv) !phomotopy_of_eq_of_phomotopy ... ≃* @psigma_gen (Π*(a : A), B a) (λ(g : Π*(a : A), B a), ppi (λa, f a (g a) = pt) (transport (λb, f pt b = pt) (respect_pt g)⁻¹ (respect_pt (f pt)))) (ppi_const _) : begin refine psigma_gen_pequiv_psigma_gen_right (λg, ppi_equiv_ppi_basepoint (_ ⬝ !eq_transport_Fl⁻¹)) _, intro g, refine !con_idp ⬝ _, apply whisker_right, exact ap02 (f pt) !inv_inv⁻¹ ⬝ !ap_inv, apply eq_of_phomotopy, fapply phomotopy.mk, intro x, reflexivity, refine !idp_con ⬝ _, symmetry, refine !ap_id ◾ !idp_con ⬝ _, apply con.right_inv end ... ≃* Π*(a : A), (psigma_gen (λb, f a b = pt) (respect_pt (f a))) : by exact (ppi_psigma _ _)⁻¹ᵉ* ... ≃* Π*(a : A), pfiber (f a) : by exact ppi_pequiv_right (λa, !pfiber.sigma_char'⁻¹ᵉ*) /- TODO: proof the following as a special case of pfiber_pppi_compose_left -/ definition pfiber_ppcompose_left (f : B →* C) : pfiber (@ppcompose_left A B C f) ≃* ppmap A (pfiber f) := calc pfiber (@ppcompose_left A B C f) ≃* psigma_gen (λ(g : ppmap A B), f ∘* g = pconst A C) proof (eq_of_phomotopy (pcompose_pconst f)) qed : by exact !pfiber.sigma_char' ... ≃* psigma_gen (λ(g : ppmap A B), f ∘* g ~* pconst A C) proof (pcompose_pconst f) qed : by exact psigma_gen_pequiv_psigma_gen_right (λa, !pmap_eq_equiv) !phomotopy_of_eq_of_phomotopy ... ≃* psigma_gen (λ(g : ppmap A B), ppi (λa, f (g a) = pt) (transport (λb, f b = pt) (respect_pt g)⁻¹ (respect_pt f))) (ppi_const _) : begin refine psigma_gen_pequiv_psigma_gen_right (λg, ppi_equiv_ppi_basepoint (_ ⬝ !eq_transport_Fl⁻¹)) _, intro g, refine !con_idp ⬝ _, apply whisker_right, exact ap02 f !inv_inv⁻¹ ⬝ !ap_inv, apply eq_of_phomotopy, fapply phomotopy.mk, intro x, reflexivity, refine !idp_con ⬝ _, symmetry, refine !ap_id ◾ !idp_con ⬝ _, apply con.right_inv end ... ≃* ppmap A (psigma_gen (λb, f b = pt) (respect_pt f)) : by exact (ppmap_psigma _ _)⁻¹ᵉ* ... ≃* ppmap A (pfiber f) : by exact ppmap_pequiv_ppmap_right !pfiber.sigma_char'⁻¹ᵉ* -- definition pppi_ppmap {A C : Type*} {B : A → Type*} : -- ppmap (/- dependent smash of B -/) C ≃* Π*(a : A), ppmap (B a) C := definition ppi_add_point_over {A : Type} (B : A → Type*) : (Π*a, add_point_over B a) ≃ Πa, B a := begin fapply equiv.MK, { intro f a, exact f (some a) }, { intro f, fconstructor, intro a, cases a, exact pt, exact f a, reflexivity }, { intro f, reflexivity }, { intro f, cases f with f p, apply eq_of_phomotopy, fapply phomotopy.mk, { intro a, cases a, exact p⁻¹, reflexivity }, { exact con.left_inv p }}, end definition pppi_add_point_over {A : Type} (B : A → Type*) : (Π*a, add_point_over B a) ≃* Πᵘ*a, B a := pequiv_of_equiv (ppi_add_point_over B) idp definition ppmap_add_point {A : Type} (B : Type*) : ppmap A₊ B ≃* A →ᵘ* B := pequiv_of_equiv (pmap_equiv_left A B) idp /- There are some lemma's needed to prove the naturality of the equivalence Ω (Π*a, B a) ≃* Π*(a : A), Ω (B a) -/ definition ppi_eq_equiv_natural_gen_lem {B C : A → Type} {b₀ : B pt} {c₀ : C pt} {f : Π(a : A), B a → C a} {f₀ : f pt b₀ = c₀} {k : ppi B b₀} {k' : ppi C c₀} (p : ppi_functor_right f f₀ k ~* k') : ap1_gen (f pt) (p pt) f₀ (respect_pt k) = respect_pt k' := begin symmetry, refine _ ⬝ !con.assoc⁻¹, exact eq_inv_con_of_con_eq (to_homotopy_pt p), end definition ppi_eq_equiv_natural_gen_lem2 {B C : A → Type} {b₀ : B pt} {c₀ : C pt} {f : Π(a : A), B a → C a} {f₀ : f pt b₀ = c₀} {k l : ppi B b₀} {k' l' : ppi C c₀} (p : ppi_functor_right f f₀ k ~* k') (q : ppi_functor_right f f₀ l ~* l') : ap1_gen (f pt) (p pt) (q pt) (respect_pt k ⬝ (respect_pt l)⁻¹) = respect_pt k' ⬝ (respect_pt l')⁻¹ := (ap1_gen_con (f pt) _ f₀ _ _ _ ⬝ (ppi_eq_equiv_natural_gen_lem p) ◾ (!ap1_gen_inv ⬝ (ppi_eq_equiv_natural_gen_lem q)⁻²)) definition ppi_eq_equiv_natural_gen {B C : A → Type} {b₀ : B pt} {c₀ : C pt} {f : Π(a : A), B a → C a} {f₀ : f pt b₀ = c₀} {k l : ppi B b₀} {k' l' : ppi C c₀} (p : ppi_functor_right f f₀ k ~* k') (q : ppi_functor_right f f₀ l ~* l') : hsquare (ap1_gen (ppi_functor_right f f₀) (eq_of_phomotopy p) (eq_of_phomotopy q)) (ppi_functor_right (λa, ap1_gen (f a) (p a) (q a)) (ppi_eq_equiv_natural_gen_lem2 p q)) phomotopy_of_eq phomotopy_of_eq := begin intro r, induction r, induction f₀, induction k with k k₀, induction k₀, refine idp ⬝ _, revert l' q, refine phomotopy_rec_idp' _ _, revert k' p, refine phomotopy_rec_idp' _ _, reflexivity end definition ppi_eq_equiv_natural_gen_refl {B C : A → Type} {f : Π(a : A), B a → C a} {k : Πa, B a} : ppi_eq_equiv_natural_gen (phomotopy.refl (ppi_functor_right f idp (ppi.mk k idp))) (phomotopy.refl (ppi_functor_right f idp (ppi.mk k idp))) idp = ap phomotopy_of_eq !ap1_gen_idp := begin refine !idp_con ⬝ _, refine !phomotopy_rec_idp'_refl ⬝ _, refine ap (transport _ _) !phomotopy_rec_idp'_refl ⬝ _, refine !tr_diag_eq_tr_tr⁻¹ ⬝ _, refine !eq_transport_Fl ⬝ _, refine !ap_inv⁻² ⬝ !inv_inv ⬝ !ap_compose ⬝ ap02 _ _, exact !ap1_gen_idp_eq⁻¹ end definition loop_pppi_pequiv [constructor] {A : Type*} (B : A → Type*) : Ω (Π*a, B a) ≃* Π*(a : A), Ω (B a) := pequiv_of_equiv !ppi_eq_equiv idp definition loop_pppi_pequiv_natural_right {A : Type*} {X Y : A → Type*} (f : Π (a : A), X a →* Y a) : psquare (loop_pppi_pequiv X) (loop_pppi_pequiv Y) (Ω→ (pppi_compose_left f)) (pppi_compose_left (λ a, Ω→ (f a))) := begin apply ptranspose, revert Y f, refine fiberwise_pointed_map_rec _ _, intro Y f, fapply phomotopy.mk, { exact ppi_eq_equiv_natural_gen (pmap_compose_ppi_ppi_const (λa, pmap_of_map (f a) pt)) (pmap_compose_ppi_ppi_const (λa, pmap_of_map (f a) pt)) }, { exact !ppi_eq_equiv_natural_gen_refl ◾ (!idp_con ⬝ !eq_of_phomotopy_refl) } end definition loop_pppi_pequiv_natural_left {A B : Type*} {X : A → Type*} (f : B →* A) : psquare (loop_pppi_pequiv X) (loop_pppi_pequiv (X ∘ f)) (Ω→ (pppi_compose_right f)) (pppi_compose_right f) := begin exact sorry end definition loopn_pppi_pequiv (n : ℕ) {A : Type*} (B : A → Type*) : Ω[n] (Π*a, B a) ≃* Π*(a : A), Ω[n] (B a) := begin induction n with n IH, { reflexivity }, { refine loop_pequiv_loop IH ⬝e* loop_pppi_pequiv (λa, Ω[n] (B a)) } end definition loop_ppmap_pequiv [constructor] (A B : Type*) : Ω (A →** B) ≃* A →** Ω B := !loop_pppi_pequiv definition loop_ppmap_pequiv_natural_right (A : Type*) {X Y : Type*} (f : X →* Y) : psquare (loop_ppmap_pequiv A X) (loop_ppmap_pequiv A Y) (Ω→ (ppcompose_left f)) (ppcompose_left (Ω→ f)) := begin exact loop_pppi_pequiv_natural_right (λa, f) end definition loop_ppmap_pequiv_natural_left {A B : Type*} (X : Type*) (f : A →* B) : psquare (loop_ppmap_pequiv B X) (loop_ppmap_pequiv A X) (Ω→ (ppcompose_right f)) (ppcompose_right f) := begin refine Ω⇒ !pppi_compose_right_phomotopy⁻¹* ⬝ph* _ ⬝hp* !pppi_compose_right_phomotopy⁻¹*, exact loop_pppi_pequiv_natural_left f end definition loopn_ppmap_pequiv (n : ℕ) (A B : Type*) : Ω[n] (A →** B) ≃* A →** Ω[n] B := !loopn_pppi_pequiv definition pfunext [constructor] {A : Type*} (B : A → Type*) : (Π*(a : A), Ω (B a)) ≃* Ω (Π*a, B a) := (loop_pppi_pequiv B)⁻¹ᵉ* definition deloopable_pppi [instance] [constructor] {A : Type*} (B : A → Type*) [Πa, deloopable (B a)] : deloopable (Π*a, B a) := deloopable.mk (Π*a, deloop (B a)) (loop_pppi_pequiv (λa, deloop (B a)) ⬝e* ppi_pequiv_right (λa, deloop_pequiv (B a))) definition deloopable_ppmap [instance] [constructor] (A B : Type*) [deloopable B] : deloopable (A →** B) := deloopable_pppi (λa, B) /- below is an alternate proof strategy for the naturality of loop_pppi_pequiv_natural, where we define loop_pppi_pequiv as composite of pointed equivalences, and proved the naturality individually. That turned out to be harder. -/ /- definition loop_pppi_pequiv2 {A : Type*} (B : A → Type*) : Ω (Π*a, B a) ≃* Π*(a : A), Ω (B a) := begin refine loop_pequiv_loop (pppi.sigma_char B) ⬝e* _, refine !loop_psigma_gen ⬝e* _, transitivity @psigma_gen (Πᵘ*a, Ω (B a)) (λf, f pt = idp) idp, exact psigma_gen_pequiv_psigma_gen (loop_pupi B) (λp, eq_pathover_equiv_Fl p idp idp ⬝e equiv_eq_closed_right _ (whisker_right _ (ap_eq_apd10 p _)) ⬝e !eq_equiv_eq_symm) idpo, exact (pppi.sigma_char (Ω ∘ B))⁻¹ᵉ* end definition loop_pppi_pequiv_natural2 {A : Type*} {X Y : A → Type*} (f : Π (a : A), X a →* Y a) : psquare (Ω→ (pppi_compose_left f)) (pppi_compose_left (λ a, Ω→ (f a))) (loop_pppi_pequiv2 X) (loop_pppi_pequiv2 Y) := begin refine ap1_psquare (pppi_sigma_char_natural f) ⬝v* _, refine !loop_psigma_gen_natural ⬝v* _, refine _ ⬝v* (pppi_sigma_char_natural (λ a, Ω→ (f a)))⁻¹ᵛ*, fapply psigma_gen_functor_psquare, { apply loop_pupi_natural }, { intro p q, exact sorry }, { exact sorry } end-/ end pointed open pointed open is_trunc is_conn namespace is_conn section /- todo: reorder arguments and make some implicit -/ variables (A : Type*) (n : ℕ₋₂) (H : is_conn (n.+1) A) include H definition is_contr_ppi_match (P : A → Type*) (H2 : Πa, is_trunc (n.+1) (P a)) : is_contr (Π*(a : A), P a) := begin apply is_contr.mk pt, intro f, induction f with f p, apply eq_of_phomotopy, fapply phomotopy.mk, { apply is_conn.elim n, exact p⁻¹ }, { krewrite (is_conn.elim_β n), apply con.left_inv } end -- definition is_trunc_ppi_of_is_conn (k : ℕ₋₂) (P : A → Type*) -- : is_trunc k.+1 (Π*(a : A), P a) := definition is_trunc_ppi_of_is_conn (k l : ℕ₋₂) (H2 : l ≤ n.+1+2+k) (P : A → Type*) (H3 : Πa, is_trunc l (P a)) : is_trunc k.+1 (Π*(a : A), P a) := begin have H4 : Πa, is_trunc (n.+1+2+k) (P a), from λa, is_trunc_of_le (P a) H2 _, clear H2 H3, revert P H4, induction k with k IH: intro P H4, { apply is_prop_of_imp_is_contr, intro f, apply is_contr_ppi_match A n H P H4 }, { apply is_trunc_succ_of_is_trunc_loop (trunc_index.succ_le_succ (trunc_index.minus_two_le k)), intro f, apply @is_trunc_equiv_closed_rev _ _ k.+1 (ppi_loop_equiv f), apply IH, intro a, apply is_trunc_loop, apply H4 } end definition is_trunc_pmap_of_is_conn (k l : ℕ₋₂) (B : Type*) (H2 : l ≤ n.+1+2+k) (H3 : is_trunc l B) : is_trunc k.+1 (A →* B) := is_trunc_ppi_of_is_conn A n H k l H2 (λ a, B) _ end open trunc_index algebra nat definition is_trunc_ppi_of_is_conn_nat (A : Type*) (n : ℕ) (H : is_conn (n.-1) A) (k l : ℕ) (H2 : l ≤ n + k) (P : A → Type*) (H3 : Πa, is_trunc l (P a)) : is_trunc k (Π*(a : A), P a) := begin refine is_trunc_ppi_of_is_conn A (n.-2) H (k.-1) l _ P H3, refine le.trans (of_nat_le_of_nat H2) (le_of_eq !sub_one_add_plus_two_sub_one⁻¹) end definition is_trunc_pmap_of_is_conn_nat (A : Type*) (n : ℕ) (H : is_conn (n.-1) A) (k l : ℕ) (B : Type*) (H2 : l ≤ n + k) (H3 : is_trunc l B) : is_trunc k (A →* B) := is_trunc_ppi_of_is_conn_nat A n H k l H2 (λ a, B) _ -- this is probably much easier to prove directly definition is_trunc_ppi (A : Type*) (n k : ℕ₋₂) (H : n ≤ k) (P : A → Type*) (H2 : Πa, is_trunc n (P a)) : is_trunc k (Π*(a : A), P a) := begin cases k with k, { apply is_contr_of_merely_prop, { exact @is_trunc_ppi_of_is_conn A -2 (is_conn_minus_one A (tr pt)) -2 _ (trunc_index.le.step H) P H2 }, { exact tr pt } }, { assert K : n ≤ -1 +2+ k, { rewrite (trunc_index.add_plus_two_comm -1 k), exact H }, { exact @is_trunc_ppi_of_is_conn A -2 (is_conn_minus_one A (tr pt)) k _ K P H2 } } end end is_conn /- TODO: move, these facts use some of these pointed properties -/ namespace trunc lemma pmap_ptrunc_pequiv_natural [constructor] (n : ℕ₋₂) {A A' B B' : Type*} [H : is_trunc n B] [H : is_trunc n B'] (f : A' →* A) (g : B →* B') : psquare (pmap_ptrunc_pequiv n A B) (pmap_ptrunc_pequiv n A' B') (ppcompose_left g ∘* ppcompose_right (ptrunc_functor n f)) (ppcompose_left g ∘* ppcompose_right f) := begin refine _ ⬝v* _, exact pmap_ptrunc_pequiv n A' B, { fapply phomotopy.mk, { intro h, apply eq_of_phomotopy, exact !passoc ⬝* pwhisker_left h (ptr_natural n f)⁻¹* ⬝* !passoc⁻¹* }, { xrewrite [▸*, +pcompose_right_eq_of_phomotopy, -+eq_of_phomotopy_trans], apply ap eq_of_phomotopy, refine !trans_assoc ⬝ idp ◾** (!trans_assoc⁻¹ ⬝ (eq_bot_of_phsquare (phtranspose (passoc_pconst_left (ptrunc_functor n f) (ptr n A'))))⁻¹) ⬝ _, refine !trans_assoc ⬝ idp ◾** !pconst_pcompose_phomotopy ⬝ _, apply passoc_pconst_left }}, { fapply phomotopy.mk, { intro h, apply eq_of_phomotopy, exact !passoc⁻¹* }, { xrewrite [▸*, pcompose_right_eq_of_phomotopy, pcompose_left_eq_of_phomotopy, -+eq_of_phomotopy_trans], apply ap eq_of_phomotopy, apply symm_trans_eq_of_eq_trans, symmetry, apply passoc_pconst_middle }} end end trunc
f3b41a062fd19d413b4b5817fa770483d32622a8
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/topology/order.lean
cab31ed76ebf8b5cc691657fab17ec37c534fde2
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
27,833
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 filter 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, 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}, 𝓟 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 _ ≤ 𝓟 s ⊓ 𝓟 t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ 𝓟 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.unique_topological_space [subsingleton α] : unique (topological_space α) := { default := ⊥, uniq := λ t, eq_bot_of_singletons_open $ λ x, subsingleton.set_cases (@is_open_empty _ t) (@is_open_univ _ t) ({x} : set α) } @[priority 100] instance subsingleton.discrete_topology [t : topological_space α] [subsingleton α] : discrete_topology α := ⟨unique.eq_default t⟩ 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 α} : @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 ne_bot (comap f (𝓝 (f a) ⊓ 𝓟 (f '' s))) ↔ ne_bot (𝓝 (f a) ⊓ 𝓟 (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) ⊓ 𝓟 (f '' s), from mem_inf_sets_of_right $ by simp [subset.refl], have s₂ ∩ f '' s ∈ 𝓝 (f a) ⊓ 𝓟 (f '' s), from inter_mem_sets hs₂ this, let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := h.nonempty_of_mem this in ⟨_, hs $ by rwa [←ha₂] at hb₁⟩⟩, calc a ∈ @closure α (topological_space.induced f t) s ↔ (@nhds α (topological_space.induced f t) a) ⊓ 𝓟 s ≠ ⊥ : by rw [closure_eq_cluster_pts]; refl ... ↔ comap f (𝓝 (f a)) ⊓ 𝓟 (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced, preimage_image_eq _ hf] ... ↔ comap f (𝓝 (f a) ⊓ 𝓟 (f '' s)) ≠ ⊥ : by rw [comap_inf, ←comap_principal] ... ↔ _ : by rwa [closure_eq_cluster_pts] 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
3062690ae2ff3cc071836b3d6f63e06cc6c32a4c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/place_eqn.lean
40bcc3969b17d8b94d5229304d9a8b96a586077d
[ "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
79
lean
open nat definition foo : nat → nat | foo zero := _ | foo (succ a) := _
53573bf1244ea1bdd4a305455e2651009bec5e9a
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/tactic/norm_num.lean
36f34ead452aef9ea129d62a97b899fb235e9a37
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
59,966
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro -/ import data.rat.cast import data.rat.meta_defs /-! # `norm_num` Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `≤`. -/ universes u v w namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e namespace instance_cache /-- Faster version of `mk_app ``bit0 [e]`. -/ meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]) /-- Faster version of `mk_app ``bit1 [e]`. -/ meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) end instance_cache end tactic open tactic namespace norm_num variable {α : Type u} lemma subst_into_add {α} [has_add α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := by rw [prl, prr, prt] lemma subst_into_mul {α} [has_mul α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := by rw [prl, prr, prt] lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] /-- The result type of `match_numeral`, either `0`, `1`, or a top level decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/ meta inductive match_numeral_result | zero | one | bit0 (e : expr) | bit1 (e : expr) | other /-- Unfold the top level constructor of the numeral expression. -/ meta def match_numeral : expr → match_numeral_result | `(bit0 %%e) := match_numeral_result.bit0 e | `(bit1 %%e) := match_numeral_result.bit1 e | `(@has_zero.zero _ _) := match_numeral_result.zero | `(@has_one.one _ _) := match_numeral_result.one | _ := match_numeral_result.other theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _ theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable. (It may prove garbage instead of failing if `a + 1 = b` is false.) -/ meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr) | c e r := match match_numeral e with | zero := c.mk_app ``zero_succ [] | one := c.mk_app ``one_succ [] | bit0 e := c.mk_app ``bit0_succ [e] | bit1 e := do let r := r.app_arg, (c, p) ← prove_succ c e r, c.mk_app ``bit1_succ [e, r, p] | _ := failed end end theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_assoc] theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm] theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm] theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit0 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit0 a + bit1 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result meta mutual def prove_add_nat, prove_adc_nat with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := c.mk_app ``zero_add [b] | _, zero := c.mk_app ``add_zero [a] | _, one := prove_succ c a r | one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p] | _, _ := failed end with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p] | _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p] | one, one := c.mk_app ``adc_one_one [] | bit0 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p] | one, bit0 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p] | bit1 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p] | one, bit1 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p] | _, _ := failed end /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/ add_decl_doc prove_add_nat /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/ add_decl_doc prove_adc_nat /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/ meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, nb ← b.to_nat, (c, r) ← c.of_nat (na + nb), (c, p) ← prove_add_nat c a b r, return (c, r, p) end theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul] theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) : a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add] theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h) theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α) (hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) : bit1 a * bit1 b = bit1 e := by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/ meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic a b := match match_numeral a, match_numeral b with | zero, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, zero := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p) | _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p) | bit0 a, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p], (ic, c') ← ic.mk_bit0 c, (ic, c') ← ic.mk_bit0 c', return (ic, c', p) | bit0 a, _ := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | _, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | bit1 a, bit1 b := do (ic, c, pc) ← prove_mul_nat ic a b, (ic, d, pd) ← prove_add_nat' ic a b, (ic, c') ← ic.mk_bit0 c, (ic, e, pe) ← prove_add_nat' ic c' d, (ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe], (ic, e') ← ic.mk_bit1 e, return (ic, e', p) | _, _ := failed end end section open match_numeral_result /-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/ meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr) | e := match match_numeral e with | one := c.mk_app ``zero_lt_one' [] | bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p] | bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p] | _ := failed end end /-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/ meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr) | `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂, c.mk_app ``div_pos [e₁, e₂, p₁, p₂] | e := prove_pos_nat c e /-- `match_neg (- e) = some e`, otherwise `none` -/ meta def match_neg : expr → option expr | `(- %%e) := some e | _ := none /-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/ meta def match_sign : expr → expr ⊕ bool | `(- %%e) := sum.inl e | `(has_zero.zero) := sum.inr ff | _ := sum.inr tt theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1 /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero' (c : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_neg a with | some a := do (c, p) ← prove_ne_zero' a, c.mk_app ``ne_zero_neg [a, p] | none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p] end theorem clear_denom_div {α} [division_ring α] (a b b' c d : α) (h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c := by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀] /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom' (prove_ne_zero : instance_cache → expr → ℚ → tactic (instance_cache × expr)) (c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) : tactic (instance_cache × expr × expr) := if na.denom = 1 then prove_mul_nat c a d else do [_, _, a, b] ← return a.get_app_args, (c, b') ← c.of_nat (nd / na.denom), (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, _, p₁) ← prove_mul_nat c b b', (c, r, p₂) ← prove_mul_nat c a b', (c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂], return (c, r, p) theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a := lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h) theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a := one_lt_bit1.2 h theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b := bit0_lt_bit0.2 theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b := lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _) theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b := lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h) theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b := bit1_lt_bit1.2 theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a := le_of_lt (lt_one_bit0 _ h) -- deliberately strong hypothesis because bit1 0 is not a numeral theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a := le_of_lt (lt_one_bit1 _ h) theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b := bit0_le_bit0.2 theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b := le_of_lt (lt_bit0_bit1 _ _ h) theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b := le_of_lt (lt_bit1_bit0 _ _ h) theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b := bit1_le_bit1.2 theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a := bit0_le_bit0.2 theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a := le_bit0_bit1 _ _ theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b := le_bit1_bit0 _ _ theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b := bit1_le_bit1.2 h theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit0 b := (bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit1 b := (bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h /-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/ meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr) | e@`(has_zero.zero) := ic.mk_app ``le_refl [e] | e := if ic.α = `(ℕ) then return (ic, `(nat.zero_le).mk_app [e]) else do (ic, p) ← prove_pos ic e, ic.mk_app ``nonneg_pos [e, p] section open match_numeral_result /-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/ meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_numeral a with | one := ic.mk_app ``le_refl [a] | bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p] | bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p] | _ := failed end meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache) with prove_le_nat : expr → expr → tactic (instance_cache × expr) | a b := if a = b then ic.mk_app ``le_refl [a] else match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p] | _, _ := failed end with prove_sle_nat : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p] | _, _ := failed end /-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/ add_decl_doc prove_le_nat /-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/ add_decl_doc prove_sle_nat /-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/ meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_pos ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p] | _, _ := failed end end theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b := lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀) /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_lt_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_lt_nat ic a' b', ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p] lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b := lt_trans (neg_neg_of_pos ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_lt_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_lt_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_pos ic a, ic.mk_app ``neg_neg_of_pos [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_pos ic a, (ic, pb) ← prove_pos ic b, ic.mk_app ``lt_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_pos ic b | sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb end theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b := le_of_mul_le_mul_right (by rwa [ha, hb]) h₀ /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_le_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_le_nat ic a' b', ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p] lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b := le_trans (neg_nonpos_of_nonneg ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_le_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_nonneg ic a, ic.mk_app ``neg_nonpos_of_nonneg [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_nonneg ic a, (ic, pb) ← prove_nonneg ic b, ic.mk_app ``le_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_nonneg ic b | sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb end /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove `⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/ meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na < nb then do (ic, p) ← prove_lt_rat ic a b na nb, ic.mk_app ``ne_of_lt [a, b, p] else do (ic, p) ← prove_lt_rat ic b a nb na, ic.mk_app ``ne_of_gt [a, b, p] theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ nat.cast_bit0 _ theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ nat.cast_bit1 _ theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ int.cast_bit0 _ theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ int.cast_bit1 _ theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ rat.cast_bit0 _ theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ rat.cast_bit1 _ /-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (nc, e) ← nc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``nat_cast_zero [], return (ic, nc, e, p) | match_numeral_result.one := do (nc, e) ← nc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``nat_cast_one [], return (ic, nc, e, p) | match_numeral_result.bit0 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a0) ← nc.mk_bit0 a, (ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p], return (ic, nc, a0, p) | match_numeral_result.bit1 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a1) ← nc.mk_bit1 a, (ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p], return (ic, nc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (zc, e) ← zc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``int_cast_zero [], return (ic, zc, e, p) | match_numeral_result.one := do (zc, e) ← zc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``int_cast_one [], return (ic, zc, e, p) | match_numeral_result.bit0 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a0) ← zc.mk_bit0 a, (ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p], return (ic, zc, a0, p) | match_numeral_result.bit1 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a1) ← zc.mk_bit1 a, (ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p], return (ic, zc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (qc, e) ← qc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``rat.cast_zero [], return (ic, qc, e, p) | match_numeral_result.one := do (qc, e) ← qc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``rat.cast_one [], return (ic, qc, e, p) | match_numeral_result.bit0 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a0) ← qc.mk_bit0 a, (ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p], return (ic, qc, a0, p) | match_numeral_result.bit1 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a1) ← qc.mk_bit1 a, (ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p], return (ic, qc, a1, p) | _ := failed end theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' := ha ▸ hb ▸ rat.cast_div _ _ /-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := if na'.denom = 1 then prove_rat_uncast_nat ic qc cz_inst a' else do [_, _, a', b'] ← return a'.get_app_args, (ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a', (ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b', (qc, e) ← qc.mk_app ``has_div.div [a, b], (ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb], return (ic, qc, e, p) theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ int.cast_neg _ theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ rat.cast_neg _ /-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, zc, a, p) ← prove_int_uncast_nat ic zc a', (zc, e) ← zc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``int_cast_neg [a, a', p], return (ic, zc, e, p) | none := prove_int_uncast_nat ic zc a' end /-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'), (qc, e) ← qc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p], return (ic, qc, e, p) | none := prove_rat_uncast_nonneg ic qc cz_inst a' na' end theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt nat.cast_inj.1 h theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt int.cast_inj.1 h theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt rat.cast_inj.1 h /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods: * Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order * Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`. This requires that the base type be `char_zero`, and also that it be a `division_ring` so that the coercion from `ℚ` is well defined. We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero` rings and semirings. -/ meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr) | ic a b na nb := prove_ne_rat ic a b na nb <|> do cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance, if na.denom = 1 ∧ nb.denom = 1 then if na ≥ 0 ∧ nb ≥ 0 then do guard (ic.α ≠ `(ℕ)), nc ← mk_instance_cache `(ℕ), (ic, nc, a', pa) ← prove_nat_uncast ic nc a, (ic, nc, b', pb) ← prove_nat_uncast ic nc b, (nc, p) ← prove_ne_rat nc a' b' na nb, ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℤ)), zc ← mk_instance_cache `(ℤ), (ic, zc, a', pa) ← prove_int_uncast ic zc a, (ic, zc, b', pb) ← prove_int_uncast ic zc b, (zc, p) ← prove_ne_rat zc a' b' na nb, ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℚ)), qc ← mk_instance_cache `(ℚ), (ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na, (ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb, (qc, p) ← prove_ne_rat qc a' b' na nb, ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero (ic : instance_cache) : expr → ℚ → tactic (instance_cache × expr) | a na := do (ic, z) ← ic.mk_app ``has_zero.zero [], prove_ne ic a z na 0 /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom : instance_cache → expr → expr → ℚ → ℕ → tactic (instance_cache × expr × expr) := prove_clear_denom' prove_ne_zero theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α) (h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c') (h : a' + b' = c') : a + b = c := mul_right_cancel' h₀ $ by rwa [add_mul, ha, hb, hc] /-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_add_nat ic a b c else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_ne_zero ic d (rat.of_int nd), (ic, a', pa) ← prove_clear_denom ic a d na nd, (ic, b', pb) ← prove_clear_denom ic b d nb nd, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, p) ← prove_add_nat ic a' b' c', ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p] theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c := h ▸ by simp theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c := h ▸ by simp theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c := h ▸ by simp theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c := h ▸ by simp theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c := h ▸ by simp /-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) : tactic (instance_cache × expr) := match match_neg ea, match_neg eb, match_neg ec with | some ea, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c), ic.mk_app ``add_neg_neg [ea, eb, ec, p] | some ea, none, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a), ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p] | some ea, none, none := do (ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b, ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p] | none, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b), ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p] | none, some eb, none := do (ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a, ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p] | _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c end /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/ meta def prove_add_rat' (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_rat, nb ← b.to_rat, let nc := na + nb, (ic, c) ← ic.of_rat nc, (ic, p) ← prove_add_rat ic a b c na nb nc, return (ic, c, p) theorem clear_denom_simple_nat {α} [division_ring α] (a : α) : (1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩ theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) : b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩ /-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)` where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/ meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) : tactic (instance_cache × expr × expr × expr) := if na.denom = 1 then do (c, d) ← c.mk_app ``has_one.one [], (c, p) ← c.mk_app ``clear_denom_simple_nat [a], return (c, d, a, p) else do [α, _, a, b] ← return a.get_app_args, (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀], return (c, b, a, p) theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α) (ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b') (hc : c * d = c') (hd : d₁ * d₂ = d) (h : a' * b' = c') : a * b = c := mul_right_cancel' ha.1 $ mul_right_cancel' hb.1 $ by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a] /-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_mul_nat ic a b else do let nc := na * nb, (ic, c) ← ic.of_rat nc, (ic, d₁, a', pa) ← prove_clear_denom_simple ic a na, (ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb, (ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, _, p) ← prove_mul_nat ic a' b', (ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p], return (ic, c, p) theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb), (ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p], return (ic, c, p) | sum.inr ff, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, sum.inr ff := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | sum.inl a, sum.inr tt := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb, (ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb), (ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb end theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b := h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div] theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := inv_one theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a := by rw [one_div, inv_inv'] theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a := inv_eq_one_div _ theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a := by simp only [inv_eq_one_div, one_div_div] /-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/ meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr) | ic e n := match match_sign e with | sum.inl e := do (ic, e', p) ← prove_inv ic e (-n), (ic, r) ← ic.mk_app ``has_neg.neg [e'], (ic, p) ← ic.mk_app ``inv_neg [e, e', p], return (ic, r, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``inv_zero [], return (ic, e, p) | sum.inr tt := if n.num = 1 then if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_one [], return (ic, e, p) else do let e := e.app_arg, (ic, p) ← ic.mk_app ``inv_one_div [e], return (ic, e, p) else if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_div_one [e], e ← infer_type p, return (ic, e.app_arg, p) else do [_, _, a, b] ← return e.get_app_args, (ic, e') ← ic.mk_app ``has_div.div [b, a], (ic, p) ← ic.mk_app ``inv_div [a, b], return (ic, e', p) end theorem div_eq {α} [division_ring α] (a b b' c : α) (hb : b⁻¹ = b') (h : a * b' = c) : a / b = c := by rwa ← hb at h /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/ meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := do (ic, b', pb) ← prove_inv ic b nb, (ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹, (ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p], return (ic, c, p) /-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/ meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := match match_sign a with | sum.inl a := do (ic, p) ← ic.mk_app ``neg_neg [a], return (ic, a, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``neg_zero [], return (ic, a, p) | sum.inr tt := do (ic, a') ← ic.mk_app ``has_neg.neg [a], p ← mk_eq_refl a', return (ic, a', p) end theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c := by rwa ← hb at h theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c := by rwa sub_neg_eq_add /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := match match_sign b with | sum.inl b := do (ic, c, p) ← prove_add_rat' ic a b, (ic, p) ← ic.mk_app ``sub_neg [a, b, c, p], return (ic, c, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``sub_zero [a], return (ic, a, p) | sum.inr tt := do (ic, b', pb) ← prove_neg ic b, (ic, c, p) ← prove_add_rat' ic a b', (ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p], return (ic, c, p) end theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c := h ▸ nat.add_sub_cancel_left _ _ theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 := nat.sub_eq_zero_of_le $ h ▸ nat.le_add_right _ _ /-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) := do na ← a.to_nat, nb ← b.to_nat, if nb ≤ na then do (ic, c) ← ic.of_nat (na - nb), (ic, p) ← prove_add_nat ic b c a, return (c, `(sub_nat_pos).mk_app [a, b, c, p]) else do (ic, c) ← ic.of_nat (nb - na), (ic, p) ← prove_add_nat ic a c b, return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p]) /-- This is needed because when `a` and `b` are numerals lean is more likely to unfold them than unfold the instances in order to prove that `add_group_has_sub = int.has_sub`. -/ theorem int_sub_hack (a b c : ℤ) (h : @has_sub.sub ℤ add_group_has_sub a b = c) : a - b = c := h /-- Given `a : ℤ`, `b : ℤ` integral numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub_int (ic : instance_cache) (a b : expr) : tactic (expr × expr) := do (_, c, p) ← prove_sub ic a b, return (c, `(int_sub_hack).mk_app [a, b, c, p]) /-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals. Also handles nat subtraction. Does not do recursive simplification; that is, `1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level `simp` call in `norm_num.derive`. -/ meta def eval_field : expr → tactic (expr × expr) | `(%%e₁ + %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, let n₃ := n₁ + n₂, (c, e₃) ← c.of_rat n₃, (_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃, return (e₃, p) | `(%%e₁ * %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂ | `(- %%e) := do c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_neg c e | `(@has_sub.sub %%α %%inst %%a %%b) := do c ← mk_instance_cache α, if α = `(nat) then prove_sub_nat c a b else if inst = `(int.has_sub) then prove_sub_int c a b else prod.snd <$> prove_sub c a b | `(has_inv.inv %%e) := do n ← e.to_rat, c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_inv c e n | `(%%e₁ / %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_div c e₁ e₂ n₁ n₂ | _ := failed lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ) (h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c := h₂ ▸ by simp [pow_bit0, h] lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ) (h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c := by rw [← h₃, ← h₂]; simp [pow_bit1, h] section open match_numeral_result /-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/ meta def prove_pow (a : expr) (na : ℚ) : instance_cache → expr → tactic (instance_cache × expr × expr) | ic b := match match_numeral b with | zero := do (ic, p) ← ic.mk_app ``pow_zero [a], (ic, o) ← ic.mk_app ``has_one.one [], return (ic, o, p) | one := do (ic, p) ← ic.mk_app ``pow_one [a], return (ic, a, p) | bit0 b := do (ic, c', p) ← prove_pow ic b, nc' ← expr.to_rat c', (ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc', (ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂], return (ic, c, p) | bit1 b := do (ic, c₁, p) ← prove_pow ic b, nc₁ ← expr.to_rat c₁, (ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁, (ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na, (ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃], return (ic, c, p) | _ := failed end end /-- Evaluates expressions of the form `a ^ b`, `monoid.pow a b` or `nat.pow a b`. -/ meta def eval_pow : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, match m with | `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂ | _ := failed end | `(monoid.pow %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_pow e₁ n₁ c e₂ | _ := failed /-- Given `⊢ p`, returns `(true, ⊢ p = true)`. -/ meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk `(true) <$> mk_app ``eq_true_intro [p] /-- Given `⊢ ¬ p`, returns `(false, ⊢ p = false)`. -/ meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk `(false) <$> mk_app ``eq_false_intro [p] theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false := eq_false_intro $ not_not_intro rfl /-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/ meta def eval_ineq : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p else if n₁ = n₂ then do (_, p) ← c.mk_app ``lt_irrefl [e₁], false_intro p else do (c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'], false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (_, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else prove_le_rat c e₁ e₂ n₁ n₂, true_intro p else do (c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq | `(%%e₁ ≠ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁] else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p | _ := failed theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁ /-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral. (We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure that towers of successors coming from e.g. `induction` are a common case.) -/ meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr) | `(nat.succ %%a) := do (ic, n, b, p₁) ← prove_nat_succ a, let n' := n + 1, (ic, c) ← ic.of_nat n', (ic, p₂) ← prove_add_nat ic b `(1) c, return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂]) | e := do n ← e.to_nat, p ← mk_eq_refl e, return (ic, n, e, p) lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c := h₂ ▸ h ▸ int.div_neg _ _ lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c := (int.mod_neg _ _).trans h /-- Given `a`,`b` numerals in `nat` or `int`, * `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)` * `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)` -/ meta def prove_div_mod (ic : instance_cache) : expr → expr → bool → tactic (instance_cache × expr × expr) | a b mod := match match_neg b with | some b := do (ic, c', p) ← prove_div_mod a b mod, if mod then return (ic, c', `(int_mod_neg).mk_app [a, b, c', p]) else do (ic, c, p₂) ← prove_neg ic c', return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂]) | none := do nb ← b.to_nat, na ← a.to_int, let nq := na / nb, let nr := na % nb, let nm := nq * nr, (ic, q) ← ic.of_int nq, (ic, r) ← ic.of_int nr, (ic, m, pm) ← prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb), (ic, p) ← prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na), (ic, p') ← prove_lt_nat ic r b, if ic.α = `(nat) then if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p']) else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p']) else if ic.α = `(int) then do (ic, p₀) ← prove_nonneg ic r, if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p']) else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p']) else failed end theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂ theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂ /-- Evaluates some extra numeric operations on `nat` and `int`, specifically `nat.succ`, `/` and `%`, and `∣` (divisibility). -/ meta def eval_nat_int_ext : expr → tactic (expr × expr) | e@`(nat.succ _) := do ic ← mk_instance_cache `(ℕ), (_, _, ep) ← prove_nat_succ ic e, return ep | `(%%a / %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b ff | `(%%a % %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b tt | `(%%a ∣ %%b) := do α ← infer_type a, ic ← mk_instance_cache α, th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else if α = `(int) then return `(dvd_eq_int) else failed, (ic, c, p₁) ← prove_div_mod ic b a tt, (ic, z) ← ic.mk_app ``has_zero.zero [], (e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq, return (e', th.mk_app [a, b, c, e', p₁, p₂]) | _ := failed /-- This version of `derive` does not fail when the input is already a numeral -/ meta def derive.step (e : expr) : tactic (expr × expr) := eval_field e <|> eval_nat_int_ext e <|> eval_pow e <|> eval_ineq e /-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put `@[norm_num]` on a tactic of type `expr → tactic (expr × expr)`; the tactic will be called on subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`, `12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the original expression is equal to the rewritten expression. Failure is used to indicate that this tactic does not apply to the term. For performance reasons, it is best to detect non-applicability as soon as possible so that the next tactic can have a go, so generally it will start with a pattern match and then checking that the arguments to the term are numerals or of the appropriate form, followed by proof construction, which should not fail. Propositions are treated like any other term. The normal form for propositions is `true` or `false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be used to help here. -/ @[user_attribute] protected meta def attr : user_attribute (expr → tactic (expr × expr)) unit := { name := `norm_num, descr := "Add norm_num derivers", cache_cfg := { mk_cache := λ ns, do { t ← ns.mfoldl (λ (t : expr → tactic (expr × expr)) n, do t' ← eval_expr (expr → tactic (expr × expr)) (expr.const n []), pure (λ e, t' e <|> t e)) (λ _, failed), pure (λ e, derive.step e <|> t e) }, dependencies := [] } } add_tactic_doc { name := "norm_num", category := doc_category.attr, decl_names := [`norm_num.attr], tags := ["arithmetic", "decision_procedure"] } /-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with additional reduction procedures. -/ meta def get_step : tactic (expr → tactic (expr × expr)) := norm_num.attr.get_cache /-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/ meta def derive' (step : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | e := do e ← instantiate_mvars e, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← step e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) /-- Simplify an expression bottom-up using the default `norm_num` set to simplify the subexpressions. -/ meta def derive (e : expr) : tactic (expr × expr) := do f ← get_step, derive' f e end norm_num /-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num1 (step : expr → tactic (expr × expr)) (loc : interactive.loc) : tactic unit := do ns ← loc.get_locals, tt ← tactic.replace_at (norm_num.derive' step) ns loc.include_goal | fail "norm_num failed to simplify", when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num (step : expr → tactic (expr × expr)) (hs : list simp_arg_type) (l : interactive.loc) : tactic unit := repeat1 $ orelse' (tactic.norm_num1 step l) $ interactive.simp_core {} (tactic.norm_num1 step (interactive.loc.ns [none])) ff (simp_arg_type.except ``one_div :: hs) [] l namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do f ← get_step, tactic.norm_num1 f loc /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := do f ← get_step, tactic.norm_num f hs l add_hint_tactic "norm_num" /-- Normalizes a numerical expression and tries to close the goal with the result. -/ meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ /-- Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. ```lean import data.real.basic example : (2 : ℝ) + 2 = 4 := by norm_num example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num example : (73 : ℝ) < 789/2 := by norm_num example : 123456789 + 987654321 = 1111111110 := by norm_num example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num example : nat.prime (2^13 - 1) := by norm_num example : ¬ nat.prime (2^11 - 1) := by norm_num example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption ``` The variant `norm_num1` does not call `simp`. Both `norm_num` and `norm_num1` can be called inside the `conv` tactic. The tactic `apply_normed` normalises a numerical expression and tries to close the goal with the result. Compare: ```lean def a : ℕ := 2^100 #print a -- 2 ^ 100 def normed_a : ℕ := by apply_normed 2^100 #print normed_a -- 1267650600228229401496703205376 ``` -/ add_tactic_doc { name := "norm_num", category := doc_category.tactic, decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num, `tactic.interactive.apply_normed], tags := ["arithmetic", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive tactic.interactive open norm_num (derive) /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 : conv unit := replace_lhs derive /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) : conv unit := repeat1 $ orelse' norm_num1 $ conv.interactive.simp ff (simp_arg_type.except ``one_div :: hs) [] { discharger := tactic.interactive.norm_num1 (loc.ns [none]) } end conv.interactive
004161e21e17d04fdc5c689905d7ec8d24e5320c
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/real/ereal.lean
e36f4927492f1011db51ef20a9bbf1178b6d4db0
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,590
lean
/- Copyright (c) 2019 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import data.real.basic import data.real.ennreal /-! # The extended reals [-∞, ∞]. This file defines `ereal`, the real numbers together with a top and bottom element, referred to as ⊤ and ⊥. It is implemented as `with_top (with_bot ℝ)` Addition and multiplication are problematic in the presence of ±∞, but negation has a natural definition and satisfies the usual properties. An ad hoc addition is defined, for which `ereal` is an `add_comm_monoid`, and even an ordered one (if `a ≤ a'` and `b ≤ b'` then `a + b ≤ a' + b'`). Note however that addition is badly behaved at `(⊥, ⊤)` and `(⊤, ⊥)` so this can not be upgraded to a group structure. Our choice is that `⊥ + ⊤ = ⊤ + ⊥ = ⊤`. An ad hoc subtraction is then defined by `x - y = x + (-y)`. It does not have nice properties, but it is sometimes convenient to have. An ad hoc multiplication is defined, for which `ereal` is a `comm_monoid_with_zero`. This does not distribute with addition, as `⊤ = ⊤ - ⊥ = 1*⊤ - 1*⊤ ≠ (1 - 1) * ⊤ = 0 * ⊤ = 0`. `ereal` is a `complete_linear_order`; this is deduced by type class inference from the fact that `with_top (with_bot L)` is a complete linear order if `L` is a conditionally complete linear order. Coercions from `ℝ` and from `ℝ≥0∞` are registered, and their basic properties are proved. The main one is the real coercion, and is usually referred to just as `coe` (lemmas such as `ereal.coe_add` deal with this coercion). The one from `ennreal` is usually called `coe_ennreal` in the `ereal` namespace. ## Tags real, ereal, complete lattice ## TODO abs : ereal → ℝ≥0∞ In Isabelle they define + - * and / (making junk choices for things like -∞ + ∞) and then prove whatever bits of the ordered ring/field axioms still hold. They also do some limits stuff (liminf/limsup etc). See https://isabelle.in.tum.de/dist/library/HOL/HOL-Library/Extended_Real.html -/ open_locale ennreal nnreal /-- ereal : The type `[-∞, ∞]` -/ @[derive [order_bot, order_top, comm_monoid_with_zero, has_Sup, has_Inf, complete_linear_order, linear_ordered_add_comm_monoid_with_top]] def ereal := with_top (with_bot ℝ) /-- The canonical inclusion froms reals to ereals. Do not use directly: as this is registered as a coercion, use the coercion instead. -/ def real.to_ereal : ℝ → ereal := some ∘ some namespace ereal @[simp] lemma bot_lt_top : (⊥ : ereal) < ⊤ := with_top.coe_lt_top _ @[simp] lemma bot_ne_top : (⊥ : ereal) ≠ ⊤ := bot_lt_top.ne instance : has_coe ℝ ereal := ⟨real.to_ereal⟩ @[simp, norm_cast] protected lemma coe_le_coe_iff {x y : ℝ} : (x : ereal) ≤ (y : ereal) ↔ x ≤ y := by { unfold_coes, simp [real.to_ereal] } @[simp, norm_cast] protected lemma coe_lt_coe_iff {x y : ℝ} : (x : ereal) < (y : ereal) ↔ x < y := by { unfold_coes, simp [real.to_ereal] } @[simp, norm_cast] protected lemma coe_eq_coe_iff {x y : ℝ} : (x : ereal) = (y : ereal) ↔ x = y := by { unfold_coes, simp [real.to_ereal, option.some_inj] } /-- The canonical map from nonnegative extended reals to extended reals -/ def _root_.ennreal.to_ereal : ℝ≥0∞ → ereal | ⊤ := ⊤ | (some x) := x.1 instance has_coe_ennreal : has_coe ℝ≥0∞ ereal := ⟨ennreal.to_ereal⟩ instance : has_zero ereal := ⟨(0 : ℝ)⟩ instance : inhabited ereal := ⟨0⟩ /-- A recursor for `ereal` in terms of the coercion. A typical invocation looks like `induction x using ereal.rec`. Note that using `induction` directly will unfold `ereal` to `option` which is undesirable. When working in term mode, note that pattern matching can be used directly. -/ @[elab_as_eliminator] protected def rec {C : ereal → Sort*} (h_bot : C ⊥) (h_real : Π a : ℝ, C a) (h_top : C ⊤) : ∀ a : ereal, C a | ⊥ := h_bot | (a : ℝ) := h_real a | ⊤ := h_top /-! ### Real coercion -/ instance : can_lift ereal ℝ := { coe := coe, cond := λ r, r ≠ ⊤ ∧ r ≠ ⊥, prf := λ x hx, begin induction x using ereal.rec, { simpa using hx }, { simp }, { simpa using hx } end } /-- The map from extended reals to reals sending infinities to zero. -/ def to_real : ereal → ℝ | ⊥ := 0 | ⊤ := 0 | (x : ℝ) := x @[simp] lemma to_real_top : to_real ⊤ = 0 := rfl @[simp] lemma to_real_bot : to_real ⊥ = 0 := rfl @[simp] lemma to_real_zero : to_real 0 = 0 := rfl @[simp] lemma to_real_coe (x : ℝ) : to_real (x : ereal) = x := rfl @[simp] lemma bot_lt_coe (x : ℝ) : (⊥ : ereal) < x := by { apply with_top.coe_lt_coe.2, exact with_bot.bot_lt_coe _ } @[simp] lemma coe_ne_bot (x : ℝ) : (x : ereal) ≠ ⊥ := (bot_lt_coe x).ne' @[simp] lemma bot_ne_coe (x : ℝ) : (⊥ : ereal) ≠ x := (bot_lt_coe x).ne @[simp] lemma coe_lt_top (x : ℝ) : (x : ereal) < ⊤ := with_top.coe_lt_top _ @[simp] lemma coe_ne_top (x : ℝ) : (x : ereal) ≠ ⊤ := (coe_lt_top x).ne @[simp] lemma top_ne_coe (x : ℝ) : (⊤ : ereal) ≠ x := (coe_lt_top x).ne' @[simp] lemma bot_lt_zero : (⊥ : ereal) < 0 := bot_lt_coe 0 @[simp] lemma bot_ne_zero : (⊥ : ereal) ≠ 0 := (coe_ne_bot 0).symm @[simp] lemma zero_ne_bot : (0 : ereal) ≠ ⊥ := coe_ne_bot 0 @[simp] lemma zero_lt_top : (0 : ereal) < ⊤ := coe_lt_top 0 @[simp] lemma zero_ne_top : (0 : ereal) ≠ ⊤ := coe_ne_top 0 @[simp] lemma top_ne_zero : (⊤ : ereal) ≠ 0 := (coe_ne_top 0).symm @[simp, norm_cast] lemma coe_add (x y : ℝ) : ((x + y : ℝ) : ereal) = (x : ereal) + (y : ereal) := rfl @[simp] lemma coe_zero : ((0 : ℝ) : ereal) = 0 := rfl lemma to_real_le_to_real {x y : ereal} (h : x ≤ y) (hx : x ≠ ⊥) (hy : y ≠ ⊤) : x.to_real ≤ y.to_real := begin lift x to ℝ, lift y to ℝ, { simpa using h }, { simp [hy, ((bot_lt_iff_ne_bot.2 hx).trans_le h).ne'] }, { simp [hx, (h.trans_lt (lt_top_iff_ne_top.2 hy)).ne], }, end lemma coe_to_real {x : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) : (x.to_real : ereal) = x := begin induction x using ereal.rec, { simpa using h'x }, { refl }, { simpa using hx }, end lemma le_coe_to_real {x : ereal} (h : x ≠ ⊤) : x ≤ x.to_real := begin by_cases h' : x = ⊥, { simp only [h', bot_le] }, { simp only [le_refl, coe_to_real h h'] }, end lemma coe_to_real_le {x : ereal} (h : x ≠ ⊥) : ↑x.to_real ≤ x := begin by_cases h' : x = ⊤, { simp only [h', le_top] }, { simp only [le_refl, coe_to_real h' h] }, end lemma eq_top_iff_forall_lt (x : ereal) : x = ⊤ ↔ ∀ (y : ℝ), (y : ereal) < x := begin split, { rintro rfl, exact ereal.coe_lt_top }, { contrapose!, intro h, exact ⟨x.to_real, le_coe_to_real h⟩, }, end lemma eq_bot_iff_forall_lt (x : ereal) : x = ⊥ ↔ ∀ (y : ℝ), x < (y : ereal) := begin split, { rintro rfl, exact bot_lt_coe }, { contrapose!, intro h, exact ⟨x.to_real, coe_to_real_le h⟩, }, end /-! ### ennreal coercion -/ @[simp] lemma to_real_coe_ennreal : ∀ {x : ℝ≥0∞}, to_real (x : ereal) = ennreal.to_real x | ⊤ := rfl | (some x) := rfl lemma coe_nnreal_eq_coe_real (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) = (x : ℝ) := rfl @[simp] lemma coe_ennreal_top : ((⊤ : ℝ≥0∞) : ereal) = ⊤ := rfl @[simp] lemma coe_ennreal_eq_top_iff : ∀ {x : ℝ≥0∞}, (x : ereal) = ⊤ ↔ x = ⊤ | ⊤ := by simp | (some x) := by { simp only [ennreal.coe_ne_top, iff_false, ennreal.some_eq_coe], dec_trivial } lemma coe_nnreal_ne_top (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) ≠ ⊤ := dec_trivial @[simp] lemma coe_nnreal_lt_top (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) < ⊤ := dec_trivial @[simp, norm_cast] lemma coe_ennreal_le_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) ≤ (y : ereal) ↔ x ≤ y | x ⊤ := by simp | ⊤ (some y) := by simp | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] @[simp, norm_cast] lemma coe_ennreal_lt_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) < (y : ereal) ↔ x < y | ⊤ ⊤ := by simp | (some x) ⊤ := by simp | ⊤ (some y) := by simp | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] @[simp, norm_cast] lemma coe_ennreal_eq_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) = (y : ereal) ↔ x = y | ⊤ ⊤ := by simp | (some x) ⊤ := by simp | ⊤ (some y) := by simp [(coe_nnreal_lt_top y).ne'] | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] lemma coe_ennreal_nonneg (x : ℝ≥0∞) : (0 : ereal) ≤ x := coe_ennreal_le_coe_ennreal_iff.2 (zero_le x) @[simp] lemma bot_lt_coe_ennreal (x : ℝ≥0∞) : (⊥ : ereal) < x := (bot_lt_coe 0).trans_le (coe_ennreal_nonneg _) @[simp] lemma coe_ennreal_ne_bot (x : ℝ≥0∞) : (x : ereal) ≠ ⊥ := (bot_lt_coe_ennreal x).ne' @[simp, norm_cast] lemma coe_ennreal_add : ∀ (x y : ennreal), ((x + y : ℝ≥0∞) : ereal) = x + y | ⊤ y := rfl | x ⊤ := by simp | (some x) (some y) := rfl @[simp] lemma coe_ennreal_zero : ((0 : ℝ≥0∞) : ereal) = 0 := rfl /-! ### Order -/ lemma exists_rat_btwn_of_lt : Π {a b : ereal} (hab : a < b), ∃ (x : ℚ), a < (x : ℝ) ∧ ((x : ℝ) : ereal) < b | ⊤ b h := (not_top_lt h).elim | (a : ℝ) ⊥ h := (lt_irrefl _ ((bot_lt_coe a).trans h)).elim | (a : ℝ) (b : ℝ) h := by simp [exists_rat_btwn (ereal.coe_lt_coe_iff.1 h)] | (a : ℝ) ⊤ h := let ⟨b, hab⟩ := exists_rat_gt a in ⟨b, by simpa using hab, coe_lt_top _⟩ | ⊥ ⊥ h := (lt_irrefl _ h).elim | ⊥ (a : ℝ) h := let ⟨b, hab⟩ := exists_rat_lt a in ⟨b, bot_lt_coe _, by simpa using hab⟩ | ⊥ ⊤ h := ⟨0, bot_lt_coe _, coe_lt_top _⟩ lemma lt_iff_exists_rat_btwn {a b : ereal} : a < b ↔ ∃ (x : ℚ), a < (x : ℝ) ∧ ((x : ℝ) : ereal) < b := ⟨λ hab, exists_rat_btwn_of_lt hab, λ ⟨x, ax, xb⟩, ax.trans xb⟩ lemma lt_iff_exists_real_btwn {a b : ereal} : a < b ↔ ∃ (x : ℝ), a < x ∧ (x : ereal) < b := ⟨λ hab, let ⟨x, ax, xb⟩ := exists_rat_btwn_of_lt hab in ⟨(x : ℝ), ax, xb⟩, λ ⟨x, ax, xb⟩, ax.trans xb⟩ /-- The set of numbers in `ereal` that are not equal to `±∞` is equivalent to `ℝ`. -/ def ne_top_bot_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ ℝ := { to_fun := λ x, ereal.to_real x, inv_fun := λ x, ⟨x, by simp⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ begin lift x to ℝ, { simp }, { simpa [not_or_distrib, and_comm] using hx } end, right_inv := λ x, by simp } /-! ### Addition -/ @[simp] lemma add_top (x : ereal) : x + ⊤ = ⊤ := add_top _ @[simp] lemma top_add (x : ereal) : ⊤ + x = ⊤ := top_add _ @[simp] lemma bot_add_bot : (⊥ : ereal) + ⊥ = ⊥ := rfl @[simp] lemma bot_add_coe (x : ℝ) : (⊥ : ereal) + x = ⊥ := rfl @[simp] lemma coe_add_bot (x : ℝ) : (x : ereal) + ⊥ = ⊥ := rfl lemma to_real_add : ∀ {x y : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥), to_real (x + y) = to_real x + to_real y | ⊥ y hx h'x hy h'y := (h'x rfl).elim | ⊤ y hx h'x hy h'y := (hx rfl).elim | x ⊤ hx h'x hy h'y := (hy rfl).elim | x ⊥ hx h'x hy h'y := (h'y rfl).elim | (x : ℝ) (y : ℝ) hx h'x hy h'y := by simp [← ereal.coe_add] lemma add_lt_add_right_coe {x y : ereal} (h : x < y) (z : ℝ) : x + z < y + z := begin induction x using ereal.rec; induction y using ereal.rec, { exact (lt_irrefl _ h).elim }, { simp only [bot_lt_coe, bot_add_coe, ← coe_add] }, { simp }, { exact (lt_irrefl _ (h.trans (bot_lt_coe x))).elim }, { norm_cast at h ⊢, exact add_lt_add_right h _ }, { simp only [← coe_add, top_add, coe_lt_top] }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, end lemma add_lt_add_of_lt_of_le {x y z t : ereal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥) (ht : t ≠ ⊤) : x + z < y + t := begin induction z using ereal.rec, { simpa only using hz }, { calc x + z < y + z : add_lt_add_right_coe h _ ... ≤ y + t : add_le_add (le_refl _) h' }, { exact (ht (top_le_iff.1 h')).elim } end lemma add_lt_add_left_coe {x y : ereal} (h : x < y) (z : ℝ) : (z : ereal) + x < z + y := by simpa [add_comm] using add_lt_add_right_coe h z lemma add_lt_add {x y z t : ereal} (h1 : x < y) (h2 : z < t) : x + z < y + t := begin induction y using ereal.rec, { exact (lt_irrefl _ (bot_le.trans_lt h1)).elim }, { calc x + z ≤ y + z : add_le_add h1.le (le_refl _) ... < y + t : add_lt_add_left_coe h2 _ }, { simp [lt_top_iff_ne_top, with_top.add_eq_top, h1.ne, (h2.trans_le le_top).ne] } end @[simp] lemma add_eq_top_iff {x y : ereal} : x + y = ⊤ ↔ x = ⊤ ∨ y = ⊤ := begin induction x using ereal.rec; induction y using ereal.rec; simp [← ereal.coe_add], end @[simp] lemma add_lt_top_iff {x y : ereal} : x + y < ⊤ ↔ x < ⊤ ∧ y < ⊤ := by simp [lt_top_iff_ne_top, not_or_distrib] /-! ### Negation -/ /-- negation on `ereal` -/ protected def neg : ereal → ereal | ⊥ := ⊤ | ⊤ := ⊥ | (x : ℝ) := (-x : ℝ) instance : has_neg ereal := ⟨ereal.neg⟩ @[norm_cast] protected lemma neg_def (x : ℝ) : ((-x : ℝ) : ereal) = -x := rfl @[simp] lemma neg_top : - (⊤ : ereal) = ⊥ := rfl @[simp] lemma neg_bot : - (⊥ : ereal) = ⊤ := rfl @[simp] lemma neg_zero : - (0 : ereal) = 0 := by { change ((-0 : ℝ) : ereal) = 0, simp } /-- `- -a = a` on `ereal`. -/ @[simp] protected theorem neg_neg : ∀ (a : ereal), - (- a) = a | ⊥ := rfl | ⊤ := rfl | (a : ℝ) := by { norm_cast, simp [neg_neg a] } theorem neg_inj {a b : ereal} (h : -a = -b) : a = b := by rw [←ereal.neg_neg a, h, ereal.neg_neg b] @[simp] theorem neg_eq_neg_iff (a b : ereal) : - a = - b ↔ a = b := ⟨λ h, neg_inj h, λ h, by rw [h]⟩ @[simp] lemma to_real_neg : ∀ {a : ereal}, to_real (-a) = - to_real a | ⊤ := by simp | ⊥ := by simp | (x : ℝ) := rfl /-- Even though `ereal` is not an additive group, `-a = b ↔ -b = a` still holds -/ theorem neg_eq_iff_neg_eq {a b : ereal} : -a = b ↔ -b = a := ⟨by {intro h, rw ←h, exact ereal.neg_neg a}, by {intro h, rw ←h, exact ereal.neg_neg b}⟩ @[simp] lemma neg_eg_top_iff {x : ereal} : - x = ⊤ ↔ x = ⊥ := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } @[simp] lemma neg_eg_bot_iff {x : ereal} : - x = ⊥ ↔ x = ⊤ := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } @[simp] lemma neg_eg_zero_iff {x : ereal} : - x = 0 ↔ x = 0 := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } /-- if `-a ≤ b` then `-b ≤ a` on `ereal`. -/ protected theorem neg_le_of_neg_le : ∀ {a b : ereal} (h : -a ≤ b), -b ≤ a | ⊥ ⊥ h := h | ⊥ (some b) h := by cases (top_le_iff.1 h) | ⊤ l h := le_top | (a : ℝ) ⊥ h := by cases (le_bot_iff.1 h) | l ⊤ h := bot_le | (a : ℝ) (b : ℝ) h := by { norm_cast at h ⊢, exact _root_.neg_le_of_neg_le h } /-- `-a ≤ b ↔ -b ≤ a` on `ereal`. -/ protected theorem neg_le {a b : ereal} : -a ≤ b ↔ -b ≤ a := ⟨ereal.neg_le_of_neg_le, ereal.neg_le_of_neg_le⟩ /-- `a ≤ -b → b ≤ -a` on ereal -/ theorem le_neg_of_le_neg {a b : ereal} (h : a ≤ -b) : b ≤ -a := by rwa [←ereal.neg_neg b, ereal.neg_le, ereal.neg_neg] @[simp] lemma neg_le_neg_iff {a b : ereal} : - a ≤ - b ↔ b ≤ a := by conv_lhs { rw [ereal.neg_le, ereal.neg_neg] } @[simp, norm_cast] lemma coe_neg (x : ℝ) : ((- x : ℝ) : ereal) = - (x : ereal) := rfl /-- Negation as an order reversing isomorphism on `ereal`. -/ def neg_order_iso : ereal ≃o (order_dual ereal) := { to_fun := ereal.neg, inv_fun := ereal.neg, left_inv := ereal.neg_neg, right_inv := ereal.neg_neg, map_rel_iff' := λ x y, neg_le_neg_iff } lemma neg_lt_of_neg_lt {a b : ereal} (h : -a < b) : -b < a := begin apply lt_of_le_of_ne (ereal.neg_le_of_neg_le h.le), assume H, rw [← H, ereal.neg_neg] at h, exact lt_irrefl _ h end lemma neg_lt_iff_neg_lt {a b : ereal} : -a < b ↔ -b < a := ⟨λ h, ereal.neg_lt_of_neg_lt h, λ h, ereal.neg_lt_of_neg_lt h⟩ /-! ### Subtraction -/ /-- Subtraction on `ereal`, defined by `x - y = x + (-y)`. Since addition is badly behaved at some points, so is subtraction. There is no standard algebraic typeclass involving subtraction that is registered on `ereal` because of this bad behavior. -/ protected noncomputable def sub (x y : ereal) : ereal := x + (-y) noncomputable instance : has_sub ereal := ⟨ereal.sub⟩ @[simp] lemma top_sub (x : ereal) : ⊤ - x = ⊤ := top_add x @[simp] lemma sub_bot (x : ereal) : x - ⊥ = ⊤ := add_top x @[simp] lemma bot_sub_top : (⊥ : ereal) - ⊤ = ⊥ := rfl @[simp] lemma bot_sub_coe (x : ℝ) : (⊥ : ereal) - x = ⊥ := rfl @[simp] lemma coe_sub_bot (x : ℝ) : (x : ereal) - ⊤ = ⊥ := rfl @[simp] lemma sub_zero (x : ereal) : x - 0 = x := by { change x + (-0) = x, simp } @[simp] lemma zero_sub (x : ereal) : 0 - x = - x := by { change 0 + (-x) = - x, simp } lemma sub_eq_add_neg (x y : ereal) : x - y = x + -y := rfl lemma sub_le_sub {x y z t : ereal} (h : x ≤ y) (h' : t ≤ z) : x - z ≤ y - t := add_le_add h (neg_le_neg_iff.2 h') lemma sub_lt_sub_of_lt_of_le {x y z t : ereal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥) (ht : t ≠ ⊤) : x - t < y - z := add_lt_add_of_lt_of_le h (neg_le_neg_iff.2 h') (by simp [ht]) (by simp [hz]) lemma coe_real_ereal_eq_coe_to_nnreal_sub_coe_to_nnreal (x : ℝ) : (x : ereal) = real.to_nnreal x - real.to_nnreal (-x) := begin rcases le_or_lt 0 x with h|h, { have : real.to_nnreal x = ⟨x, h⟩, by { ext, simp [h] }, simp only [real.to_nnreal_of_nonpos (neg_nonpos.mpr h), this, sub_zero, ennreal.coe_zero, coe_ennreal_zero, coe_coe], refl }, { have : (x : ereal) = - (- x : ℝ), by simp, conv_lhs { rw this }, have : real.to_nnreal (-x) = ⟨-x, neg_nonneg.mpr h.le⟩, by { ext, simp [neg_nonneg.mpr h.le], }, simp only [real.to_nnreal_of_nonpos h.le, this, zero_sub, neg_eq_neg_iff, coe_neg, ennreal.coe_zero, coe_ennreal_zero, coe_coe], refl } end lemma to_real_sub {x y : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥) : to_real (x - y) = to_real x - to_real y := begin rw [ereal.sub_eq_add_neg, to_real_add hx h'x, to_real_neg], { refl }, { simpa using hy }, { simpa using h'y } end /-! ### Multiplication -/ @[simp] lemma coe_one : ((1 : ℝ) : ereal) = 1 := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ) : ((x * y : ℝ) : ereal) = (x : ereal) * (y : ereal) := eq.trans (with_bot.coe_eq_coe.mpr with_bot.coe_mul) with_top.coe_mul @[simp] lemma mul_top (x : ereal) (h : x ≠ 0) : x * ⊤ = ⊤ := with_top.mul_top h @[simp] lemma top_mul (x : ereal) (h : x ≠ 0) : ⊤ * x = ⊤ := with_top.top_mul h @[simp] lemma bot_mul_bot : (⊥ : ereal) * ⊥ = ⊥ := rfl @[simp] lemma bot_mul_coe (x : ℝ) (h : x ≠ 0) : (⊥ : ereal) * x = ⊥ := with_top.coe_mul.symm.trans $ with_bot.coe_eq_coe.mpr $ with_bot.bot_mul $ function.injective.ne (@option.some.inj _) h @[simp] lemma coe_mul_bot (x : ℝ) (h : x ≠ 0) : (x : ereal) * ⊥ = ⊥ := with_top.coe_mul.symm.trans $ with_bot.coe_eq_coe.mpr $ with_bot.mul_bot $ function.injective.ne (@option.some.inj _) h @[simp] lemma to_real_one : to_real 1 = 1 := rfl lemma to_real_mul : ∀ {x y : ereal}, to_real (x * y) = to_real x * to_real y | ⊤ y := by by_cases hy : y = 0; simp [hy] | x ⊤ := by by_cases hx : x = 0; simp [hx] | (x : ℝ) (y : ℝ) := by simp [← ereal.coe_mul] | ⊥ (y : ℝ) := by by_cases hy : y = 0; simp [hy] | (x : ℝ) ⊥ := by by_cases hx : x = 0; simp [hx] | ⊥ ⊥ := by simp end ereal
41565bc09dd50c3ff19ac969472a109d7ab58f88
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Compiler/LCNF/Specialize.lean
0973ff9099384d966449e9d59ef51d36698f2400
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
17,779
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Compiler.Specialize import Lean.Compiler.LCNF.Simp import Lean.Compiler.LCNF.SpecInfo import Lean.Compiler.LCNF.PrettyPrinter import Lean.Compiler.LCNF.ToExpr import Lean.Compiler.LCNF.Level import Lean.Compiler.LCNF.PhaseExt namespace Lean.Compiler.LCNF namespace Specialize abbrev Cache := PHashMap Expr Name builtin_initialize specCacheExt : EnvExtension Cache ← registerEnvExtension (pure {}) def cacheSpec (key : Expr) (declName : Name) : CoreM Unit := modifyEnv fun env => specCacheExt.modifyState env (·.insert key declName) def findSpecCache? (key : Expr) : CoreM (Option Name) := return specCacheExt.getState (← getEnv) |>.find? key structure Context where /-- Set of free variables in scope. The "collector" uses this information when collecting dependencies for code specialization. -/ scope : FVarIdSet := {} /-- Set of let-declarations in scope that do not depend on parameters. -/ ground : FVarIdSet := {} /-- Name of the declaration being processed -/ declName : Name structure State where decls : Array Decl := #[] abbrev SpecializeM := ReaderT Context $ StateRefT State CompilerM @[inline] def withParams (ps : Array Param) (x : SpecializeM α) : SpecializeM α := withReader (fun ctx => { ctx with scope := ps.foldl (init := ctx.scope) fun s p => s.insert p.fvarId }) x @[inline] def withFVar (fvarId : FVarId) (x : SpecializeM α) : SpecializeM α := withReader (fun ctx => { ctx with scope := ctx.scope.insert fvarId }) x /-- Return `true` if `e` is a ground term. That is, it contains only free variables t -/ def isGround (e : Expr) : SpecializeM Bool := do let s := (← read).ground return !e.hasAnyFVar (!s.contains ·) @[inline] def withLetDecl (decl : LetDecl) (x : SpecializeM α) : SpecializeM α := do let grd ← isGround decl.value let fvarId := decl.fvarId withReader (fun { scope, ground, declName } => { declName, scope := scope.insert fvarId, ground := if grd then ground.insert fvarId else ground }) x namespace Collector /-! # Dependency collector for the code specialization function. During code specialization, we select which arguments are going to be used during the specialization. Then, we have to collect their dependencies. For example, suppose are trying to specialize the following `IO.println` and `List.forM` applications in the following example: ``` def f xs a.1 := let _x.2 := @instMonadEIO IO.Error let _x.5 := instToStringString let _x.9 := instToStringNat let _x.6 := "hello" let _x.61 := @IO.println String _x.5 _x.6 a.1 -- (*) cases _x.61 | EStateM.Result.ok a.6 a.7 => fun _f.72 _y.69 _y.70 := let _x.71 := @IO.println Nat _x.9 _y.69 _y.70 -- (*) _x.71 let _x.65 := @List.forM (fun α => PUnit → EStateM.Result IO.Error PUnit α) _x.2 Nat xs _f.72 a.7 -- (*) ... ... ``` For `IO.println` the `SpecArgInfo` is `[N, I, O, O]`, i.e., only the first two arguments are considered for code specialization. The first one is computationally neutral, and the second one is an instance. For `List.forM`, we have `[N, I, N, O, H]`. In this case, the fifth argument (tagged as `H`) is a function. Note that the actual `List.forM` application has 6 arguments, the extra argument comes from the `IO` monad. For the first `IO.println` application, the collector collects `_x.5`. For the `List.forM`, it collects `_x.2`, `_x.9`, and `_f.72`. The collected values are used to construct a key to identify the specialization. Arguments that were not considered are replaced with `lcErased`. The key is used to make sure we don't keep generating the same specialization over and over again. This is not an optimization, it is essential to prevent the code specializer from looping while specializing recursive functions. The keys for these two applications are the terms. ``` @IO.println Nat instToStringNat lcErased lcErased ``` and ``` @List.forM (fun α => PUnit → EStateM.Result IO.Error PUnit α) (@instMonadEIO IO.Error) Nat lcErased (fun _y.69 _y.70 => let _x.71 := @IO.println Nat instToStringNat _y.69 _y.70; _x.71) ``` The keys never contain free variables or loose bound variables. -/ /-- State for the `CollectorM` monad. -/ structure State where /-- Set of already visited free variables. -/ visited : FVarIdSet := {} /-- Free variables that must become new parameters of the code being specialized. -/ params : Array Param := #[] /-- Let-declarations and local function declarations that are going to be "copied" to the code being specialized. For example, the let-declarations often contain the instance values. In the current specialization heuristic all let-declarations are ground values (i.e., they do not contain free-variables). However, local function declarations may contain free variables. The current heuristic tries to avoid work duplication. If a let-declaration is a ground value, it most likely will be computed during compilation time, and work duplication is not an issue. -/ decls : Array CodeDecl := #[] /-- Monad for implementing the code specializer dependency collector. See `collect` -/ abbrev CollectorM := StateRefT State SpecializeM /-- Mark a free variable as already visited. We perform a topological sort over the dependencies. -/ def markVisited (fvarId : FVarId) : CollectorM Unit := modify fun s => { s with visited := s.visited.insert fvarId } mutual /-- Collect dependencies in parameters. We need this because parameters may contain other type parameters. -/ partial def collectParams (params : Array Param) : CollectorM Unit := params.forM (collectExpr ·.type) /-- Collect dependencies in the given code. We need this function to be able to collect dependencies in a local function declaration. -/ partial def collectCode (c : Code) : CollectorM Unit := do match c with | .let decl k => collectExpr decl.type; collectExpr decl.value; collectCode k | .fun decl k | .jp decl k => collectFunDecl decl; collectCode k | .cases c => collectExpr c.resultType collectFVar c.discr c.alts.forM fun alt => do match alt with | .default k => collectCode k | .alt _ ps k => collectParams ps; collectCode k | .jmp _ args => args.forM collectExpr | .unreach type => collectExpr type | .return fvarId => collectFVar fvarId /-- Collect dependencies of a local function declaration. -/ partial def collectFunDecl (decl : FunDecl) : CollectorM Unit := do collectExpr decl.type collectParams decl.params collectCode decl.value /-- Process the given free variable. If it has not already been visited and is in scope, we collect its dependencies. -/ partial def collectFVar (fvarId : FVarId) : CollectorM Unit := do unless (← get).visited.contains fvarId do markVisited fvarId if (← read).scope.contains fvarId then /- We only collect the variables in the scope of the function application being specialized. -/ if let some funDecl ← findFunDecl? fvarId then collectFunDecl funDecl modify fun s => { s with decls := s.decls.push <| .fun funDecl } else if let some param ← findParam? fvarId then collectExpr param.type modify fun s => { s with params := s.params.push param } else if let some letDecl ← findLetDecl? fvarId then collectExpr letDecl.type if (← isGround letDecl.value) then -- It is a ground value, thus we keep collecting dependencies collectExpr letDecl.value modify fun s => { s with decls := s.decls.push <| .let letDecl } else -- It is not a ground value, we convert declaration into a parameter modify fun s => { s with params := s.params.push <| { letDecl with borrow := false } } else unreachable! /-- Collect dependencies of the given expression. -/ partial def collectExpr (e : Expr) : CollectorM Unit := do e.forEach fun e => do match e with | .fvar fvarId => collectFVar fvarId | _ => pure () end /-- Given the specialization mask `paramsInfo` and the arguments `args`, collect their dependencies, and return an array `mask` of size `paramsInfo.size` s.t. - `mask[i] = some args[i]` if `paramsInfo[i] != .other` - `mask[i] = none`, otherwise. That is, `mask` contains only the arguments that are contributing to the code specialization. We use this information to compute a "key" to uniquely identify the code specialization, and creating the specialized code. -/ def collect (paramsInfo : Array SpecParamInfo) (args : Array Expr) : CollectorM (Array (Option Expr)) := do let mut argMask := #[] for paramInfo in paramsInfo, arg in args do match paramInfo with | .other => argMask := argMask.push none | .fixedNeutral | .user | .fixedInst | .fixedHO => argMask := argMask.push (some arg) collectExpr arg return argMask end Collector /-- Return `true` if it is worth using arguments `args` for specialization given the parameter specialization information. -/ def shouldSpecialize (paramsInfo : Array SpecParamInfo) (args : Array Expr) : SpecializeM Bool := do for paramInfo in paramsInfo, arg in args do match paramInfo with | .other => pure () | .fixedNeutral => pure () -- If we want to monomorphize types such as `Array`, we need to change here | .fixedInst | .user => if (← isGround arg) then return true | .fixedHO => return true -- TODO: check whether this is too aggressive return false /-- Convert the given declarations into `Expr`, and "zeta-reduce" them into body. This function is used to compute the key that uniquely identifies an code specialization. -/ def expandCodeDecls (decls : Array CodeDecl) (body : Expr) : CompilerM Expr := do let xs := decls.map (mkFVar ·.fvarId) let values := decls.map fun | .let decl => decl.value | .fun decl | .jp decl => decl.toExpr let rec go (i : Nat) (subst : Array Expr) : Expr := if h : i < values.size then let value := values[i].abstractRange i xs let value := value.instantiateRev subst go (i+1) (subst.push value) else (body.abstract xs).instantiateRev subst return go 0 #[] termination_by go => values.size - i /-- Create the "key" that uniquely identifies a code specialization. `params` and `decls` are the declarations collected by the `collect` function above. The result contains the list of universe level parameter names the key that `params`, `decls`, and `body` depends on. We use this information to create the new auxiliary declaration and resulting application. -/ def mkKey (params : Array Param) (decls : Array CodeDecl) (body : Expr) : CompilerM (Expr × List Name) := do let body ← expandCodeDecls decls body let key := ToExpr.run do ToExpr.withParams params do ToExpr.mkLambdaM params (← ToExpr.abstractM body) return normLevelParams key open Internalize in /-- Specialize `decl` using - `us`: the universe level used to instantiate `decl.name` - `argMask`: arguments that are being used to specialize the declaration. - `params`: new parameters that arguments in `argMask` depend on. - `decls`: local declarations that arguments in `argMask` depend on. - `levelParamsNew`: the universe level parameters for the new declaration. -/ def mkSpecDecl (decl : Decl) (us : List Level) (argMask : Array (Option Expr)) (params : Array Param) (decls : Array CodeDecl) (levelParamsNew : List Name) : SpecializeM Decl := do let nameNew := decl.name ++ `_at_ ++ (← read).declName ++ (`spec).appendIndexAfter (← get).decls.size /- Recall that we have just retrieved `decl` using `getDecl?`, and it may have free variable identifiers that overlap with the free-variables in `params` and `decls` (i.e., the "closure"). Recall that `params` and `decls` are internalized, but `decl` is not. Thus, we internalize `decl` before glueing these "pieces" together. We erase the internalized information after we are done. -/ let decl ← decl.internalize try go decl nameNew |>.run' {} finally eraseDecl decl where go (decl : Decl) (nameNew : Name) : InternalizeM Decl := do let mut params ← params.mapM internalizeParam let decls ← decls.mapM internalizeCodeDecl for param in decl.params, arg in argMask do if let some arg := arg then let arg ← normExpr arg modify fun s => s.insert param.fvarId arg else -- Keep the parameter let param := { param with type := param.type.instantiateLevelParams decl.levelParams us } params := params.push (← internalizeParam param) for param in decl.params[argMask.size:] do let param := { param with type := param.type.instantiateLevelParams decl.levelParams us } params := params.push (← internalizeParam param) let value := decl.instantiateValueLevelParams us let value ← internalizeCode value let value := attachCodeDecls decls value let type ← value.inferType let type ← mkForallParams params type let safe := decl.safe let recursive := decl.recursive let decl := { name := nameNew, levelParams := levelParamsNew, params, type, value, safe, recursive : Decl } return decl.setLevelParams /-- Given the specialization mask `paramsInfo` and the arguments `args`, return the arguments that have not been considered for specialization. -/ def getRemainingArgs (paramsInfo : Array SpecParamInfo) (args : Array Expr) : Array Expr := Id.run do let mut result := #[] for info in paramsInfo, arg in args do if info matches .other then result := result.push arg return result ++ args[paramsInfo.size:] mutual /-- Try to specialize the function application in the given let-declaration. `k` is the continuation for the let-declaration. -/ partial def specializeApp? (e : Expr) : SpecializeM (Option Expr) := do unless e.isApp do return none let f := e.getAppFn let .const declName us := f | return none if (← Meta.isInstance declName) then return none let some paramsInfo ← getSpecParamInfo? declName | return none let args := e.getAppArgs unless (← shouldSpecialize paramsInfo args) do return none let some decl ← getDecl? declName | return none trace[Compiler.specialize.candidate] "{e}, {paramsInfo}" let (argMask, { params, decls, .. }) ← Collector.collect paramsInfo args |>.run {} let keyBody := mkAppN f (argMask.filterMap id) let (key, levelParamsNew) ← mkKey params decls keyBody trace[Compiler.specialize.candidate] "key: {key}" assert! !key.hasLooseBVars assert! !key.hasFVar let usNew := levelParamsNew.map mkLevelParam let argsNew := params.map (mkFVar ·.fvarId) ++ getRemainingArgs paramsInfo args if let some declName ← findSpecCache? key then trace[Compiler.specialize.step] "cached: {declName}" return mkAppN (.const declName usNew) argsNew else let specDecl ← mkSpecDecl decl us argMask params decls levelParamsNew trace[Compiler.specialize.step] "new: {specDecl.name}" cacheSpec key specDecl.name specDecl.saveBase let specDecl ← specDecl.etaExpand specDecl.saveBase let specDecl ← specDecl.simp {} let specDecl ← specDecl.simp { etaPoly := true, inlinePartial := true, implementedBy := true } let value ← withReader (fun _ => { declName := specDecl.name }) do withParams specDecl.params <| visitCode specDecl.value let specDecl := { specDecl with value } modify fun s => { s with decls := s.decls.push specDecl } return mkAppN (.const specDecl.name usNew) argsNew partial def visitFunDecl (funDecl : FunDecl) : SpecializeM FunDecl := do let value ← withParams funDecl.params <| visitCode funDecl.value funDecl.update' funDecl.type value partial def visitCode (code : Code) : SpecializeM Code := do match code with | .let decl k => let mut decl := decl if let some value ← specializeApp? decl.value then decl ← decl.updateValue value let k ← withLetDecl decl <| visitCode k return code.updateLet! decl k | .fun decl k | .jp decl k => let decl ← visitFunDecl decl let k ← withFVar decl.fvarId <| visitCode k return code.updateFun! decl k | .cases c => let alts ← c.alts.mapMonoM fun alt => match alt with | .default k => return alt.updateCode (← visitCode k) | .alt _ ps k => withParams ps do return alt.updateCode (← visitCode k) return code.updateAlts! alts | .unreach .. | .jmp .. | .return .. => return code end def main (decl : Decl) : SpecializeM Decl := do if (← decl.isTemplateLike) then return decl else let value ← withParams decl.params <| visitCode decl.value return { decl with value } end Specialize partial def Decl.specialize (decl : Decl) : CompilerM (Array Decl) := do let (decl, s) ← Specialize.main decl |>.run { declName := decl.name } |>.run {} return s.decls.push decl def specialize : Pass where phase := .base name := `specialize run := fun decls => do saveSpecParamInfo decls decls.foldlM (init := #[]) fun decls decl => return decls ++ (← decl.specialize) builtin_initialize registerTraceClass `Compiler.specialize (inherited := true) registerTraceClass `Compiler.specialize.candidate registerTraceClass `Compiler.specialize.step end Lean.Compiler.LCNF
37a12f696bcbc0a57d91473216c9ff6bb04e348d
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/adjoin_root.lean
d3d24d4c9c20e4283a703b3cb69f212739d3bf82
[ "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,718
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial.field_division import linear_algebra.finite_dimensional import ring_theory.adjoin.basic import ring_theory.power_basis import ring_theory.principal_ideal_domain /-! # Adjoining roots of polynomials This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is irreducible, the field structure on `adjoin_root f` is constructed. ## Main definitions and results The main definitions are in the `adjoin_root` namespace. * `mk f : polynomial R →+* adjoin_root f`, the natural ring homomorphism. * `of f : R →+* adjoin_root f`, the natural ring homomorphism. * `root f : adjoin_root f`, the image of X in R[X]/(f). * `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`. * `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x` * `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S` -/ noncomputable theory open_locale classical open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {K : Type w} open polynomial ideal /-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring as the quotient of `R` by the principal ideal of `f`. -/ def adjoin_root [comm_ring R] (f : polynomial R) : Type u := ideal.quotient (span {f} : ideal (polynomial R)) namespace adjoin_root section comm_ring variables [comm_ring R] (f : polynomial R) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : inhabited (adjoin_root f) := ⟨0⟩ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ /-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/ def mk : polynomial R →+* adjoin_root f := ideal.quotient.mk _ @[elab_as_eliminator] theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f) (ih : ∀ p : polynomial R, C (mk f p)) : C x := quotient.induction_on' x ih /-- Embedding of the original ring `R` into `adjoin_root f`. -/ def of : R →+* adjoin_root f := (mk f).comp (ring_hom.of C) instance : algebra R (adjoin_root f) := (of f).to_algebra @[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl /-- The adjoined root. -/ def root : adjoin_root f := mk f X variables {f} instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩ @[simp] lemma mk_self : mk f f = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) @[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl @[simp] lemma mk_X : mk f X = root f := rfl @[simp] lemma aeval_eq (p : polynomial R) : aeval (root f) p = mk f p := polynomial.induction_on p (λ x, by { rw aeval_C, refl }) (λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq]) (λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X, ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl }) theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ := algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p, (algebra.adjoin_singleton_eq_range R (root f)).symm ▸ ⟨p, set.mem_univ _, aeval_eq p⟩ @[simp] lemma eval₂_root (f : polynomial R) : f.eval₂ (of f) (root f) = 0 := by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self] lemma is_root_root (f : polynomial R) : is_root (f.map (of f)) (root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring S] /-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/ def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S := begin apply ideal.quotient.lift _ (eval₂_ring_hom i x), intros g H, rcases mem_span_singleton.1 H with ⟨y, hy⟩, rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul] end variables {i : R →+* S} {a : S} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial R} : lift i a h (mk f g) = g.eval₂ i a := ideal.quotient.lift_mk _ _ _ @[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X] @[simp] lemma lift_of {x : R} : lift i a h x = i x := by rw [← mk_C x, lift_mk, eval₂_C] @[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i := ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _ variables (f) [algebra R S] /-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to a root of `f` in `S`. -/ def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S := { commutes' := λ r, show lift _ _ hfx r = _, from lift_of, .. lift (algebra_map R S) x hfx } @[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) : (lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl @[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 := begin have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes), rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂], refl, end @[simp] lemma lift_hom_eq_alg_hom (f : polynomial R) (ϕ : adjoin_root f →ₐ[R] S) : lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ := begin suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤, { exact (alg_hom.ext (λ x, (subalgebra.ext_iff.mp (this) x).mpr algebra.mem_top)).symm }, rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff], exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm, end /-- If `E` is a field extension of `F` and `f` is a polynomial over `F` then the set of maps from `F[x]/(f)` into `E` is in bijection with the set of roots of `f` in `E`. -/ def equiv (F E : Type*) [field F] [field E] [algebra F E] (f : polynomial F) (hf : f ≠ 0) : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots} := { to_fun := λ ϕ, ⟨ϕ (root f), begin rw [mem_roots (map_ne_zero hf), is_root.def, ←eval₂_eq_eval_map], exact aeval_alg_hom_eq_zero f ϕ, exact field.to_nontrivial E, end⟩, inv_fun := λ x, lift_hom f ↑x (begin rw [aeval_def, eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf)], exact subtype.mem x, exact field.to_nontrivial E end), left_inv := λ ϕ, lift_hom_eq_alg_hom f ϕ, right_inv := λ x, begin ext, refine @lift_root F E _ f _ _ ↑x _, rw [eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf), ←multiset.mem_to_finset], exact multiset.mem_to_finset.mpr (subtype.mem x), exact field.to_nontrivial E end } end comm_ring section irreducible variables [field K] {f : polynomial K} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial K)) := principal_ideal_ring.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : field (adjoin_root f) := { ..adjoin_root.comm_ring f, ..ideal.quotient.field (span {f} : ideal (polynomial K)) } lemma coe_injective : function.injective (coe : K → adjoin_root f) := (of f).injective variable (f) lemma mul_div_root_cancel : ((X - C (root f)) * (f.map (of f) / (X - C (root f))) : polynomial (adjoin_root f)) = f.map (of f) := mul_div_eq_iff_is_root.2 $ is_root_root _ end irreducible section power_basis variables [field K] {f : polynomial K} lemma power_basis_is_basis (hf : f ≠ 0) : is_basis K (λ (i : fin f.nat_degree), (root f ^ i.val)) := begin set f' := f * C (f.leading_coeff⁻¹) with f'_def, have deg_f' : f'.nat_degree = f.nat_degree, { rw [nat_degree_mul hf, nat_degree_C, add_zero], { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } }, have f'_monic : monic f' := monic_mul_leading_coeff_inv hf, have aeval_f' : aeval (root f) f' = 0, { rw [f'_def, alg_hom.map_mul, aeval_eq, mk_self, zero_mul] }, have hx : is_integral K (root f) := ⟨f', f'_monic, aeval_f'⟩, have minpoly_eq : f' = minpoly K (root f), { apply minpoly.unique K _ f'_monic aeval_f', intros q q_monic q_aeval, have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f, { ext, { simp only [ring_hom.comp_apply, mk_C, lift_of], refl }, { simp only [ring_hom.comp_apply, mk_X, lift_root] } }, rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero, with_bot.coe_le_coe, deg_f'], apply nat_degree_le_of_dvd, { rw [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem], change mk f q = 0, rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero] }, { exact q_monic.ne_zero } }, refine ⟨_, eq_top_iff.mpr _⟩, { rw [←deg_f', minpoly_eq], exact hx.linear_independent_pow }, { rintros y -, rw [←deg_f', minpoly_eq], apply hx.mem_span_pow, obtain ⟨g⟩ := y, use g, rw aeval_eq, refl } end /-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ noncomputable def power_basis (hf : f ≠ 0) : power_basis K (adjoin_root f) := { gen := root f, dim := f.nat_degree, is_basis := power_basis_is_basis hf } end power_basis end adjoin_root
f40bce57b674a961b5fde9fbf8012e001d2628bf
5382d69a781e8d7e4f53e2358896eb7649c9b298
/impossible.lean
de9821a355b55a81978bf9997e2f530231197ba7
[]
no_license
evhub/lean-math-examples
c30249747a21fba3bc8793eba4928db47cf28768
dec44bf581a1e9d5bf0b5261803a43fe8fd350e1
refs/heads/master
1,624,170,837,738
1,623,889,725,000
1,623,889,725,000
148,759,369
3
0
null
null
null
null
UTF-8
Lean
false
false
6,534
lean
import .posets namespace impossible open nat open posets -- bool: instance bool_order: bot_order bool := { le := λ x y: bool, x = ff ∨ (x = tt ∧ y = tt), le_refl := begin intros, induction a; simp, end, le_trans := begin intros, induction a_1, case or.inl { simp, left, assumption, }, case or.inr { simp, simp at a_2, cases a_2, case or.inl { induction b, case bool.ff { apply false.elim, apply ff_eq_tt_eq_false, apply a_1.2, }, case bool.tt { apply false.elim, apply tt_eq_ff_eq_false, assumption, }, }, case or.inr { right, split, apply a_1.1, apply a_2.2, }, }, end, le_antisymm := begin intros, cases a_1, case or.inl { cases a_2, case or.inl { rw [a_1, a_2], }, case or.inr { apply false.elim, apply ff_eq_tt_eq_false, rw [←a_1, ←a_2.2], }, }, case or.inr { cases a_2, case or.inl { apply false.elim, apply ff_eq_tt_eq_false, rw [←a_1.2, a_2], }, case or.inr { rw [a_1.1, a_2.1], }, }, end, bot := ff, bot_le := begin intros, left, refl, end, } @[reducible, pattern] instance bool.has_zero: has_zero bool := (| ff |) @[reducible, pattern] instance bool.has_one: has_one bool := (| tt |) theorem bool.le_tt (x: bool): x ≤ 1 := begin induction x, apply bot_le, refl, end instance bool.coe_to_nat: has_coe bool nat := { coe := λ x: bool, match x with | 0 := 0 | 1 := 1 end, } -- bitstream: structure bitstream := (bit: ℕ → bool) instance bitstream.coe_to_fun: has_coe_to_fun bitstream := { F := λ b: bitstream, ℕ → bool, coe := bitstream.bit, } @[simp] theorem bitstream.bit.of_coe (b: bitstream) (n: ℕ): b n = b.bit n := rfl def bitstream.cons (x: bool) (b: bitstream): bitstream := { bit := λ n: ℕ, match n with | 0 := x | (succ m) := b m end, } infixr ` # `:67 := bitstream.cons def all (x: bool): bitstream := { bit := λ n, x, } @[simp] theorem all.of_bit (x: bool) (n: ℕ): (all x) n = x := rfl -- find: def findN: ℕ → (bitstream → bool) → bitstream | 0 P := all 0 | (succ N) P := let find0 := 0 # findN N (λ b, P (0 # b)) in let find1 := 1 # findN N (λ b, P (1 # b)) in match P find0 with | tt := find0 | ff := find1 end def find (P: bitstream → bool): bitstream := { bit := λ n: ℕ, (findN (succ n) P) n, } def forsome (P: bitstream → bool): bool := P (find P) def forevery (P: bitstream → bool): bool := bnot (forsome (bnot ∘ P)) def equal {T: Sort _} [decidable_eq T] (P1 P2: bitstream → T): bool := forevery (λ b: bitstream, P1 b = P2 b) -- tests: namespace find_test def f (b: bitstream): ℤ := b (7 * (b 4) + 4 * (b 7) + 4) def g (b: bitstream): ℤ := b ((b 4) + 11 * (b 7)) def h (b: bitstream): ℤ := if b 7 = 0 then if b 4 = 0 then b 4 else b 11 else if b 4 = 1 then b 15 else b 8 #eval equal f g #eval equal f h #eval equal g h #eval equal f f #eval equal g g #eval equal h h end find_test -- conat: structure conat extends bitstream := [mono: monotone.decreasing bit] instance conat.coe_to_fun: has_coe_to_fun conat := { F := λ cn: conat, ℕ → bool, coe := λ cn: conat, cn.bit, } @[simp] theorem conat.bit.of_coe (cn: conat) (n: ℕ): cn n = cn.bit n := rfl def conat.zero: conat := { bit := all 0, mono := begin split, intros, refl, end, } instance conat.has_zero: has_zero conat := (| conat.zero |) def conat.inf: conat := { bit := all 1, mono := begin split, intros, refl, end, } def conat.succ (cn: conat): conat := { bit := λ n: ℕ, match n with | 0 := 1 | (succ m) := cn m end, mono := begin split, intros, simp, induction x, case nat.zero { rw [conat.succ._match_1], apply bool.le_tt, }, case nat.succ { induction y, case nat.zero { apply false.elim, apply not_succ_le_zero x_n a, }, case nat.succ { rw [conat.succ._match_1, conat.succ._match_1], apply cn.mono.elim, apply le_of_succ_le_succ, assumption, }, }, end, } end impossible
76e2eb05305ea2ebd55985df8c68613dd4900e94
7b9ff28673cd3dd7dd3dcfe2ab8449f9244fe05a
/src/jesse/exercises-day-one-solutions.lean
e20f2bd8731e5e6a50e05a80872cb19d41c7aee4
[]
no_license
jesse-michael-han/hanoi-lean-2019
ea2f0e04f81093373c48447065765a964ee82262
a5a9f368e394d563bfcc13e3773863924505b1ce
refs/heads/master
1,591,320,223,247
1,561,022,886,000
1,561,022,886,000
192,264,820
1
1
null
null
null
null
UTF-8
Lean
false
false
6,113
lean
import tactic tactic.explode open classical /- Fill in the `sorry`s below -/ local attribute [instance, priority 0] prop_decidable example (p : Prop) : p ∨ ¬ p := begin by_cases p, { left, assumption }, { right, assumption } end example (p : Prop) : p ∨ ¬ p := begin by_cases h' : p, { left, exact h' }, { right, exact h' } end example (p : Prop) : p ∨ ¬ p := begin by_cases h' : p, { exact or.inl h' }, { exact or.inr h' } end /- Give a calculational proof of the theorem log_mul below. You can use the rewrite tactic `rw` (and `calc` if you want), but not `simp`. These objects are actually defined in mathlib, but for now, we'll just declare them. -/ constant real : Type @[instance] constant orreal : ordered_ring real constants (log exp : real → real) constant log_exp_eq : ∀ x, log (exp x) = x constant exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x constant exp_pos : ∀ x, exp x > 0 constant exp_add : ∀ x y, exp (x + y) = exp x * exp y attribute [ematch] log_exp_eq exp_log_eq exp_pos exp_add example (x y z : real) : exp (x + y + z) = exp x * exp y * exp z := by rw[exp_add, exp_add] example (y : real) (h : y > 0) : exp (log y) = y := exp_log_eq ‹_› theorem log_mul' {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := begin rw[<-exp_log_eq hx, <-exp_log_eq hy, <-exp_add], simp only [log_exp_eq] end section variables {p q r : Prop} example : (p → q) → (¬q → ¬p) := by finish example : (p → (q → r)) → (p ∧ q → r) := by finish example : p ∧ ¬q → ¬(p → q) := by finish example : (¬p ∨ q) → (p → q) := by intros; cc example : (p ∨ q → r) → (p → r) ∧ (q → r) := by intros; finish example : (p → q) → (¬p ∨ q) := by intros; finish end section variables {α β : Type} (p q : α → Prop) (r : α → β → Prop) example : (∀ x, p x) ∧ (∀ x, q x) → ∀ x, p x ∧ q x := begin intros a x, cases a, fsplit, work_on_goal 0 { solve_by_elim }, solve_by_elim end example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := begin intro H, cases H, tidy, left, finish, right, finish end example : (∃ x, ∀ y, r x y) → ∀ y, ∃ x, r x y := begin intro H, cases H, /- `tidy` says -/ intros y, fsplit, work_on_goal 1 { solve_by_elim } end theorem e1 : (¬ ∃ x, p x) → ∀ x, ¬ p x := begin intro H, push_neg at H, exact H end example : (¬ ∀ x, ¬ p x) → ∃ x, p x := begin intro H, push_neg at H, from ‹_› end example : (¬ ∀ x, ¬ p x) → ∃ x, p x := begin intro H, push_neg at H, from ‹_› end end section /- There is a man in the town who is the barber. The barber shaves all men who do not shave themselves. Does the barber shave himself? -/ variables (man : Type) (barber : man) variable (shaves : man → man → Prop) example (H : ∀ x : man, shaves barber x ↔ ¬ shaves x x) : false := by {[smt] eblast_using[H barber]} end section variables {α : Type} (p : α → Prop) (r : Prop) (a : α) include a example : (r → ∃ x, p x) → ∃ x, (r → p x) := begin by_cases r, {intro H, specialize H ‹_›, cases H with x Hx, use x, intro, from ‹_›}, {intro H, use a} end end /- Prove the theorem below, using only the ring properties of ℤ enumerated in Section 4.2 and the theorem sub_self. You should probably work out a pen-and-paper proof first. -/ example (x : ℤ) : x * 0 = 0 := by simp section open list variable {α : Type*} variables s t : list α variable a : α example : length (s ++ t) = length s + length t := by simp end /- Define an inductive data type consisting of terms built up from the following constructors: `const n`, a constant denoting the natural number n `var n`, a variable, numbered n `plus s t`, denoting the sum of s and t `times s t`, denoting the product of s and t -/ inductive nat_term | const : ℕ → nat_term | var : ℕ → nat_term | plus : nat_term → nat_term → nat_term | times : nat_term → nat_term → nat_term open nat_term /- Recursively define a function that evaluates any such term with respect to an assignment `val : ℕ → ℕ` of values to the variables. For example, if `val 4 = 3 -/ def eval (val : ℕ → ℕ) : nat_term → ℕ | (const k) := k | (var k) := val k | (plus s t) := (eval s) + (eval t) | (times s t) := (eval s) * (eval t) /- Test it out by using #eval on some terms. You can use the following `val` function. In that case, for example, we would expect to have eval val (plus (const 2) (var 1)) = 5 -/ def val : ℕ → ℕ | 0 := 4 | 1 := 3 | 2 := 8 | _ := 0 example : eval val (plus (const 2) (var 1)) = 5 := rfl #eval eval val (plus (const 2) (var 1)) /- Below, we define a function `rev` that reverses a list. It uses an auxiliary function `append1`. If you can, prove that the length of the list is preserved, and that `rev (rev l) = l` for every `l`. The theorem below is given as an example, and should be helpful. Note that when you use the equation compiler to define a function foo, `rw [foo]` uses one of the defining equations if it can. For example, `rw [append1, ...]` in the theorem uses the second equation in the definition of `append1` -/ section open list variable {α : Type*} def append1 (a : α) : list α → list α | nil := [a] | (b :: l) := b :: (append1 l) def rev : list α → list α | nil := nil | (a :: l) := append1 a (rev l) theorem length_append1 (a : α) (l : list α): length (append1 a l) = length l + 1 := begin induction l, { simp[append1] }, { unfold append1 at l_ih ⊢, finish } end theorem length_rev (l : list α) : length (rev l) = length l := begin induction l, { unfold rev }, { unfold rev, finish[length_append1] } end lemma hd_rev (a : α) (l : list α) : a :: rev l = rev (append1 a l) := begin induction l, { simp[rev, append1] }, { rw[rev, append1, rev, <-l_ih, append1] } end theorem rev_rev (l : list α) : rev (rev l) = l := begin induction l, { refl }, { conv {to_rhs, rw[<-l_ih], rw[hd_rev]}, refl } end end
d8c53d5c253d4b9bac210207bc9b37e3bfd7111b
92c6b42948d74fe325c2d88530f1d36da388b2f7
/src/cvc4/sig/th_base.lean
5709f8bf59a806743ae0f317974ada11f7b7c897
[ "MIT" ]
permissive
riaqn/smtlean
8ad65055b6c1600cd03b9e345059a3b24419b6d5
c11768cfb43cd634340b552f5039cba094701a87
refs/heads/master
1,584,569,627,940
1,535,314,713,000
1,535,314,713,000
135,333,334
0
1
null
null
null
null
UTF-8
Lean
false
false
76
lean
namespace sig axiom trust : false axiom trust_f (α : Prop) : α end sig
203b546ec995713fc55a3c86c38eb55c268b4949
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/MetavarContext.lean
836570e235449c4b8afb10b4430fb6162621d684
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51,230
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.MonadCache import Lean.LocalContext namespace Lean /- The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringHasAdd ?s) ?x ?y =?= f Int intHasAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringHasAdd ?s =?= intHasAdd ``` We say `ringHasAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown aaa. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `HasCoe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called tmp metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we want to allow TC to invoke tactics. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the sythesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variables `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contatins `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `HasCoe Nat ?x`. This is good, but this constraint is too strict for problems such as `HasCoe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction betwen temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ structure LocalInstance := (className : Name) (fvar : Expr) abbrev LocalInstances := Array LocalInstance def LocalInstance.beq (i₁ i₂ : LocalInstance) : Bool := i₁.fvar == i₂.fvar instance LocalInstance.hasBeq : HasBeq LocalInstance := ⟨LocalInstance.beq⟩ /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts inductive MetavarKind | natural | synthetic | syntheticOpaque def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false structure MetavarDecl := (userName : Name := Name.anonymous) (lctx : LocalContext) (type : Expr) (depth : Nat) (localInstances : LocalInstances) (kind : MetavarKind) (numScopeArgs : Nat := 0) -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` @[export lean_mk_metavar_decl] def mkMetavarDeclEx (userName : Name) (lctx : LocalContext) (type : Expr) (depth : Nat) (localInstances : LocalInstances) (kind : MetavarKind) : MetavarDecl := { userName := userName, lctx := lctx, type := type, depth := depth, localInstances := localInstances, kind := kind } namespace MetavarDecl instance : Inhabited MetavarDecl := ⟨{ lctx := arbitrary _, type := arbitrary _, depth := 0, localInstances := #[], kind := MetavarKind.natural }⟩ end MetavarDecl /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`. Note that `fvars` may not be defined in the local context for `?m`. - TODO: after we delete the old frontend, we can remove the field `lctx`. This field is only used in old C++ implementation. -/ structure DelayedMetavarAssignment := (lctx : LocalContext) (fvars : Array Expr) (val : Expr) open Std (HashMap PersistentHashMap) structure MetavarContext := (depth : Nat := 0) (lDepth : PersistentHashMap MVarId Nat := {}) (decls : PersistentHashMap MVarId MetavarDecl := {}) (lAssignment : PersistentHashMap MVarId Level := {}) (eAssignment : PersistentHashMap MVarId Expr := {}) (dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {}) namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with decls := mctx.decls.insert mvarId { userName := userName, lctx := lctx, localInstances := localInstances, type := type, depth := mctx.depth, kind := kind, numScopeArgs := numScopeArgs } } @[export lean_metavar_ctx_mk_decl] def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } @[export lean_metavar_ctx_find_decl] def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := let search : Except MVarId Unit := mctx.decls.forM fun mvarId decl => if decl.userName == userName then throw mvarId else pure (); match search with | Except.ok _ => none | Except.error mvarId => some mvarId def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId; { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId; { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } } def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (newUserName : Name) : MetavarContext := match mctx.findDecl? mvarId with | none => panic! "unknown metavariable" | some mvarDecl => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with userName := newUserName } } @[export lean_metavar_ctx_assign_level] def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext := { m with lAssignment := m.lAssignment.insert mvarId val } @[export lean_metavar_ctx_assign_expr] def assignExprCore (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } @[export lean_metavar_ctx_assign_delayed] def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext := { m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } } @[export lean_metavar_ctx_get_level_assignment] def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level := m.lAssignment.find? mvarId @[export lean_metavar_ctx_get_expr_assignment] def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId @[export lean_metavar_ctx_get_delayed_assignment] def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment := m.dAssignment.find? mvarId @[export lean_metavar_ctx_is_level_assigned] def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.lAssignment.contains mvarId @[export lean_metavar_ctx_is_expr_assigned] def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.eAssignment.contains mvarId @[export lean_metavar_ctx_is_delayed_assigned] def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.dAssignment.contains mvarId @[export lean_metavar_ctx_erase_delayed] def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext := { m with dAssignment := m.dAssignment.erase mvarId } /- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedRoot (m : MetavarContext) : MVarId → MVarId | mvarId => match getDelayedAssignment? m mvarId with | some d => match d.val.getAppFn with | Expr.mvar mvarId _ => getDelayedRoot mvarId | _ => mvarId | none => mvarId def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.lDepth.find? mvarId with | some d => d == mctx.depth | _ => panic! "unknown universe metavariable" def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := let decl := mctx.getDecl mvarId; decl.depth == mctx.depth def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssigned mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx) | Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignedMVar f) || (a.hasMVar && hasAssignedMVar a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar t) || (v.hasMVar && hasAssignedMVar v) || (b.hasMVar && hasAssignedMVar b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar d) || (b.hasMVar && hasAssignedMVar b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar d) || (b.hasMVar && hasAssignedMVar b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar e | Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar e | Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId | Expr.localE _ _ _ _ => unreachable! /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssignable mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx) | Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignableMVar f) || (a.hasMVar && hasAssignableMVar a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar t) || (v.hasMVar && hasAssignableMVar v) || (b.hasMVar && hasAssignableMVar b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar d) || (b.hasMVar && hasAssignableMVar b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar d) || (b.hasMVar && hasAssignableMVar b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar e | Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar e | Expr.mvar mvarId _ => mctx.isExprAssignable mvarId | Expr.localE _ _ _ _ => unreachable! partial def instantiateLevelMVars : Level → StateM MetavarContext Level | lvl@(Level.succ lvl₁ _) => do lvl₁ ← instantiateLevelMVars lvl₁; pure (Level.updateSucc! lvl lvl₁) | lvl@(Level.max lvl₁ lvl₂ _) => do lvl₁ ← instantiateLevelMVars lvl₁; lvl₂ ← instantiateLevelMVars lvl₂; pure (Level.updateMax! lvl lvl₁ lvl₂) | lvl@(Level.imax lvl₁ lvl₂ _) => do lvl₁ ← instantiateLevelMVars lvl₁; lvl₂ ← instantiateLevelMVars lvl₂; pure (Level.updateIMax! lvl lvl₁ lvl₂) | lvl@(Level.mvar mvarId _) => do mctx ← get; match getLevelAssignment? mctx mvarId with | some newLvl => if !newLvl.hasMVar then pure newLvl else do newLvl' ← instantiateLevelMVars newLvl; modify $ fun mctx => mctx.assignLevel mvarId newLvl'; pure newLvl' | none => pure lvl | lvl => pure lvl namespace InstantiateExprMVars private abbrev M := StateM (WithHashMapCache Expr Expr MetavarContext) @[inline] def instantiateLevelMVars (lvl : Level) : M Level := WithHashMapCache.fromState $ MetavarContext.instantiateLevelMVars lvl @[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache e f @[inline] private def getMCtx : M MetavarContext := do s ← get; pure s.state @[inline] private def modifyCtx (f : MetavarContext → MetavarContext) : M Unit := modify $ fun s => { s with state := f s.state } /-- instantiateExprMVars main function -/ partial def main : Expr → M Expr | e@(Expr.proj _ _ s _) => do s ← visit main s; pure (e.updateProj! s) | e@(Expr.forallE _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateForallE! d b) | e@(Expr.lam _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateLambdaE! d b) | e@(Expr.letE _ t v b _) => do t ← visit main t; v ← visit main v; b ← visit main b; pure (e.updateLet! t v b) | e@(Expr.const _ lvls _) => do lvls ← lvls.mapM instantiateLevelMVars; pure (e.updateConst! lvls) | e@(Expr.sort lvl _) => do lvl ← instantiateLevelMVars lvl; pure (e.updateSort! lvl) | e@(Expr.mdata _ b _) => do b ← visit main b; pure (e.updateMData! b) | e@(Expr.app _ _ _) => e.withApp $ fun f args => do let instArgs (f : Expr) : M Expr := do { args ← args.mapM (visit main); pure (mkAppN f args) }; let instApp : M Expr := do { let wasMVar := f.isMVar; f ← visit main f; if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ visit main (f.betaRev args.reverse) else instArgs f }; match f with | Expr.mvar mvarId _ => do mctx ← getMCtx; match mctx.getDelayedAssignment? mvarId with | none => instApp | some { fvars := fvars, val := val, .. } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else do newVal ← visit main val; if newVal.hasExprMVar then instArgs f else do args ← args.mapM (visit main); /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars; let result := newVal.instantiateRevRange 0 fvars.size args; let result := mkAppRange result fvars.size args.size args; pure $ result | _ => instApp | e@(Expr.mvar mvarId _) => checkCache e $ fun e => do mctx ← getMCtx; match mctx.getExprAssignment? mvarId with | some newE => do newE' ← visit main newE; modifyCtx $ fun mctx => mctx.assignExpr mvarId newE'; pure newE' | none => pure e | e => pure e end InstantiateExprMVars def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := if !e.hasMVar then (e, mctx) else (WithHashMapCache.toState $ InstantiateExprMVars.main e).run mctx def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext := lctx.foldl (fun (result : LocalContext × MetavarContext) ldecl => let (lctx, mctx) := result; match ldecl with | LocalDecl.cdecl _ fvarId userName type bi => let (type, mctx) := mctx.instantiateMVars type; (lctx.mkLocalDecl fvarId userName type bi, mctx) | LocalDecl.ldecl _ fvarId userName type value nonDep => let (type, mctx) := mctx.instantiateMVars type; let (value, mctx) := mctx.instantiateMVars value; (lctx.mkLetDecl fvarId userName type value nonDep, mctx)) ({}, mctx) def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := let mvarDecl := mctx.getDecl mvarId; let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx; let (type, mctx) := mctx.instantiateMVars mvarDecl.type; { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } } namespace DependsOn private abbrev M := StateM ExprSet private def visit? (e : Expr) : M Bool := if !e.hasMVar && !e.hasFVar then pure false else do s ← get; if s.contains e then pure false else do modify $ fun s => s.insert e; pure true @[inline] private def visit (main : Expr → M Bool) (e : Expr) : M Bool := condM (visit? e) (main e) (pure false) @[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) : Expr → M Bool | e@(Expr.proj _ _ s _) => visit dep s | e@(Expr.forallE _ d b _) => visit dep d <||> visit dep b | e@(Expr.lam _ d b _) => visit dep d <||> visit dep b | e@(Expr.letE _ t v b _) => visit dep t <||> visit dep v <||> visit dep b | e@(Expr.mdata _ b _) => visit dep b | e@(Expr.app f a _) => visit dep a <||> if f.isApp then dep f else visit dep f | e@(Expr.mvar mvarId _) => match mctx.getExprAssignment? mvarId with | some a => visit dep a | none => let lctx := (mctx.getDecl mvarId).lctx; pure $ lctx.any $ fun decl => p decl.fvarId | e@(Expr.fvar fvarId _) => pure $ p fvarId | e => pure false @[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`. For each metavariable `?m` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool := (DependsOn.main mctx p e).run' {} /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `p x` is `true`. -/ @[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool := match localDecl with | LocalDecl.cdecl _ _ _ type _ => findExprDependsOn mctx type p | LocalDecl.ldecl _ _ _ type value _ => (DependsOn.main mctx p type <||> DependsOn.main mctx p value).run' {} def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool := findExprDependsOn mctx e $ fun fvarId' => fvarId == fvarId' def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool := findLocalDeclDependsOn mctx localDecl $ fun fvarId' => fvarId == fvarId' namespace MkBinding inductive Exception | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl) def Exception.toString : Exception → String | Exception.revertFailure _ lctx toRevert decl => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)" instance Exception.hasToString : HasToString Exception := ⟨Exception.toString⟩ /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State := (mctx : MetavarContext) (ngen : NameGenerator) (cache : HashMap Expr Expr := {}) -- abbrev MCore := EStateM Exception State abbrev M := ReaderT Bool (EStateM Exception State) def preserveOrder : M Bool := read instance : MonadHashMapCacheAdapter Expr Expr M := { getCache := do s ← get; pure s.cache, modifyCache := fun f => modify $ fun s => { s with cache := f s.cache } } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := let d : LocalDecl := lctx.getFVar! $ xs.get! 0; xs.foldlFrom (fun d x => let decl := lctx.getFVar! x; if decl.index < d.index then decl else d) d 1 /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ private def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) := if toRevert.size == 0 then pure toRevert else do when preserveOrder $ do { -- Make sure none of `toRevert` is an AuxDecl -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM $ fun i => do let fvar := toRevert.get! i; let decl := lctx.getFVar! fvar; i.forM $ fun j => let prevFVar := toRevert.get! j; let prevDecl := lctx.getFVar! prevFVar; when (localDeclDependsOn mctx prevDecl fvar.fvarId!) $ throw (Exception.revertFailure mctx lctx toRevert prevDecl) }; let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size; let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert; let initSize := newToRevert.size; lctx.foldlFromM (fun (newToRevert : Array Expr) decl => if initSize.any $ fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert else if toRevert.any (fun x => decl.fvarId == x.fvarId!) then pure (newToRevert.push decl.toExpr) else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any $ fun x => x.fvarId! == fvarId) then pure (newToRevert.push decl.toExpr) else pure newToRevert) newToRevert firstDeclToVisit.index /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ private def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (fun x lctx => lctx.erase x.fvarId!) lctx @[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache e f @[inline] private def getMCtx : M MetavarContext := do s ← get; pure s.mctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (fun scope x => if lctx.contains x.fvarId! then scope.push x else scope) #[] /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache {α} (x : M α) : M α := do cache ← modifyGet $ fun s => (s.cache, { s with cache := {} }); a ← x; modify $ fun s => { s with cache := cache }; pure a @[inline] private def abstractRangeAux (elimMVarDeps : Expr → M Expr) (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do e ← elimMVarDeps e; pure (e.abstractRange i xs) private def mkAuxMVarType (elimMVarDeps : Expr → M Expr) (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do e ← abstractRangeAux elimMVarDeps xs xs.size e; xs.size.foldRevM (fun i e => let x := xs.get! i; match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => do let type := type.headBeta; type ← abstractRangeAux elimMVarDeps xs i type; pure $ Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => do let type := type.headBeta; type ← abstractRangeAux elimMVarDeps xs i type; value ← abstractRangeAux elimMVarDeps xs i value; let e := mkLet n type value e nonDep; match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1; pure $ mkForall n BinderInfo.default type e | _ => pure e) e /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (fun e x => match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x) mvar /-- Return true iff some `e` in `es` depends on `fvarId` -/ private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool := es.any $ fun e => exprDependsOn mctx e fvarId private partial def elimMVarDepsApp (elimMVarDepsAux : Expr → M Expr) (xs : Array Expr) : Expr → Array Expr → M Expr | f, args => match f with | Expr.mvar mvarId _ => do let processDefault (newF : Expr) : M Expr := do { if newF.isLambda then do args ← args.mapM (visit elimMVarDepsAux); elimMVarDepsAux $ newF.betaRev args.reverse else if newF == f then do args ← args.mapM (visit elimMVarDepsAux); pure $ mkAppN newF args else elimMVarDepsApp newF args }; mctx ← getMCtx; match mctx.getExprAssignment? mvarId with | some val => processDefault val | _ => let mvarDecl := mctx.getDecl mvarId; let mvarLCtx := mvarDecl.lctx; let toRevert := getInScope mvarLCtx xs; if toRevert.size == 0 then processDefault f else let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind; /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment ``` ?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`. Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]` -/ let continue (nestedFVars : Array Expr) : M Expr := do { args ← args.mapM (visit elimMVarDepsAux); preserve ← preserveOrder; match collectDeps mctx mvarLCtx toRevert preserve with | Except.error ex => throw ex | Except.ok toRevert => do let newMVarLCtx := reduceLocalContext mvarLCtx toRevert; let newLocalInsts := mvarDecl.localInstances.filter $ fun inst => toRevert.all $ fun x => inst.fvar != x; newMVarType ← mkAuxMVarType elimMVarDepsAux mvarLCtx toRevert newMVarKind mvarDecl.type; newMVarId ← get >>= fun s => pure s.ngen.curr; let newMVar := mkMVar newMVarId; let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind; let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs; modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next }; match newMVarKind with | MetavarKind.syntheticOpaque => modify $ fun s => { s with mctx := assignDelayed s.mctx newMVarId mvarLCtx (toRevert ++ nestedFVars) (mkAppN f nestedFVars) } | _ => modify $ fun s => { s with mctx := assignExpr s.mctx mvarId result }; pure (mkAppN result args) }; if !mvarDecl.kind.isSyntheticOpaque then continue #[] else match mctx.getDelayedAssignment? mvarId with | none => continue #[] | some { fvars := fvars, .. } => continue fvars | _ => do f ← visit elimMVarDepsAux f; args ← args.mapM (visit elimMVarDepsAux); pure (mkAppN f args) private partial def elimMVarDepsAux (xs : Array Expr) : Expr → M Expr | e@(Expr.proj _ _ s _) => do s ← visit elimMVarDepsAux s; pure (e.updateProj! s) | e@(Expr.forallE _ d b _) => do d ← visit elimMVarDepsAux d; b ← visit elimMVarDepsAux b; pure (e.updateForallE! d b) | e@(Expr.lam _ d b _) => do d ← visit elimMVarDepsAux d; b ← visit elimMVarDepsAux b; pure (e.updateLambdaE! d b) | e@(Expr.letE _ t v b _) => do t ← visit elimMVarDepsAux t; v ← visit elimMVarDepsAux v; b ← visit elimMVarDepsAux b; pure (e.updateLet! t v b) | e@(Expr.mdata _ b _) => do b ← visit elimMVarDepsAux b; pure (e.updateMData! b) | e@(Expr.app _ _ _) => e.withApp $ fun f args => elimMVarDepsApp elimMVarDepsAux xs f args | e@(Expr.mvar mvarId _) => elimMVarDepsApp elimMVarDepsAux xs e #[] | e => pure e partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else withFreshCache $ elimMVarDepsAux xs e /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] private def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do e ← elimMVarDeps xs e; pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` are created only for used variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : M (Expr × Nat) := do e ← abstractRange xs xs.size e; xs.size.foldRevM (fun i (p : Expr × Nat) => let (e, num) := p; let x := xs.get! i; match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then do let type := type.headBeta; type ← abstractRange xs i type; if isLambda then pure (Lean.mkLambda n bi type e, num + 1) else pure (Lean.mkForall n bi type e, num + 1) else pure (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => do if e.hasLooseBVar 0 then do type ← abstractRange xs i type; value ← abstractRange xs i value; pure (mkLet n type value e nonDep, num + 1) else pure (e.lowerLooseBVars 1 1, num)) (e, 0) end MkBinding abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun _ => MkBinding.elimMVarDeps xs e preserveOrder def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : MkBindingM (Expr × Nat) := fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly false @[inline] def mkLambda (xs : Array Expr) (e : Expr) : MkBindingM Expr := do (e, _) ← mkBinding true xs e; pure e @[inline] def mkForall (xs : Array Expr) (e : Expr) : MkBindingM Expr := do (e, _) ← mkBinding false xs e; pure e @[inline] def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MkBindingM (Expr × Nat) := do mkBinding false xs e true /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool | Expr.mdata _ e _ => isWellFormed e | Expr.proj _ _ e _ => isWellFormed e | e@(Expr.app f a _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed f && isWellFormed a) | e@(Expr.lam _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed d && isWellFormed b) | e@(Expr.forallE _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed d && isWellFormed b) | e@(Expr.letE _ t v b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed t && isWellFormed v && isWellFormed b) | Expr.const _ _ _ => true | Expr.bvar _ _ => true | Expr.sort _ _ => true | Expr.lit _ _ => true | Expr.mvar mvarId _ => let mvarDecl := mctx.getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then true else match mctx.getExprAssignment? mvarId with | none => false | some v => isWellFormed v | Expr.fvar fvarId _ => lctx.contains fvarId | Expr.localE _ _ _ _ => unreachable! namespace LevelMVarToParam structure Context := (paramNamePrefix : Name) (alreadyUsedPred : Name → Bool) structure State := (mctx : MetavarContext) (paramNames : Array Name := #[]) (nextParamIdx : Nat) abbrev M := ReaderT Context $ StateM State partial def mkParamName : Unit → M Name | _ => do ctx ← read; s ← get; let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx; if ctx.alreadyUsedPred newParamName then do modify $ fun s => { s with nextParamIdx := s.nextParamIdx + 1 }; mkParamName () else do modify $ fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName }; pure newParamName partial def visitLevel : Level → M Level | u@(Level.succ v _) => do v ← visitLevel v; pure (u.updateSucc v rfl) | u@(Level.max v₁ v₂ _) => do v₁ ← visitLevel v₁; v₂ ← visitLevel v₂; pure (u.updateMax v₁ v₂ rfl) | u@(Level.imax v₁ v₂ _) => do v₁ ← visitLevel v₁; v₂ ← visitLevel v₂; pure (u.updateIMax v₁ v₂ rfl) | u@(Level.zero _) => pure u | u@(Level.param _ _) => pure u | u@(Level.mvar mvarId _) => do s ← get; match s.mctx.getLevelAssignment? mvarId with | some v => visitLevel v | none => do p ← mkParamName (); let p := mkLevelParam p; modify $ fun s => { s with mctx := s.mctx.assignLevel mvarId p }; pure p @[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr := if e.hasMVar then f e else pure e partial def main : Expr → M Expr | e@(Expr.proj _ _ s _) => do s ← visit main s; pure (e.updateProj! s) | e@(Expr.forallE _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateForallE! d b) | e@(Expr.lam _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateLambdaE! d b) | e@(Expr.letE _ t v b _) => do t ← visit main t; v ← visit main v; b ← visit main b; pure (e.updateLet! t v b) | e@(Expr.app f a _) => do f ← visit main f; a ← visit main a; pure (e.updateApp! f a) | e@(Expr.mdata _ b _) => do b ← visit main b; pure (e.updateMData! b) | e@(Expr.const _ us _) => do us ← us.mapM visitLevel; pure (e.updateConst! us) | e@(Expr.sort u _) => do u ← visitLevel u; pure (e.updateSort! u) | e@(Expr.mvar mvarId _) => do s ← get; match s.mctx.getExprAssignment? mvarId with | some v => visit main v | none => pure e | e => pure e end LevelMVarToParam structure UnivMVarParamResult := (mctx : MetavarContext) (newParamNames : Array Name) (nextParamIdx : Nat) (expr : Expr) def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx }; { mctx := s.mctx, newParamNames := s.paramNames, nextParamIdx := s.nextParamIdx, expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (fun a mvarId _ => Array.push a mvarId) #[] end MetavarContext class MonadMCtx (m : Type → Type) := (getMCtx : m MetavarContext) export MonadMCtx (getMCtx) instance monadMCtxTrans (m n) [MonadMCtx m] [MonadLift m n] : MonadMCtx n := { getMCtx := liftM (getMCtx : m _) } end Lean
0e8e8a3973b442815eb0c277dfe351643f1ca559
b9def12ac9858ba514e44c0758ebb4e9b73ae5ed
/src/monoidal_categories_reboot/tensor_product.lean
264e6ff5c73a49598d0717045f83b11749eea8e0
[ "Apache-2.0" ]
permissive
cipher1024/monoidal-categories-reboot
5f826017db2f71920336331739a0f84be2f97bf7
998f2a0553c22369d922195dc20a20fa7dccc6e5
refs/heads/master
1,586,710,273,395
1,543,592,573,000
1,543,592,573,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,305
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. import category_theory.category import category_theory.functor import category_theory.products import category_theory.natural_isomorphism open category_theory universes u v open category_theory.category open category_theory.functor open category_theory.prod open category_theory.functor.category.nat_trans namespace category_theory.monoidal @[reducible] def tensor_obj_type (C : Type u) [category.{u v} C] := C → C → C @[reducible] def tensor_hom_type {C : Type u} [category.{u v} C] (tensor_obj : tensor_obj_type C) : Type (max u v) := Π {X₁ Y₁ X₂ Y₂ : C}, hom X₁ Y₁ → hom X₂ Y₂ → hom (tensor_obj X₁ X₂) (tensor_obj Y₁ Y₂) local attribute [tidy] tactic.assumption def assoc_obj {C : Type u} [category.{u v} C] (tensor_obj : tensor_obj_type C) : Type (max u v) := Π X Y Z : C, (tensor_obj (tensor_obj X Y) Z) ≅ (tensor_obj X (tensor_obj Y Z)) def assoc_natural {C : Type u} [category.{u v} C] (tensor_obj : tensor_obj_type C) (tensor_hom : tensor_hom_type tensor_obj) (assoc : assoc_obj tensor_obj) : Prop := ∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃), (tensor_hom (tensor_hom f₁ f₂) f₃) ≫ (assoc Y₁ Y₂ Y₃).hom = (assoc X₁ X₂ X₃).hom ≫ (tensor_hom f₁ (tensor_hom f₂ f₃)) def left_unitor_obj {C : Type u} [category.{u v} C] (tensor_obj : tensor_obj_type C) (tensor_unit : C) : Type (max u v) := Π X : C, (tensor_obj tensor_unit X) ≅ X def left_unitor_natural {C : Type u} [category.{u v} C] (tensor_obj : tensor_obj_type C) (tensor_hom : tensor_hom_type tensor_obj) (tensor_unit : C) (left_unitor : left_unitor_obj tensor_obj tensor_unit) : Prop := ∀ {X Y : C} (f : X ⟶ Y), (tensor_hom (𝟙 tensor_unit) f) ≫ (left_unitor Y).hom = (left_unitor X).hom ≫ f def right_unitor_obj {C : Type u} [category.{u v} C] (tensor_obj : tensor_obj_type C) (tensor_unit : C) : Type (max u v) := Π (X : C), (tensor_obj X tensor_unit) ≅ X def right_unitor_natural {C : Type u} [category.{u v} C] (tensor_obj : tensor_obj_type C) (tensor_hom : tensor_hom_type tensor_obj) (tensor_unit : C) (right_unitor : right_unitor_obj tensor_obj tensor_unit) : Prop := ∀ {X Y : C} (f : X ⟶ Y), (tensor_hom f (𝟙 tensor_unit)) ≫ (right_unitor Y).hom = (right_unitor X).hom ≫ f @[reducible] def pentagon {C : Type u} [category.{u v} C] {tensor_obj : tensor_obj_type C} (tensor_hom : tensor_hom_type tensor_obj) (assoc : assoc_obj tensor_obj) : Prop := ∀ W X Y Z : C, (tensor_hom (assoc W X Y).hom (𝟙 Z)) ≫ (assoc W (tensor_obj X Y) Z).hom ≫ (tensor_hom (𝟙 W) (assoc X Y Z).hom) = (assoc (tensor_obj W X) Y Z).hom ≫ (assoc W X (tensor_obj Y Z)).hom @[reducible] def triangle {C : Type u} [category.{u v} C] {tensor_obj : tensor_obj_type C} {tensor_unit : C} (tensor_hom : tensor_hom_type tensor_obj) (left_unitor : left_unitor_obj tensor_obj tensor_unit) (right_unitor : right_unitor_obj tensor_obj tensor_unit) (assoc : assoc_obj tensor_obj) : Prop := ∀ X Y : C, (assoc X tensor_unit Y).hom ≫ (tensor_hom (𝟙 X) (left_unitor Y).hom) = tensor_hom (right_unitor X).hom (𝟙 Y) end category_theory.monoidal
fd772c9724f5aec5c35b3787d26370a478750d75
649957717d58c43b5d8d200da34bf374293fe739
/src/category_theory/fully_faithful.lean
34cd797f2fc88a754da412864fcef4fd8a558749
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
3,005
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.isomorphism universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 class full (F : C ⥤ D) := (preimage : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), X ⟶ Y) (witness' : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), F.map (preimage f) = f . obviously) restate_axiom full.witness' attribute [simp] full.witness class faithful (F : C ⥤ D) : Prop := (injectivity' : ∀ {X Y : C} {f g : X ⟶ Y} (p : F.map f = F.map g), f = g . obviously) restate_axiom faithful.injectivity' namespace functor def injectivity (F : C ⥤ D) [faithful F] {X Y : C} {f g : X ⟶ Y} (p : F.map f = F.map g) : f = g := faithful.injectivity F p def preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : X ⟶ Y := full.preimage.{v₁ v₂} f @[simp] lemma image_preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : F.map (preimage F f) = f := by unfold preimage; obviously end functor variables {F : C ⥤ D} [full F] [faithful F] {X Y Z : C} def preimage_iso (f : (F.obj X) ≅ (F.obj Y)) : X ≅ Y := { hom := F.preimage f.hom, inv := F.preimage f.inv, hom_inv_id' := F.injectivity (by simp), inv_hom_id' := F.injectivity (by simp), } @[simp] lemma preimage_iso_hom (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).hom = F.preimage f.hom := rfl @[simp] lemma preimage_iso_inv (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).inv = F.preimage (f.inv) := rfl @[simp] lemma preimage_id : F.preimage (𝟙 (F.obj X)) = 𝟙 X := F.injectivity (by simp) @[simp] lemma preimage_comp (f : F.obj X ⟶ F.obj Y) (g : F.obj Y ⟶ F.obj Z) : F.preimage (f ≫ g) = F.preimage f ≫ F.preimage g := F.injectivity (by simp) @[simp] lemma preimage_map (f : X ⟶ Y) : F.preimage (F.map f) = f := F.injectivity (by simp) variables (F) def is_iso_of_fully_faithful (f : X ⟶ Y) [is_iso (F.map f)] : is_iso f := { inv := F.preimage (inv (F.map f)), hom_inv_id' := F.injectivity (by simp), inv_hom_id' := F.injectivity (by simp) } end category_theory namespace category_theory variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 instance full.id : full (functor.id C) := { preimage := λ _ _ f, f } instance : faithful (functor.id C) := by obviously variables {D : Type u₂} [𝒟 : category.{v₂} D] {E : Type u₃} [ℰ : category.{v₃} E] include 𝒟 ℰ variables (F : C ⥤ D) (G : D ⥤ E) instance faithful.comp [faithful F] [faithful G] : faithful (F ⋙ G) := { injectivity' := λ _ _ _ _ p, F.injectivity (G.injectivity p) } instance full.comp [full F] [full G] : full (F ⋙ G) := { preimage := λ _ _ f, F.preimage (G.preimage f) } end category_theory
d2ce3a744ee056ce08e7d44aa1f0d313d336bdf2
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Data/LOption.lean
ae29a55699af4d703f200e6e993fafd5698988c4
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,094
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.ToString universes u namespace Lean inductive LOption (α : Type u) | none {} : LOption | some : α → LOption | undef {} : LOption namespace LOption variables {α : Type u} instance : Inhabited (LOption α) := ⟨none⟩ instance [HasToString α] : HasToString (LOption α) := ⟨fun o => match o with | none => "none" | undef => "undef" | (some a) => "(some " ++ toString a ++ ")"⟩ def beq [HasBeq α] : LOption α → LOption α → Bool | none, none => true | undef, undef => true | some a, some b => a == b | _, _ => false instance [HasBeq α] : HasBeq (LOption α) := ⟨beq⟩ end LOption end Lean def Option.toLOption {α : Type u} : Option α → Lean.LOption α | none => Lean.LOption.none | some a => Lean.LOption.some a @[inline] def toLOptionM {α} {m : Type → Type} [Monad m] (x : m (Option α)) : m (Lean.LOption α) := do b ← x; pure b.toLOption